<?php
$vercode=''; //此处取值请自行修改
if(isset($_POST['vercode'])){
if ($_POST['vercode']!=$vercode){
 echo("[err]invalid vercode[/err]");
 exit();
}
}

define('SCR','post');
//if (isset($_POST['ajax']) && $_POST['ajax'] == 1) {
// define("AJAX",1);
//}

//require_once ('global.php');
//file_exists('install.php') && header('Location: ./install.php');
error_reporting(E_ERROR | E_PARSE);
function_exists('set_magic_quotes_runtime') && set_magic_quotes_runtime(0);
function_exists('date_default_timezone_set') && date_default_timezone_set('Etc/GMT+0');

define('R_P',getdirname(__FILE__));
define('D_P',R_P);
define('A_P', R_P.'apps/');
define('P_W','global');
defined('SCR') || define('SCR','other');

$P_S_T  = pwMicrotime();
require_once(R_P.'require/common.php');
S::filter();
require_once (D_P.'data/bbscache/baseconfig.php');
require_once D_P.'data/sql_config.php';
pwCache::getData(D_P.'data/bbscache/config.php');

define('AREA_PATH', R_P . $db_htmdir . '/channel/');
define('PORTAL_PATH', R_P . $db_htmdir . '/portal/');
$db_userurl = ($db_htmifopen && $db_userurlopen) ? 'u/' : 'u.php?uid='; //url
define('USER_URL',$db_userurl);

$db_debug && error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
//zzcity add
//$timestamp = time();
$zzhours = !isset($_POST['zzhours']) ? '1' : intval($_POST['zzhours']); 
$timestamp =time()-$zzhours*60*60;  //主题时间提前zzhour小时
$zzmins = !isset($_POST['zzmins']) ? '5' : intval($_POST['zzmins']);  //回帖时间随机分钟
$timestamp = $timestamp+((int)$_POST['replyno'])*$zzmins*60+(rand(1,$zzmins)*60);  //zzcity add
//zzdicy add end
$db_cvtime!=0 && $timestamp += $db_cvtime*60;
$wind_in = $SCR = SCR;

$onlineip = pwGetIp();
if ($db_forcecharset && !defined('W_P') && !defined('AJAX')) {
 @header("Content-Type:text/html; charset=$db_charset");
}
if ($db_loadavg && !defined('W_P') && pwLoadAvg($db_loadavg)) {
 $db_cc = 2;
}
if ($db_cc && !defined('COL')) {
 pwDefendCc($db_cc);
}

if ($db_htmifopen) {
	$_NGET = parseRewriteQueryString($pwServer['QUERY_STRING']);
	!empty($_NGET) && $_GET = $_NGET;
}

foreach ($_POST as $_key => $_value) {
	if (!in_array($_key,array('atc_content','atc_title','quote_content','prosign','pwuser','pwpwd'))) {
		S::checkVar($_POST[$_key]);
	}
}
foreach ($_GET as $_key => $_value) {
 S::checkVar($_GET[$_key]);
}

list($wind_version,$wind_repair,$wind_from) = explode(',',WIND_VERSION);
$db_olsize    = 96;

if (false !== ($dirstrpos = strpos($pwServer['SCRIPT_NAME'],$db_dir))) {
 $tmp = substr($pwServer['SCRIPT_NAME'],0,$dirstrpos);
 $pwServer['PHP_SELF'] = "$tmp.php";
 unset($dirstrpos);
} else {
 $tmp = $pwServer['SCRIPT_NAME'];
}
$REQUEST_URI = $pwServer['PHP_SELF'].($pwServer['QUERY_STRING'] ? '?'.$pwServer['QUERY_STRING'] : '');

$_mainUrl = $index_url = $db_bbsurl;
$R_url = $db_bbsurl = parseBbsUrl();

$defaultMode = empty($db_mode) ? 'bbs' : $db_mode;
$db_mode = 'bbs';

//二级域名绑定跳转
if (in_array(SCR, array('read', 'thread')) && $_mainUrl !== $db_bbsurl) {
	ObHeader($_mainUrl . substr($REQUEST_URI, strrpos($REQUEST_URI, '/')));
} elseif (SCR == 'u' && !empty($db_modedomain['o']) && $db_modedomain['o'] !== $pwServer['HTTP_HOST']) {
	ObHeader("http://" . $db_modedomain['o'] . substr($REQUEST_URI, strrpos($REQUEST_URI, '/')));
}

if ($cookie_lastvisit = GetCookie('lastvisit')) {
 list($c_oltime,$lastvisit,$lastpath) = explode("\t",$cookie_lastvisit);
 ($onbbstime=$timestamp-$lastvisit)<$db_onlinetime && $c_oltime+=$onbbstime;
 unset($cookie_lastvisit);
} else {
 $lastvisit = $lastpath = '';
 $c_oltime = $onbbstime = 0;
 Cookie('lastvisit',$c_oltime."\t".$timestamp."\t".$REQUEST_URI);
}

S::gp(array('fid','tid'),'GP',2);
//zzcity add
S::gp(array('fid'));

$zzfids=explode(',',$fid);
if (count($zzfids)>0){
 $fid=(int)$zzfids[rand(0,count($zzfids)-1)];
}else
{
 echo('[err]参数fid设置错误[/err]');
 exit;
}

//zzcity add end

#$db = $ftp = $credit = null;
$ftp = $credit = null;//distributed

!is_array($manager) && $manager = array();
$newmanager = array();
foreach ($manager as $key => $value) {
	if (!empty($value) && !is_array($value)) {
		$newmanager[$key] = $value;
	}
}
$manager = $newmanager;
if ($database == 'mysqli' && Pwloaddl('mysqli') === false) {
 $database = 'mysql';
}
ObStart();//noizy

if ($db_http != 'N') {
 $imgpath = $db_http;
 if (D_P != R_P) {
  $R_url = substr($db_http,-1)=='/' ?  substr($db_http,0,-1) : $db_http;
  $R_url = substr($R_url,0,strrpos($R_url,'/'));
 }
} else {
 $imgpath = $db_picpath;
}
list($attachpath,$imgdir,$attachdir,$pw_posts,$pw_tmsgs,$runfc) = array($db_attachurl != 'N' ? $db_attachurl : $db_attachname, R_P.$db_picpath, R_P.$db_attachname, 'pw_posts', 'pw_tmsgs', 'N');
list($winduid,$windpwd,$safecv) = explode("\t",addslashes(StrCode(GetCookie('winduser'),'DECODE')));

$loginhash = GetVerify($onlineip,$db_pptkey);
if ($db_pptifopen && $db_ppttype == 'client') {
 if (strpos($db_pptloginurl,'?') === false) {
  $db_pptloginurl .= '?';
 } elseif (substr($db_pptloginurl,-1) != '&') {
  $db_pptloginurl .= '&';
 }
 if (strpos($db_pptregurl,'?') === false) {
  $db_pptregurl .= '?';
 } elseif (substr($db_pptregurl,-1) != '&') {
  $db_pptregurl .= '&';
 }
 $urlencode = rawurlencode($db_bbsurl);
 $loginurl = "$db_pptserverurl/{$db_pptloginurl}forward=$urlencode";
 $loginouturl= "$db_pptserverurl/$db_pptloginouturl&forward=$urlencode&verify=$loginhash";
 $regurl  = "$db_pptserverurl/{$db_pptregurl}forward=$urlencode";
} else {
 $loginurl = 'login.php';
 $loginouturl= "login.php?action=quit&verify=$loginhash";
 $regurl  = $db_registerfile;
}

$ol_offset = (int)GetCookie('ol_offset');
$skinco    = GetCookie('skinco');

if ($db_refreshtime && SCR != 'register' && str_replace("=",'',$REQUEST_URI) == $lastpath && $onbbstime < $db_refreshtime) {
 !GetCookie('winduser') && $groupid = 'guest';
 $skin = $skinco ? $skinco : $db_defaultstyle;
 Showmsg('refresh_limit');
}
if (!$db_bbsifopen && !defined('CK')) {
 require_once(R_P.'require/bbsclose.php');
}

$H_url =& $db_wwwurl;
$B_url =& $db_bbsurl;
$_time  = array('hours'=>get_date($timestamp,'G'),'day'=>get_date($timestamp,'j'),'week'=>get_date($timestamp,'w'));
$tdtime  = PwStrtoTime(get_date($timestamp,'Y-m-d'));
$montime = PwStrtoTime(get_date($timestamp,'Y-m').'-1');

if (!defined('CK')) {
 switch (SCR) {
  case 'thread': $lastpos = "F$fid";break;
  case 'read': $lastpos = "T$tid";break;
  case 'cate': $lastpos = "C$fid";break;
  case 'index': $lastpos = 'index';break;
  case 'mode': $lastpos = $db_mode;break;
  default: $lastpos = 'other';
 }

 if ($timestamp-$lastvisit>$db_onlinetime || $lastpos != GetCookie('lastpos') || GetCookie('oltoken') == 'init') {
  $runfc = 'Y';
  Cookie('lastpos',$lastpos);
 }
}//zzcity add 用户登录
PwNewDB();
 $etuser = $db->get_one("SELECT uid,password FROM pw_members  WHERE username=".pwEscape($_POST['pwuser']));
 $winduid=$etuser['uid'];
 $windpwd=$etuser['password'];

//zzcity add end

if (is_numeric($winduid) && strlen($windpwd)>=16) {
 $winddb   = User_info();
 list($winduid,$groupid,$userrvrc,$windid,$_datefm,$_timedf,$credit_pop) = array($winddb['uid'],$winddb['groupid'],floor($winddb['rvrc']/10),$winddb['username'],$winddb['datefm'],$winddb['timedf'],$winddb['creditpop']);

	if ($credit_pop && $db_ifcredit) {//Credit Changes Tips
		$credit_pop = str_replace(array('&lt;', '&quot;', '&gt;'), array('<', '"', '>'), $credit_pop);
		list($tmpCreditPop, $creditOuterData) = array('', array());
		$creditOuterData = explode(',', $credit_pop);
		foreach ($creditOuterData as $value) {
			$creditdb = explode('|', $value);
			$tmpCreditPop .= ($tmpCreditPop ? '<br/>' : '') .  S::escapeChar(GetCreditLang('creditpop', $creditdb['0']));
			unset($creditdb['0']);
			foreach ($creditdb as $val) {
				list($credit_1, $credit_2) = explode(':', $val);
				$tmpCreditPop .= '<span class="w"><em class="mr5 b">'.pwCreditNames($credit_1).'</em><span class="f20">'.$credit_2.'</span></span>';
			}
		}
		$credit_pop = $tmpCreditPop;
		$userService = L::loadClass('UserService', 'user'); /* @var $userService PW_UserService */
		$userService->update($winduid, array(), array('creditpop' => ''));
 }

 list($winddb['style'],$ifcustomstyle) = explode('|',$winddb['style']);
 $skin   = $winddb['style'] ? $winddb['style'] : $db_defaultstyle;
 list($winddb['onlineip']) = explode('|',$winddb['onlineip']);
 $groupid == '-1' && $groupid = $winddb['memberid'];
 $winddb['lastpost'] < $tdtime && $winddb['todaypost'] = 0;
 $curvalue = $db_signcurtype == 'rvrc' ? $userrvrc : $winddb[$db_signcurtype];
 if (getstatus($winddb['userstatus'], PW_USERSTATUS_SHOWSIGN) && (!$winddb['starttime'] && $db_signmoney && strpos($db_signgroup,",$groupid,") !== false && $curvalue > $db_signmoney || $winddb['starttime'] && $winddb['starttime'] != $tdtime)) {
  require_once(R_P.'require/Signfunc.php');
  Signfunc($winddb['starttime'],$curvalue);
 }
 unset($curvalue);
} else {
 $skin  = $db_defaultstyle;
 $groupid = 'guest';
 $winddb  = $windid = $winduid = $_datefm = $_timedf = '';
}
$verifyhash = GetVerify($winduid);

if ($db_bbsifopen==2 && SCR!='login' && !defined('CK')) {
 require_once(R_P.'require/bbsclose.php');
}
if ($db_ifsafecv && !$safecv && !defined('PRO') && strpos($db_safegroup,",$groupid,") !== false ) {
 Showmsg('safecv_prompt');
}

pwCache::getData(D_P.'data/bbscache/inv_config.php'); 
if ($inv_linkopen && !$windid && (is_numeric($_GET['u']) || ($_GET['a'] && strlen(rawurldecode($_GET['a']))<16)) && strpos($pwServer['HTTP_REFERER'],$pwServer['HTTP_HOST']) === false) {
 S::gp(array('u','a'));
 if ($inv_linktype == 0) {
  $a = rawurldecode($a);
  require_once(R_P.'require/userads.php');
 } else {
  Cookie('userads',"$u\t$a\t".md5($pwServer['HTTP_REFERER']));
 }
}
unset($u,$a,$cookie_userads);

($_POST['skinco']) ? $skinco = $_POST['skinco'] : (($_GET['skinco']) ? $skinco = $_GET['skinco'] : '');
if ($skinco && strpos($skinco,'..')===false && file_exists(D_P."data/style/$skinco.php") ) {
 $skin = $skinco;
 Cookie('skinco',$skin);
}

if ($db_columns && !defined('W_P') && !defined('SIMPLE') && !defined('COL') && !defined('CK')) {
 $j_columns = GetCookie('columns');
 if (!$j_columns) {
  $db_columns==2 && $j_columns = 2;
  Cookie('columns',$j_columns);
 }
 if ($j_columns==2 && (strpos($pwServer['HTTP_REFERER'],$db_bbsurl)===false || strpos($pwServer['HTTP_REFERER'],$db_adminfile)!==false)) {
  strpos($REQUEST_URI,'index.php')===false ? Cookie('columns','1') : ObHeader('columns.php?action=columns');
 }
 unset($j_columns);
}
Ipban();

Cookie('lastvisit',$c_oltime."\t".$timestamp."\t".$REQUEST_URI);

if ($groupid == 'guest' && $db_guestdir && GetGcache()) {
 require_once(R_P.'require/guestfunc.php');
 getguestcache();
}
PwNewDB();
unset($db_whybbsclose,$db_whycmsclose,$db_ipban,$db_diy,$dbhost,$dbuser,$dbpw,$dbname,$pconnect,$manager_pwd,$newmanager);
if ($groupid == 'guest') {
	pwCache::getData(D_P.'data/groupdb/group_2.php');
} elseif (file_exists(D_P."data/groupdb/group_$groupid.php")) {
	pwCache::getData(S::escapePath(D_P."data/groupdb/group_$groupid.php"));
} else {
	pwCache::getData(D_P.'data/groupdb/group_1.php');
}
visitRightByGroup();
if ($_G['pwdlimitime'] && !defined('PRO') && !S::inArray($windid,$manager) && $timestamp-86400*$_G['pwdlimitime']>$winddb['pwdctime'] ) {
 Showmsg('pwdchange_prompt');
}

require_once(R_P.'lib/cloudwind/cloudwind.class.php');
$cloud_information = CloudWind::getUserInfo();
CloudWind::sendUserInfo($cloud_information);

//响应

/**
 * 跳转
 *
 * @global string $db_ifjump
 * @param string $URL 跳转url
 * @param string $content 跳转提示信息
 * @param int $statime 几秒后跳转
 * @param bool $forcejump
 */
function refreshto($URL, $content, $statime = 1, $forcejump = false) {
 if (defined('AJAX')) Showmsg($content);
 global $db_ifjump,$db_htmifopen;

 if (!$forcejump && !($db_ifjump && $statime > 0)) {
  ObHeader($URL);
 } else {
  if ($db_htmifopen && strtolower(substr($URL,0,4))!=='http') {
   $URL = urlRewrite($URL);
  }
  ob_end_clean();
  global $expires, $db_charset, $tplpath, $fid, $imgpath, $db_obstart, $db_bbsname, $B_url, $forumname, $tpctitle, $db_bbsurl;
  $index_name = & $db_bbsname;
  $index_url = & $B_url;
  ObStart(); //noizy
  extract(L::style());
  //css file for showmsg
  require (L::style('', $skinco, true));
  if ("wind" != $tplpath && file_exists(D_P.'data/style/'.$tplpath.'_css.htm')) {
   $css_path = D_P.'data/style/'.$tplpath.'_css.htm';
  } else{
   $css_path = D_P.'data/style/wind_css.htm';
  }
  //end css file
  $content = getLangInfo('refreshto', $content);
  if (defined('AREA_PAGE') && function_exists('areaLoadFrontView')) {
   require_once areaLoadFrontView('area_manage_refreshto');
  } else {
   require PrintEot('refreshto');
  }
  $output = str_replace(array('<!--<!---->', '<!---->', "\r\n\r\n"), '', ob_get_contents());
  echo ObContents($output);
  exit();
 }
}

/**
 * 302跳转
 *
 * @param string $url
 */
function ObHeader($URL){
 global $db_obstart,$db_bbsurl,$db_htmifopen;
 if ($db_htmifopen && strtolower(substr($URL,0,4))!=='http') {
  $URL = urlRewrite($URL);
 }
 ob_end_clean();
 if (!$db_obstart) {
  ObStart();
  echo "<meta http-equiv='refresh' content='0;url=$URL'>";
  exit;
 }
 header("Location: $URL");
 exit;
}
/**
 * 显示系统提示信息
 *
 * @param string $msg_info 信息内容
 * @param int $dejump ?
 */

//function Showmsg($msg_info, $dejump = 0) {
// @extract($GLOBALS, EXTR_SKIP);
// global $stylepath, $tablewidth, $mtablewidth, $tplpath, $db;
// define('PWERROR', 1);
// $msg_info = getLangInfo('msg', $msg_info);
// if (defined('AJAX')) {
//  echo $msg_info;
//  ajax_footer();
// }
// $showlogin = false;
// if ($dejump != '1' && $groupid == 'guest' && $REQUEST_URI == str_replace(array('register', 'login'), '', $REQUEST_URI) && (!$db_pptifopen || $db_ppttype != 'client')) {
//  if (strpos($REQUEST_URI, 'post.php') !== false || strpos($REQUEST_URI, 'job.php?action=vote') !== false || strpos($REQUEST_URI, 'job.php?action=pcjoin') !== false) {
//   $tmpTid = (int) S::getGP('tid', 'GP');
//   $tmpTid && $REQUEST_URI = substr($REQUEST_URI, 0, strrpos($REQUEST_URI, '/')) . "/read.php?tid=$tmpTid&toread=1";
//  }
//  $jumpurl = "http://" . $pwServer['HTTP_HOST'] . $REQUEST_URI;
//  //list(, $qcheck) = explode("\t", $db_qcheck);
//  $qkey = $db_ckquestion & 2 && $db_question ? array_rand($db_question) : '';
//  $showlogin = true;
// }
// extract(L::style());
// //css file for showmsg
// require (L::style('', $skinco, true));
// if ("wind" != $tplpath && file_exists(D_P.'data/style/'.$tplpath.'_css.htm')) {
//  $css_path = D_P.'data/style/'.$tplpath.'_css.htm';
// } else{
//  $css_path = D_P.'data/style/wind_css.htm';
// }
// //end css file
// list($_Navbar, $_LoginInfo) = pwNavBar();
// ob_end_clean();
// ObStart();
// /*
// if (defined('AREA_PAGE') && function_exists('areaLoadFrontView')) {
//  require_once areaLoadFrontView('area_manage_showmsg');exit;
// }*/
// require_once PrintEot('showmsg');
// exit();
//}

//zzcity add
function Showmsg($msg_info, $dejump = 0) {
 
 @extract($GLOBALS, EXTR_SKIP);
 global $stylepath, $tablewidth, $mtablewidth, $tplpath, $db;
 define('PWERROR', 1);
 $msg_info = getLangInfo('msg', $msg_info);
 //ob_end_clean();
 //ObStart();
 echo '[err]'.$msg_info.'[/err]';
 exit();
}
//zzcity add end


/**
 * 设置响应头
 *
 * @param int $num 响应状态码
 * @param bool $rtarr 是否返回响应头字符串
 * @return string
 */
function sendHeader($num, $rtarr = null) {
 static $sapi = null;
 if ($sapi === null) {
  $sapi = php_sapi_name();
 }
 $header_a = array('200' => 'OK', '206' => 'Partial Content', '304' => 'Not Modified', '404' => '404 Not Found',
  '416' => 'Requested Range Not Satisfiable');
 if ($header_a[$num]) {
  if ($sapi == 'cgi' || $sapi == 'cgi-fcgi') {
   $headermsg = "Status: $num " . $header_a[$num];
  } else {
   $headermsg = "HTTP/1.1: $num " . $header_a[$num];
  }
  if (empty($rtarr)) {
   header($headermsg);
  } else {
   return $headermsg;
  }
 }
 return '';
}

//全局业务
/**
 * 禁止ip
 *
 * @global string $db_ipban
 */
function Ipban() {
 global $db_ipban;
 if ($db_ipban) {
  global $onlineip, $imgpath, $stylepath;
  $baniparray = explode(',', $db_ipban);
  $ip = explode(".",$onlineip);
  if( in_array($ip[0],$baniparray) || in_array($ip[0].'.'.$ip[1],$baniparray) || in_array($ip[0].'.'.$ip[1].'.'.$ip[2],$baniparray) || in_array($ip[0].'.'.$ip[1].'.'.$ip[2].'.'.$ip[3],$baniparray)) {
   Showmsg('ip_ban');
  }
 }
}

//用户业务

/**
 * 获取用户信息
 */
function User_info() {
	global $db, $timestamp, $db_onlinetime, $winduid, $windpwd, $bday, $safecv, $db_ifonlinetime, $c_oltime, $onlineip, $db_ipcheck, $tdtime, $montime, $db_ifsafecv, $db_ifpwcache, $uc_server,$db_md_ifopen;
 PwNewDB();
 $detail = getUserByUid($winduid);
 if (empty($detail) && $uc_server) {
  require_once (R_P . 'require/ucuseradd.php');
 }
 $loginout = 0;
 if ($db_ipcheck && strpos($detail['onlineip'], $onlineip) === false) {
  $iparray = explode('.', $onlineip);
  strpos($detail['onlineip'], $iparray[0] . '.' . $iparray[1]) === false && $loginout = 1;
 }
//zzcity modi
// if (!$detail || PwdCode($detail['password']) != $windpwd || ($db_ifsafecv && $safecv != $detail['safecv']) || $loginout || $detail['yz'] > 1) {
//  $GLOBALS['groupid'] = 'guest';
//  require_once (R_P . 'require/checkpass.php');
//  Loginout();
//  if ($detail['yz'] > 1) {
//   $GLOBALS['jihuo_uid'] = $detail['uid'];
//   Showmsg('login_jihuo');
//  }
//  Showmsg('ip_change');
// } else {
  list($detail['shortcut'], $detail['appshortcut']) = explode("\t", $detail['shortcut']);
  unset($detail['password']);
  $detail['honor'] = substrs($detail['honor'], 90);
  $distime = $timestamp - $detail['lastvisit'];
  if ($distime > $db_onlinetime || $distime > 3600) {
   /*--- element update ---start*/
   if ($db_ifpwcache & 1 && SCR != 'post' && SCR != 'thread') {
    L::loadClass('elementupdate', '', false);
    $elementupdate = new ElementUpdate();
    $elementupdate->userSortUpdate($detail);
   }
   /*--- element update ---end*/
   if (!GetCookie('hideid')) {
    $userService = L::loadClass('UserService', 'user'); /* @var $userService PW_UserService */

    $updateMemberData = $updateByIncrementMemberData = array();
    $updateMemberData['lastvisit'] = $timestamp;
    $updateMemberData['thisvisit'] = $timestamp;

    if ($db_ifonlinetime) {
     $c_oltime = intval($c_oltime);
     $c_oltime = $c_oltime <= 0 ? 0 : ($c_oltime > $db_onlinetime * 1.2 ? $db_onlinetime : $c_oltime);
     $updateByIncrementMemberData['onlinetime'] = $c_oltime;
     if ($detail['lastvisit'] > $montime) {
      $updateByIncrementMemberData['monoltime'] = $c_oltime;
     } else {
      $updateMemberData['monoltime'] = $c_oltime;
     }
     if ($c_oltime) {
      require_once (R_P . 'require/functions.php');
      updateDatanalyse($winduid, 'memberOnLine', $c_oltime);
     }
     $c_oltime = 0;
    }
    if(get_date($timestamp,'Y-m-d') > get_date($detail['lastvisit'],'Y-m-d')){
     /*更新今日登录数*/
     $stasticsService = L::loadClass('Statistics', 'datanalyse');
     $stasticsService->login($winduid);
					/*连续登录天数*/
					if ($db_md_ifopen) {
						require_once(R_P.'require/functions.php');
						doMedalBehavior($winduid,'continue_login');
					}
    }
    $userService->update($winduid, array(), $updateMemberData);
    $updateByIncrementMemberData && $userService->updateByIncrement($winduid, array(), $updateByIncrementMemberData);

    $detail['lastvisit'] = $detail['thisvisit'] = $timestamp;
   }
  }
 //}
 return $detail;
}

/**
 * 检查用户是否为版块管理员
 *
 * @param string $forumAdmins 版块管理员
 * @param string $fupAdmins 父版块管理员
 * @param string $username 用户名
 * @return bool
 */
function admincheck($forumAdmins, $fupAdmins, $username) {
 if (!$username) {
  return false;
 }
 if ($forumAdmins && strpos($forumAdmins, ",$username,") !== false) {
  return true;
 }
 if ($fupAdmins && strpos($fupAdmins, ",$username,") !== false) {
  return true;
 }
 return false;
}

/**
 * 检查是否允许?
 *
 * @param string $allowGroups 允许的用户组
 * @param int $groupId 用户用户组
 * @param string $userGroups 用户的用户组
 * @param int|string $fid
 * @param string $allowForums 允许的论坛
 * @return bool
 */
function allowcheck($allowGroups, $groupId, $userGroups, $fid = '', $allowForums = '') {
 if ($allowGroups && strpos($allowGroups, ",$groupId,") !== false) {
  return true;
 }
 if ($allowGroups && $userGroups) {
  $groupIds = explode(',', substr($userGroups, 1, -1));
  foreach ($groupIds as $value) {
   if (strpos($allowGroups, ",$value,") !== false) {
    return true;
   }
  }
 }
 if ($fid && $allowForums && strpos(",$allowForums,", ",$fid,") !== false) {
  return true;
 }
 return false;
}

//在线用户业务

/**
 * 更新在线用户
 *
 * @global string $runfc
 * @global string $db_online
 */
function Update_ol() {
 global $runfc, $db_online;
 if ($runfc == 'Y') {
  if ($db_online) {
   Sql_ol();
  } else {
   Txt_ol();
  }
  $runfc = 'N';
 }
}

/**
 * 在线用户文本存储实现
 */
function Txt_ol() {
 global $ol_offset, $winduid, $db_ipstates, $isModify;
 require_once (R_P . 'require/userglobal.php');
 if ($winduid > 0) {
  list($alt_offset, $isModify) = addonlinefile($ol_offset, $winduid);
 } else {
  list($alt_offset, $isModify) = addguestfile($ol_offset);
 }
 $alt_offset != $ol_offset && Cookie('ol_offset', $alt_offset);
 $ipscookie = GetCookie('ipstate');
 if ($db_ipstates && ((!$ipscookie && $isModify === 1) || ($ipscookie && $ipscookie < $GLOBALS['tdtime']))) {
  require_once (R_P . 'require/ipstates.php');
 }
}

/**
 * 在线用户数据库存储实现
 */
function Sql_ol() {
 global $winduid, $timestamp, $db_onlinetime, $db_ipstates, $db_today, $lastvisit, $tdtime, $onlineip;
 $onlineService = L::loadClass('OnlineService', 'user');
 
 // 统计每日来访IP
 $ipscookie = GetCookie('ipstate');
 $guestInfo = $onlineService->getGuestInfo();
 if ($db_ipstates && (
 $ipscookie && $ipscookie < $GLOBALS['tdtime'] ||
 !$ipscookie && GetCookie('oltoken')=='init' && $onlineService->countOnlineGuestByIp($guestInfo['ip']) == 0 ||
 $guestInfo['ipchange'])) {
  require_once (R_P . 'require/ipstates.php');
 }
 
 // 统计每日来访会员
	if ($winduid && $db_today && $timestamp - $lastvisit > $db_onlinetime) {
  require_once (R_P . 'require/today.php');
 }
  
 // 更新在线信息
 if (!$_COOKIE || (GetCookie('oltoken') === null && !$winduid)){
  $onlineService->setGuestToken();
 }else {
  $winduid ? $onlineService->updateOnlineUser() : $onlineService->updateOnlineGuest();
 }
}


//论坛业务

/**
 * 判断
 *
 * @return bool
 */
function GetGcache() {
 global $db_fguestnum, $db_tguestnum, $db_guestindex,$defaultMode;
 $page = isset($GLOBALS['page']) ? (int)$GLOBALS['page'] : (int) $_GET['page'];
 if (SCR == 'thread' && $page < $db_fguestnum && !isset($_GET['type']) && !S::getGP('search')) {
  return true;
 } elseif (SCR == 'read' && $page < $db_tguestnum && !isset($_GET['uid'])) {
  return true;
 } elseif (SCR == 'index' && $db_guestindex && !isset($_GET['cateid']) && (($defaultMode=='bbs' && !$_GET['m']) || $_GET['m']=='bbs')) {
  return true;
 }
 return false;
}

/**
 * 获取版块短名
 *
 * @global array $winddb
 * @global array $forum
 * @global string $winduid
 * @global string $db_shortcutforum
 * @return array
 */
function pwGetShortcut() {
 static $sForumsShortcut = array();
 if (empty($sForumsShortcut)) {
  global $winduid, $db_shortcutforum;
  $sForumsShortcut = pwGetMyShortcut();
  if (empty($sForumsShortcut)) {
   if (!$db_shortcutforum && $winduid) {
    require_once (R_P . 'require/updateforum.php');
    updateshortcut();
    //$sForumsShortcut = updateshortcut();
   } 
  }
 }
 /*侧栏 等处因删除无权查看的隐藏板块*/
 global $winddb, $forum ,$groupid,$windid;
 extract(pwCache::getData(D_P . 'data/bbscache/forum_cache.php', false));
 foreach($sForumsShortcut as $k=>$v){
  if($forum[$k]['f_type'] == 'hidden'
   && (!allowcheck($forum['allowvisit'], $groupid, $winddb['groups'], $forum['fid'], $winddb['visit']) && !S::inArray($windid, $manager))) {
    unset($sForumsShortcut[$k]);
  }
 }
 return $sForumsShortcut;
}

function pwGetMyShortcut(){
 static $sMyForumsShortcut = array();
 if (empty($sMyForumsShortcut)) {
  global $winddb, $forum;
  if (trim($winddb['shortcut'], ',')) {
   if (!isset($forum)) {
    extract(pwCache::getData(D_P . 'data/bbscache/forum_cache.php', false));
   }
   $shortcuts = explode(',', $winddb['shortcut']);
   foreach ($shortcuts as $value) {
    if ($value && isset($forum[$value])) {
     $sMyForumsShortcut[$value] = strip_tags($forum[$value]['name']);
    }
   }
  }
 }
 return $sMyForumsShortcut;
}

//任务调度业务

/**
 * 运行任务调度
 */
function runTask() {
 $taskClass = L::loadclass('task', 'task');
 $taskClass->run();
}

//任务系统业务

/**
 * 运行用户任务系统
 *
 * @global string $db_job_isopen
 * @global int $winduid
 * @global int $groupid
 */
function runJob() {
 global $db_job_isopen, $winduid, $groupid;
 if (!$db_job_isopen || !$winduid) {
  return;
 }
 $taskClass = L::loadclass('autojob', 'job');
 $taskClass->run($winduid, $groupid);
}

//模式

/**
 * 选择模式
 *
 * @param string $modeName 模式名
 */
function selectMode(&$modeName,$controll = '') {
	global $defaultMode, $db_mode, $db_modes, $db_modepages, $pwServer, $db_modedomain, $REQUEST_URI, $_mainUrl;
 if (defined('M_P'))
  return;
 if (in_array(SCR, array('index', 'mode'))) {
  $db_mode = $defaultMode;
  if (!$modeName && $db_modedomain) {
   $modeName = array_search($pwServer['HTTP_HOST'], $db_modedomain);
  }
  if ($db_modes && isset($db_modes[$modeName]) && is_array($db_modes[$modeName]) && ($db_modes[$modeName]['ifopen'] || ($modeName == 'area' && in_array($controll,array('manage','dialog'))))) {
   $db_mode = $modeName;
  }
  if (!empty($db_mode) && $db_mode != 'bbs' && file_exists(R_P . "mode/$db_mode/")) {
   define('M_P', R_P . "mode/$db_mode/");
   $db_modepages = $db_modepages[$db_mode];
   $GLOBALS['pwModeImg'] = "mode/$db_mode/images";
		}
		//二级域名绑定跳转
		if (defined('M_P') && !defined('HTML_CHANNEL') && !empty($db_modedomain[$db_mode]) && $db_modedomain[$db_mode] !== $pwServer['HTTP_HOST']) {
			ObHeader('http://' . $db_modedomain[$db_mode] . substr($REQUEST_URI, strrpos($REQUEST_URI, '/')));
  }
 }
}

/**
 * 获取二级域名 //TODO 没有被调用
 *
 * @param string $url
 * @param string $mainUrl
 * @return string
 */
function getSecDomain($url, $mainUrl = null) {
 global $pwServer;
 if ($mainUrl && $url == $mainUrl) {
  return '';
 }
 $dirname = substr($pwServer['HTTP_HOST'], 0, strpos($pwServer['HTTP_HOST'], '.'));
 if (preg_match('/[^\w]' . $dirname . '\./i', $mainUrl)) {
  return '';
 }
 return $dirname;
}

//语言包

/**
 * 获取语言包文件路径
 *
 * @param string $lang 语言文件包名
 * @param string $EXT 扩展名
 */
function GetLang($lang, $EXT = 'php') {
 global $tplpath;
 
 if (file_exists(R_P . "template/$tplpath/lang_$lang.$EXT")) {
  return R_P . "template/$tplpath/lang_$lang.$EXT";
 } elseif (file_exists(R_P . "template/wind/lang_$lang.$EXT")) {
  return R_P . "template/wind/lang_$lang.$EXT";
 } else {
  exit("Can not find lang_$lang.$EXT file");
 }
}

//模板


/**
 * 获取模板文件路径
 *
 * @global string $db_mode
 * @global array $db_modes //TODO 未使用
 * @global string $pwModeImg
 * @global string $db_tplstyle
 * @global string $appdir
 * @global array $tplapps
 * @global string $db_tplpath
 * @param string $template 模板文件名
 * @param string $EXT 扩展名
 * @return string
 */
function PrintEot($template, $EXT = 'htm') {
 !$template && $template = 'N';
 static $bbsTemplate = null;
 isset($bbsTemplate) || $bbsTemplate = new template(new bbsTemplate());
 return $bbsTemplate->printEot($template, $EXT);

 global $db_mode, $db_modes, $pwModeImg, $db_tplstyle, $appdir;
 !$template && $template = 'N';

 
 if (!defined('PWERROR')) { //apps template render
  //zhudong 通过判断模板名称为'm_'开头的调用apps目录下的模板
  if (defined('A_P') && $appdir && substr($template,0,2) == 'm_' && file_exists(A_P . "$appdir/template/$template.$EXT")) {
   return S::escapePath(A_P . "$appdir/template/$template.$EXT");
  }
  if (defined('F_M')/* || ($db_mode && $db_mode != 'bbs')*/) {
   $temp = modeEot($template, $EXT);
   if ($temp)
    return S::escapePath($temp);
  }
 }
 //if (defined('A_P') && !in_array($template,array('header','footer'))/* || ($db_mode && $db_mode != 'bbs')*/) {
 // return A_P."$appdir/template/$template.$EXT";
 //}
 if (file_exists(R_P . "template/$tplpath/$template.$EXT")) {
  return S::escapePath(R_P . "template/$tplpath/$template.$EXT");
 } elseif (file_exists(R_P . "template/wind/$template.$EXT")) {
  return S::escapePath(R_P . "template/wind/$template.$EXT");
 } else {
  exit("Can not find $template.$EXT file");
 }
}


/**
 * 输出页脚，并处理输出缓存中的内容
 */
function footer() {
 global $db, $db_obstart, $db_footertime, $P_S_T, $mtablewidth, $db_ceoconnect, $wind_version, $imgpath, $stylepath, $footer_ad, $db_union, $timestamp, $db_icp, $db_icpurl, $db_advertdb, $groupid, $db_ystats_ifopen, $db_ystats_unit_id, $db_ystats_style, $pwServer, $db_ifcredit, $credit_pop, $db_foot, $db_mode, $db_modes, $shortcutforum, $_G, $winddb, $db_toolbar, $winduid, $db_menuinit, $db_appifopen, $db_job_ispop, $db_job_isopen, $db_siteappkey, $_Navbar,$db_statscode;

 defined('AJAX') && ajax_footer();

 $wind_spend = '';

 //$db_statscode = html_entity_decode($db_statscode);
 $ft_gzip = ($db_obstart ? 'Gzip enabled' : 'Gzip disabled') . $db_union[3];
 if ($db_footertime == 1) {
  $totaltime = number_format((pwMicrotime() - $P_S_T), 6);
  $qn = $db ? $db->query_num : 0;
  $wind_spend = "Total $totaltime(s) query $qn,";
  
 }
 $ft_time = get_date($timestamp, 'm-d H:i');
 $db_icp && $db_icp = "<a href=\"http://www.miibeian.gov.cn\" target=\"_blank\">$db_icp</a>";

 if ($db_toolbar) {
  if ($_COOKIE['toolbarhide']) {
   $toolbarstyle = 'style="display:none"';
   $openbarstyle = '';
   $closebarstyle = 'style="display:none"';
  } else {
   $toolbarstyle = '';
   $openbarstyle = 'style="display:none"';
   $closebarstyle = '';
   if ($db_appifopen) {
    $appshortcut = trim($winddb['appshortcut'], ',');
    if (!empty($appshortcut) && $db_siteappkey) {
     $appshortcut = explode(',', $appshortcut);
     $bottom_appshortcut = array();
     $appclient = L::loadClass('appclient');
     $bottom_appshortcut = $appclient->userApplist($winduid, $appshortcut, 1);
    }
   }
  }
 }
 $db_menuinit = trim($db_menuinit, ',');

 runJob();

 require PrintEot('footer');
 if ($db_advertdb['Site.PopupNotice'] || $db_advertdb['Site.FloatLeft'] || $db_advertdb['Site.FloatRight'] || $db_advertdb['Site.FloatRand']) {
  require PrintEot('advert');
 }
 pwOutPut();
}

function pwOutPut() {
 global $db_htmifopen, $db_redundancy, $SCR, $groupid;
	$masterDb = $GLOBALS['db']->getMastdb();
	if ($masterDb->arr_query) {
		writeover(D_P . "data/sqllist.txt", $masterDb->arr_query, 'wb');
	}
 Update_ol();
 $output = parseHtmlUrlRewrite(ob_get_contents(), $db_htmifopen);
 if ($db_redundancy && $SCR != 'post') {
  $output = str_replace(array("\r", '<!--<!---->-->', '<!---->-->', '<!--<!---->', "<!---->\n", '<!---->', '<!-- -->', "<!--\n-->", "\t\t", '    ', "\n\t", "\n\n"), array('', '', '', '', '', '', '', '', '', '',"\n", "\n"), $output);
 } else {
  $output = str_replace(array('<!--<!---->-->','<!---->-->', '<!--<!---->', "<!---->\r\n", '<!---->', '<!-- -->', "\t\t\t"), '', $output);
 }
 if ($SCR != 'post' && !defined('AJAX')) {
  $ceversion = defined('CE') ? 1 : 0;
		$output .= "<script type=\"text/javascript\">(function(d,t){
var url=\"http://init.phpwind.net/init.php?sitehash={$GLOBALS[db_sitehash]}&v={$GLOBALS[wind_version]}&c=$ceversion\";
var g=d.createElement(t);g.async=1;g.src=url;d.body.appendChild(g)}(document,\"script\"));</script>";
 }
 if ($groupid == 'guest' && !defined('MSG') && GetGcache()) {
  require_once (R_P . 'require/guestfunc.php');
  creatguestcache($output);
 }
 if (defined('SHOWLOG')) Error::writeLog();
 if (defined('PW_PACK_FILES')) pwPack::files();
 echo ObContents($output);
 unset($output);
 N_flush();
 exit();
}

/**
 * 获取目录路径
 *
 * @param string $path 文件路径
 * @return string
 */
function getdirname($path = null) {
 if (!empty($path)) {
  if (strpos($path, '\\') !== false) {
   return substr($path, 0, strrpos($path, '\\')) . '/';
  } elseif (strpos($path, '/') !== false) {
   return substr($path, 0, strrpos($path, '/')) . '/';
  }
 }
 return './';
}

/**
 * 设置状态
 *
 * @param int $status
 * @param int $b
 * @param string $setv
 */
function setstatus(&$status, $b, $setv = '1') {
 --$b;
 for ($i = strlen($setv) - 1; $i >= 0; $i--) {
  if ($setv[$i]) {
   $status |= 1 << $b;
  } else {
   $status &= ~(1 << $b);
  }
  ++$b;
 }
 //return $status;
}


//安全

/**
 * 获取客户端唯一hash
 *
 * @param string $str 附加信息
 * @param string $app
 * @return string
 */
function GetVerify($str, $app = null) {
 empty($app) && $app = $GLOBALS['db_siteid'];
 return substr(md5($str . $app . $GLOBALS['pwServer']['HTTP_USER_AGENT']), 8, 8);
}
/**
 * POST请求检查
 *
 * @global array $pwServer
 * @param int $checkHash 是否检查请求hash
 * @param int $checkGd 是否检查验证码
 * @param int $checkQuestion 是否检查安全问题
 * @param int $checkReferer 是否检查refer
 */
function PostCheck($checkHash = 1, $checkGd = 0, $checkQuestion = 0, $checkReferer = 1) {
 global $pwServer;
 $checkHash && checkVerify();
 if ($checkReferer && $pwServer['REQUEST_METHOD'] == 'POST') {
  $refererParsed = @parse_url($pwServer['HTTP_REFERER']);
  if ($refererParsed['host']) {
   list($httpHost) = explode(':', $pwServer['HTTP_HOST']);
   if ($refererParsed['host'] != $httpHost) {
    Showmsg('undefined_action');
   }
  }
 }
 $checkGd && GdConfirm($_POST['gdcode']);
 $checkQuestion && Qcheck($_POST['qanswer'], $_POST['qkey']);
}
/**
 * 校验请求的hash字符串
 *
 * @param string $hash 系统hash的key
 */
function checkVerify($hash = 'verifyhash') {
 //zzcity modi
// S::getGP('verify') != $GLOBALS[$hash] && Showmsg('illegal_request');
}


/**
 * 校验验证码
 *
 * @param string $code
 */
function GdConfirm($code,$bool = null) {
 Cookie('cknum', '', 0);
 if (!$code || !SafeCheck(explode("\t", StrCode(GetCookie('cknum'), 'DECODE')), strtoupper($code), 'cknum', 1800)) {
  if($bool){
   return false;
  }else{
   Showmsg('check_error');
  }
 }
 return true;
}

/**
 * 随机机器问题1
 * @param boolean $setCookie
 */
function getMachineQuestion_1($setCookie = true){
 global $timestamp;
 $alg = mt_rand(0,1);//+-
 $num1 = mt_rand(1,100);
 switch($alg){
  case 0:
   $num2 = mt_rand(0,100-$num1);
   $symbol = '+';
   $answer = $num1 + $num2;
   break;
  case 1:
   $num2 = mt_rand(0,$num1);
   $symbol = '-';
   $answer = $num1 - $num2;
   break;
 }
	$setCookie && Cookie('ckquestion',StrCode($timestamp."\t\t".md5($answer.$timestamp . getHashSegment())));
 return sprintf('%s %s %s = ?',$num1,$symbol,$num2);
}
/**
 * 校验问题
 *
 * @global string $db_question
 * @global array $db_answer
 * @param string $answer 答案
 * @param string $qkey
 */
function Qcheck($answer, $qkey, $return = false) {
	global $db_question, $db_answer;
	$answer = trim($answer);
	if($qkey < 0){
		//机选问题
		//Cookie('ckquestion', '', 0);
		if(!is_string($answer) || $answer === '' || !SafeCheck(explode("\t", StrCode(GetCookie('ckquestion'), 'DECODE')), $answer, 'ckquestion', 1800 , false ,false)){
			if ($return) return false;
			Showmsg('qcheck_error');
		}
	}elseif($db_question && (!isset($db_answer[$qkey]) || $answer != $db_answer[$qkey])){
		if ($return) return false;
		Showmsg('qcheck_error');
	}
	if ($return) return true;
}

//数据库

//系统
/**
 * 加载扩展
 *
 * @param string $module 扩展模块名
 * @param string $checkFunction 检测函数
 * @return bool
 */
function Pwloaddl($module, $checkFunction = 'mysqli_get_client_info') {
 return extension_loaded($module) && $checkFunction && function_exists($checkFunction) ? true : false;
}

/**
 * 操作加锁
 *
 * @param string $action 操作名
 * @param int $uid
 * @return bool 是否成功
 */
function procLock($action, $uid = 0) {
 global $db, $timestamp;
 if ($db->query("INSERT INTO pw_proclock (uid,action,time) VALUES ('$uid','$action','$timestamp')", 'U', false)) {
  return true;
 }
 $db->update("DELETE FROM pw_proclock WHERE uid='$uid' AND action='$action' AND time < '$timestamp' - 30");
 return false;
}

/**
 * 操作解锁
 *
 * @param string $action 操作名
 * @param int $uid
 */
function procUnLock($action = '', $uid = 0) {
 $GLOBALS['db']->update("DELETE FROM pw_proclock WHERE uid='$uid' AND action='$action'");
}

/**
 * 获取微妙时间
 *
 * performance 2010-2-10
 * @return float
 */
function pwMicrotime() {
 $t_array = explode(' ', microtime());
 return $t_array[0] + $t_array[1];
}

/**
 * 生成导航条信息
 *
 * @return array
 */
function pwNavBar() {
 global $winduid, $db_mainnav, $db_menu, $groupid, $winddb, $SCR, $db_modes, $db_mode, $defaultMode, $db_menuinit;
 global $alias;

 $tmpLogin = $tmpNav = array();
 if ($groupid != 'guest') {
  require_once (R_P . 'require/showimg.php');
  list($tmpLogin['faceurl']) = showfacedesign($winddb['icon'], 1, 's');
  $tmpLogin['lastlodate'] = get_date($winddb['lastvisit'], 'Y-m-d');
 } else {
  global $db_question, $db_logintype, $db_qcheck,$db_ckquestion;
  if ($db_question) {
   list(,$tmpLogin['showq']) = explode("\t", $db_qcheck);
   $tmpLogin['qcheck'] = $db_ckquestion & 2;
   if ($tmpLogin['qcheck'])
    $tmpLogin['qkey'] = array_rand($db_question);
  }
  if ($db_logintype) {
   for ($i = 0; $i < 3; $i++) {
    if ($db_logintype & pow(2, $i))
     $tmpLogin['logintype'][] = $i;
   }
  } else {
   $tmpLogin['logintype'][0] = 0;
  }
 }
 $postion = $db_mode;

 if (defined('APP_GROUP')) $postion = 'group';  //群组定位特殊处理
 $currentPostion = array();
 $currentPostion['mode'] = $postion;
 if (in_array(SCR, array('index', 'cate', 'mode', 'read', 'thread')) || $SCR == 'm_home') {
  $currentPostion['mode'] = empty($postion) ? 'bbs' : $postion;
 }
 if ($currentPostion['mode'] == 'area' && $alias) $currentPostion['alias'] = $alias;
 $navConfigService = L::loadClass('navconfig', 'site'); /* @var $navConfigService PW_NavConfig */
 $tmpNav[PW_NAV_TYPE_MAIN] = $navConfigService->findValidNavListByTypeAndPostion(PW_NAV_TYPE_MAIN, $postion, $currentPostion);
 $tmpNav[PW_NAV_TYPE_HEAD_LEFT] = $navConfigService->findValidNavListByTypeAndPostion(PW_NAV_TYPE_HEAD_LEFT, $postion);
 $tmpNav[PW_NAV_TYPE_HEAD_RIGHT] = $navConfigService->findValidNavListByTypeAndPostion(PW_NAV_TYPE_HEAD_RIGHT, $postion);
 $tmpNav[PW_NAV_TYPE_FOOT] = $navConfigService->findValidNavListByTypeAndPostion(PW_NAV_TYPE_FOOT, $postion);

 return array($tmpNav, $tmpLogin);
}

/**
 * 生成导航html
 *
 * @param array $navData 导航配置数据数组
 */
function buildNavLinkHtml($navData) {
 $title = strip_tags($navData['title']);
 $navData['style']['b'] && $title = "<b>$title</b>";
 $navData['style']['i'] && $title = "<span style=\"font-style:oblique\">$title</span>";
 $navData['style']['u'] && $title = "<u>$title</u>";
 $navData['style']['color'] && $title = "<font color=\"".$navData['style']['color']."\">$title</font>";

 $target = $navData['target'] ? 'target="_blank"' : '';
 return '<a id="nav_key_up_'.$navData['nid'].'" href="'.$navData['link'].'" title="'.$navData['alt'].'" '.$target.'>'.$title.'</a>';
}

/**
 * 根据用户组来判断站点访问权限
 */
function visitRightByGroup() {
 global $_G, $groupid, $manager, $windid, $pwServer;

 if (defined('CK') && CK == 1) return;
 if (S::inArray(SCR,array('sendpwd', 'login', 'register', 'job'))) {
  $action = S::getGP('action');
  if (SCR !== 'job' || $pwServer['HTTP_USER_AGENT'] == 'Shockwave Flash' && S::inArray($action, array('mutiupload', 'mutiuploadphoto', 'uploadicon'))) return;
 }

 if (empty($_G['allowvisit'])) {
  if (empty($groupid) || $groupid == 'guest') {
   if (defined('AJAX') && $_GET['action'] == 'pwschools') return;
   ObHeader('login.php');
  } elseif (!S::inArray($windid, $manager)) {
   @extract($GLOBALS, EXTR_SKIP);
   require_once (R_P.'header.php');
   require_once PrintEot('error');
   footer();
  }
 }
}

function parseRewriteQueryString($queryString){
	global $db_ext;
	$_NGET = array();
	$self_array = false !== strpos($queryString, '&') ? array() : explode('-',substr($queryString,0,strpos($queryString,$db_ext)));
	for ($i=0, $s_count=count($self_array); $i<$s_count-1;$i++) {
		$_key	= $self_array[$i];
		$_value	= rawurldecode($self_array[++$i]);
		$_NGET[$_key] = addslashes($_value);
	}
	return $_NGET;
}

/**
 * 解析替换$db_bbsurl 多站点二级域名,有端口情况
 */
function parseBbsUrl() {
	global $db_bbsurl,$pwServer;
	$bbsurlArray = parse_url($db_bbsurl);
	$parsePort = '';
	if (strrpos($db_bbsurl, ':') !== false && strrpos($pwServer['HTTP_HOST'], ':') !== false) {
		$parsePort = ':'.$bbsurlArray['port'];
	}
	return S::escapeChar(str_replace($bbsurlArray['host'].$parsePort,$pwServer['HTTP_HOST'],$db_bbsurl));
}
class bbsTemplate {

 var $dir;

 function bbsTemplate() {
  $this->dir = R_P . 'template/';
 }

 function getpath($template, $EXT = 'htm') {
  if (!defined('PWERROR')) {
   global $appdir;
   if (defined('A_P') && $appdir && substr($template,0,2) == 'm_' && file_exists(A_P . "$appdir/template/$template.$EXT")) {
    return S::escapePath(A_P . "$appdir/template/$template.$EXT");
   }
   if (defined('F_M')/* || ($db_mode && $db_mode != 'bbs')*/) {
    $temp = modeEot($template, $EXT);
    if ($temp)
     return S::escapePath($temp);
   }
  }
  $tplpath = L::style('tplpath');
  if (file_exists($this->dir . "$tplpath/$template.$EXT")) {
   return $this->dir . "$tplpath/$template.$EXT";
  }
  if (file_exists($this->dir . "wind/$template.$EXT")) {
   return $this->dir . "wind/$template.$EXT";
  }
  return false;
 }

 function getDefaultDir() {
  return $this->dir . 'wind/';
 }
}


//global.php结束

L::loadClass('forum', 'forum', false);
L::loadClass('post', 'forum', false);
//* include_once pwCache::getPath(D_P.'data/bbscache/cache_post.php');
pwCache::getData(D_P.'data/bbscache/cache_post.php');
/**
* 版块缓冲文件
*/
//empty($fid) && Showmsg('undefined_action');
empty($fid) && exit('[err]参数fid不能为空[/err]'); //zzcity add

$pwforum = new PwForum($fid);
$pwpost  = new PwPost($pwforum);
if (!S::inArray($windid, $manager)) {
 $pwpost->forumcheck();
 $pwpost->postcheck();
}

list($uploadcredit,$uploadmoney,,) = explode("\t", $pwforum->forumset['uploadset']);

$foruminfo =& $pwforum->foruminfo;
$forumset =& $pwforum->forumset;
if ($forumset['link']) {
// Showmsg('本版块为外链版块，禁止发帖');
exit('[err]本版块为外链版块，禁止发帖[/err]'); //zzcity add
}
S::gp(array('action','article','pid','page'));
S::gp(array('special','modelid','pcid', 'cyid','actmid'),GP,2);
$replacedb = array();
$secondurl = "thread.php?fid=$fid";
!$action && $action = "new";  
$replayorder_default = 'checked';
if ($action == 'new') {

 $theSpecialFlag = false;//是否是特殊帖子（分类、团购、活动）
 if ($modelid > 0) {/*主题分类*/
  L::loadClass('posttopic', 'forum', false);
  $postTopic = new postTopic($pwpost);
//  if (!$_G['allowmodelid']) {
//   Showmsg('post_allowpost');
//  }
  if (strpos(",".$pwforum->foruminfo['modelid'].",",",".$modelid.",") === false) {
   Showmsg('forum_model_undefined');
  }
  if (!$postTopic->topiccatedb[$postTopic->topicmodeldb[$modelid]['cateid']]['ifable']) {
   Showmsg('topic_cate_unable');
  }
  !$postTopic->topicmodeldb[$modelid]['ifable'] && Showmsg('topic_model_unable');
  $special = $pcid = $actmid = 0;
  $theSpecialFlag = true;
 } elseif ($pcid > 0) {/*团购*/
  L::loadClass('postcate', 'forum', false);
  $postCate = new postCate($pwpost);
  if (strpos(",".$pwforum->foruminfo['pcid'].",",",".$pcid.",") === false) {
   Showmsg('post_allowtype');
  }
  if (!$postCate->postcatedb[$pcid]['ifable']) {
   Showmsg('forum_pc_undefined');
  }
//  if (strpos(",".$_G['allowpcid'].",",",".$pcid.",") === false) {
//   Showmsg('post_allowpost');
//  }
  $special = $modelid = $actmid = 0;
  $theSpecialFlag = true;
 } elseif ($actmid > 0) {/*活动分类*/
  L::loadClass('ActivityForBbs', 'activity', false);
  $postActForBbs = new PW_ActivityForBbs($pwpost);
//  if (!$_G['allowactivity']) {
//   Showmsg('post_allowpost');
//  }
  if (strpos(",".$pwforum->foruminfo['actmids'].",",",".$actmid.",") === false) {
   Showmsg('forum_model_undefined');
  }
  if (!$postActForBbs->activitycatedb[$postActForBbs->activitymodeldb[$actmid]['actid']]['ifable']) {
   Showmsg('topic_cate_unable');
  }
  !$postActForBbs->activitymodeldb[$actmid]['ifable'] && Showmsg('topic_model_unable');
  $special = $pcid = $modelid = 0;
  $theSpecialFlag = true;
 } elseif (!($pwforum->foruminfo['allowtype'] & pow(2,$special))) {
  $modelid = $pcid = $actmid = 0;
  if (empty($special) && $pwforum->foruminfo['allowtype'] > 0) {
   $special = (int)log($pwforum->foruminfo['allowtype'],2);
  } elseif ($pwforum->foruminfo['modelid'] || $pwforum->foruminfo['pcid'] || $pwforum->foruminfo['actmids']) {
   L::loadClass('posttopic', 'forum', false);
   $postTopic = new postTopic($pwpost);
   $modeliddb = explode(",",$pwforum->foruminfo['modelid']);
 
   /*判断分类信息是否存在*/
   foreach ($modeliddb as $value) {
    if ($postTopic->topiccatedb[$postTopic->topicmodeldb[$value]['cateid']]['ifable'] && $_G['allowmodelid'] && $postTopic->topicmodeldb[$value]['ifable']) {
     $modelid = $value;
     $theSpecialFlag = true;
     break;
    }
   }

   /*判断团购是否存在*/
   if (!$modelid) {
    L::loadClass('postcate', 'forum', false);
    $postCate = new postCate($pwpost);
    $pciddb = explode(",",$pwforum->foruminfo['pcid']);
   
    foreach ($pciddb as $value) {
     if ($postCate->postcatedb[$value]['ifable'] && strpos(",".$_G['allowpcid'].",",",".$value.",") !== false) {
      $theSpecialFlag = true;
      $pcid = $value;
      break;
     }
    }
   }

   /*判断活动是否存在*/
   if (!$pcid && !$modelid) {
    L::loadClass('ActivityForBbs', 'activity', false);
    $postActForBbs = new PW_ActivityForBbs($pwpost);

    $actmiddb = explode(",",$pwforum->foruminfo['actmids']);
    foreach ($actmiddb as $value) {
     if ($postActForBbs->activitycatedb[$postActForBbs->activitymodeldb[$value]['actid']]['ifable'] && $_G['allowactivity'] && $postActForBbs->activitymodeldb[$value]['ifable']) {
      $actmid = $value;
      $theSpecialFlag = true;
      break;
     }
    }
    if (!$actmid) {
     Showmsg('post_allowtype');
    }
   }
  } else {
   Showmsg('post_allowtype');
  }

 }
}

/**
* 禁止受限制用户发言
*/
//if ($groupid == 6 || getstatus($winddb['userstatus'], PW_USERSTATUS_BANUSER)) {
// $flag  = 0;
// $bandb = $delban = array();
// $query = $db->query("SELECT * FROM pw_banuser WHERE uid=".pwEscape($winduid));
// while ($rt = $db->fetch_array($query)) {
//  if ($rt['type'] == 1 && $timestamp - $rt['startdate'] > $rt['days']*86400) {
//   $delban[] = $rt['id'];
//  } elseif ($rt['fid'] == 0 || $rt['fid'] == $fid) {
//   $bandb[$rt['fid']] = $rt;
//  } else {
//   $flag = 1;
//  }
// }
// $delban && $db->update('DELETE FROM pw_banuser WHERE id IN('.pwImplode($delban).')');
//
// $updateUser = array();
// if ($groupid == 6 && !isset($bandb[0])) {
//  $updateUser['groupid'] = -1;
// }
// if (getstatus($winddb['userstatus'], PW_USERSTATUS_BANUSER) && !isset($bandb[$fid]) && !$flag) {
//  $userService = L::loadClass('UserService', 'user'); /* @var $userService PW_UserService */
//  $userService->setUserStatus($winduid, PW_USERSTATUS_BANUSER, false);
// }
// if (count($updateUser)) {
//  $userService = L::loadClass('UserService', 'user'); /* @var $userService PW_UserService */
//  $userService->update($winduid, $updateUser);
// }
// if ($bandb) {
//  $bandb = current($bandb);
//  if ($bandb['type'] == 1) {
//   $s_date = get_date($bandb['startdate']);
//   $e_date = $bandb['startdate'] + $bandb['days']*86400;
//   $e_date = get_date($e_date);
//   Showmsg('ban_info1');
//  } else {
//   if ($bandb['type'] == 3) {
//    Cookie('force',$winduid);
//    Showmsg('ban_info3');
//   } else {
//    Showmsg('ban_info2');
//   }
//  }
// }
//}
//if (GetCookie('force') && $winduid != GetCookie('force')) {
// $force = GetCookie('force');
// $bandb = $db->get_one("SELECT type FROM pw_banuser WHERE uid=".pwEscape($force)." AND fid='0'");
// if ($bandb['type'] == 3) {
//  Showmsg('ban_info3');
// } else {
//  Cookie('force','',0);
// }
//}

$userlastptime = $groupid != 'guest' ?  $winddb['lastpost'] : GetCookie('userlastptime');
/**
* 灌水预防
*/
//$tdtime  >= $winddb['lastpost'] && $winddb['todaypost'] = 0;
//$montime >= $winddb['lastpost'] && $winddb['monthpost'] = 0;
//if ($_G['postlimit'] && $winddb['todaypost'] >= $_G['postlimit']) {
// Showmsg('post_gp_limit');
//}
//if (!empty($_POST['step']) && !$pwpost->isGM && $_G['postpertime'] && $timestamp>=$userlastptime && $timestamp-$userlastptime<=$_G['postpertime'] && !pwRights($pwpost->isBM,'postpers')) {
//	Showmsg('post_limit');
//}
list($postq,$showq) = explode("\t", $db_qcheck);
$_G['uploadtype'] && $db_uploadfiletype = $_G['uploadtype'];
$db_uploadfiletype = !empty($db_uploadfiletype) ? (is_array($db_uploadfiletype) ? $db_uploadfiletype : unserialize($db_uploadfiletype)) : array();
empty($db_sellset['type']) && $db_sellset['type'] = array('money');
empty($db_enhideset['type']) && $db_enhideset['type'] = array('rvrc');

//if (empty($_POST['step'])) {
//
// require_once(R_P.'require/credit.php');
// $editor = getstatus($winddb['userstatus'], PW_USERSTATUS_EDITOR) ? 'wysiwyg' : 'textmode';
// !is_numeric($db_attachnum) && $db_attachnum = 1;
// $htmlsell = ($pwforum->foruminfo['allowsell'] && $_G['allowsell']) ? '' : 'disabled';
// $htmlhide = ($pwforum->forumset['allowencode'] && $_G['allowencode']) ? '' : 'disabled';
//	$htmlpost = $attachHide = ($pwforum->foruminfo['allowhide'] && $_G['allowhidden']) ? '' : 'disabled';
// $ifanonymous= ($pwpost->isGM || $pwforum->forumset['anonymous'] && $_G['anonymous']) ? '' : 'disabled';
// $groupid   == 'guest' && $userrvrc = 0;
// $atc_title  = $atc_content = $ifmailck = $selltype = $enhidetype = $alltype = '';
//	$sellCredit = $enhideCredit = $customCreditValue = $userAllCredits = array();
//	$attachAllow = pwJsonEncode($db_uploadfiletype);
//	$imageAllow = pwJsonEncode(getAllowKeysFromArray($db_uploadfiletype, array('jpg','jpeg','gif','png','bmp')));
//	
//	if (S::inArray($action, array('new', 'modify')) && $_G['allowreplyreward'] && S::isArray($_CREDITDB)) {
//		$customCreditValue = $credit->get($winduid, 'CUSTOM');
//	}
//	foreach ($credit->cType as $key => $value) {
//		if (S::inArray($action, array('new', 'modify')) && $_G['allowreplyreward'] && ($winddb[$key] || $customCreditValue[$key])) {
//			$replyrewardcredit .= "<option value=\"$key\">" . $value . "</option>";
//			$userAllCredits['c' . $key] = array(
//				$winddb[$key] ? ($key == 'rvrc' ? $winddb[$key] / 10 : $winddb[$key]) : $customCreditValue[$key],
//				$value,
//				$credit->cUnit[$key]
//			);
//		}
//		$alltype .= "<option value=\"$key\">".$value."</option>";
//	}
//	$userAllCredits && $userAllCredits = pwJsonEncode($userAllCredits);
//	foreach ($db_sellset['type'] as $key => $value) {
//		$selltype .= "<option value=\"$value\">".$credit->cType[$value]."</option>";
//		$sellCredit[$value] = $credit->cType[$value];
//	}
//	if (is_array($db_enhideset['type'])) {
//		foreach ($db_enhideset['type'] as $key => $value) {
//			$enhidetype .= "<option value=\"$value\">".$credit->cType[$value]."</option>";
//			$enhideCredit[$value] = $credit->cType[$value];
//		}
//	}
//	list($sellCredit, $enhideCredit) = array(pwJsonEncode($sellCredit), pwJsonEncode($enhideCredit));
//
//	require_once(R_P.'require/showimg.php');
//	list($postFaceUrl) = showfacedesign($winddb['icon'],1,'m');
//
//	$icondb = array();
//	if ($db_threademotion) {
//		$emotion = @opendir(S::escapeDir("$imgdir/post/emotion"));
//		while (($emotionimg = @readdir($emotion)) !== false) {
//			if ($emotionimg != "." && $emotionimg != ".." && $emotionimg != "" && preg_match("/^(\d+)\.(gif|jpg|png|bmp)$/i", $emotionimg, $emotionMatch)) {
//				$icondb[$emotionMatch[1]] = $emotionimg;
//			}
//		}
//		ksort($icondb);
//		@closedir($emotion);
//	}
//
//	//multiple post types
//	if ($foruminfo['allowtype'] && (($foruminfo['allowtype'] & 1) || ($foruminfo['allowtype'] & 2 && $_G['allownewvote']) || ($foruminfo['allowtype'] & 4 && $_G['allowactive']) || ($foruminfo['allowtype'] & 8 && $_G['allowreward'])|| ($foruminfo['allowtype'] & 16) || $foruminfo['allowtype'] & 32 && $_G['allowdebate'])) {
//		$N_allowtypeopen = true;
//	} else {
//		$N_allowtypeopen = false;
//	}
	
//} else {
	if ($db_cloudgdcode && defined('AJAX') && S::inArray($action, array('reply', 'quote'))) $keepCloudCaptchaCode = true;
	PostCheck(1, ($db_gdcheck & 4) && (!$db_postgd || $winddb['postnum'] < $db_postgd), ($db_ckquestion & 4 && (!$postq || $winddb['postnum'] < $postq) && $db_question));
	!$windid && $windid = '游客';
	/*
	if ($db_xforwardip && $_POST['_hexie'] != GetVerify($onlineip.$winddb['regdate'].$fid.$tid)) {
		Showmsg('undefined_action');
	}
	*/

//}

//默认动漫表情处理
if ($db_windmagic && ($action == 'new' || ($action == 'modify' && $pid == 'tpc'))) {
 $mDef = '';
 //* @include_once pwCache::getPath(D_P."data/bbscache/myshow_default.php");
 pwCache::getData(D_P."data/bbscache/myshow_default.php");
}
//if ($action == "new") {
// require_once(R_P.'require/postnew.php');
 
//} elseif ($action == "reply" || $action == "quote") {

// require_once(R_P.'require/postreply.php');
// require/postreply.php开始
!function_exists('readover') && exit('Forbidden');
/**
 * 用户组权限判断
 */
if (!$pwforum->foruminfo['allowrp'] && !$pwpost->admincheck && $_G['allowrp'] == 0) {
 Showmsg('reply_group_right');
}
////实名认证权限
//if ($db_authstate && !$pwpost->admincheck && $pwforum->forumset['auth_allowrp'] && true !== ($authMessage = $pwforum->authStatus($winddb['userstatus'],$pwforum->forumset['auth_logicalmethod']))) {
//	Showmsg($authMessage . '_rp');
//}

if ($article == '0') {
 $pw_tmsgs = GetTtable($tid);
 $S_sql = ',m.uid,m.groupid,m.userstatus,tm.ifsign,tm.content';
 $J_sql = "LEFT JOIN pw_members m ON m.uid=t.authorid LEFT JOIN $pw_tmsgs tm ON tm.tid=t.tid";
} else {
 $S_sql = $J_sql = '';
}
$tpcarray = $db->get_one("SELECT t.tid,t.fid,t.locked,t.ifcheck,t.author,t.authorid,t.postdate,t.lastpost,t.ifmail,t.special,t.subject,t.type,t.ifshield,t.anonymous,t.ptable,t.replies,t.tpcstatus $S_sql FROM pw_threads t $J_sql WHERE t.tid=" . S::sqlEscape($tid));
$pw_posts = GetPtable($tpcarray['ptable']);
$tpcarray['openIndex'] = getstatus($tpcarray['tpcstatus'], 2);
//$t_date = $tpcarray['postdate'];//主题发表时间 bbspostguide 中用到
if ($tpcarray['fid'] != $fid) {
 Showmsg('illegal_tid');
}
$replytitle = $tpcarray['subject'];
/**
 * convert()需要$tpc_author变量
 */
$tpc_author = $tpcarray['author'];

if ($pwforum->forumset['lock']&& !$pwpost->isGM && $timestamp - $tpcarray['postdate'] > $pwforum->forumset['lock'] * 86400 && !pwRights($pwpost->isBM,'replylock')) {
 $forumset['lock'] = $pwforum->forumset['lock'];
 Showmsg('forum_locked');
}
if (!$pwpost->isGM && !$tpcarray['ifcheck'] && !pwRights($pwpost->isBM,'viewcheck')) {
 Showmsg('reply_ifcheck');
}
if (!$pwpost->isGM && $tpcarray['locked']%3<>0 && !pwRights($pwpost->isBM,'replylock')) {
 Showmsg('reply_lockatc');
}

$special = 0;
$icon = (int)$icon;

//L::loadClass('replypost', 'forum', false);
//replypost.class.php开始
/**
 * Reply
 * 
 * @package Thread
 */
class replyPost {
 
 var $db;
 var $post;
 var $forum;
 var $postdata;
 
 var $data;
 var $att;
 
 var $tid;
 var $tpcArr;
 var $replyToUser;

 var $extraBehavior = null;
	var $timestamp;
 
 function replyPost(&$post) {
		global $db,$timestamp;
  $this->db = & $db;
  $this->post = & $post;
  $this->forum = & $post->forum;
  $this->type = 'Reply';
		$this->timestamp = $timestamp;
 }
 
 function setTpc($arr) {
  $this->tpcArr = $arr;
  $this->tid = $this->tpcArr['tid'];
  $this->setBehavior();
 }

 function setBehavior() {
  if ($this->extraBehavior !== null) {
   return;
  }
  if (getstatus($this->tpcArr['tpcstatus'], 1)) {
   $cyid = $this->db->get_value("SELECT cyid FROM pw_argument WHERE tid=" . S::sqlEscape($this->tpcArr['tid']));
   require_once(R_P . 'apps/groups/lib/colonypost.class.php');
   $this->extraBehavior = new PwColonyPost($cyid);
  }
 }

 function setToUser($username) {
  $this->replyToUser = $username;
 }
 
 function creditSet() {
  static $creditset = null;
  if (!isset($creditset)) {
   global $db_creditset, $credit;
   require_once (R_P . 'require/credit.php');
   $creditset = $credit->creditset($this->forum->creditset, $db_creditset);
   $creditset = $creditset[$this->type];
  }
  return $creditset;
 }

 function userCreidtSet() {
  $creditset = $this->creditSet();
  if (($times = $this->forum->authCredit($this->post->user['userstatus'])) > 1) {
   foreach ($creditset as $key => $value) {
    $value > 0 && $creditset[$key] *= $times;
   }
  }
  return $creditset;
 }
 
 function check() {
  $this->post->checkUserCredit($this->creditSet());
  /**
  * 版块权限判断
  */
  if (!$this->getReplyForumRight()) {
   return $this->post->showmsg('reply_forum_right');
  }
  if ($this->extraBehavior) {
   if (($return = $this->extraBehavior->replyCheck()) !== true) {
    return $this->post->showmsg($return);
   }
  }
		if (getstatus($this->tpcArr['tpcstatus'], 7)) {
			$robbuildService = L::loadClass('RobBuild', 'forum'); /* @var $robbuildService PW_RobBuild */
			$robbuild = $robbuildService->getByTid($this->tid);
			if ($robbuild['starttime'] > $this->timestamp) {
				$robbuild['starttime'] = get_date($robbuild['starttime'],'Y-m-d H:i');
				$this->post->showmsg("亲,不要急哦,抢楼活动开始时间：{$robbuild['starttime']}");
			}
			if ($robbuild['status']) {
				$this->post->showmsg("亲,抢楼活动已经结束了哦");
			}
		}
 }
 
 function setPostData(&$postdata) {
  $this->postdata = & $postdata;
  $this->att = & $postdata->att;
  $this->data = $postdata->getData();
		if ((stripslashes($this->data['title']) == 'Re:' . $this->tpcArr['subject']) || (strlen($this->data['title']) > 98 && strrpos($this->data['title'],'Re:') === 0)) {
   $this->data['title'] = '';
  }
 }
 /**
  * @author papa
  * @param $pid
  * @return unknown_type
  */
 function setPostFloor($pid) {
  $sql = "INSERT INTO pw_postsfloor SET pid=" . S::sqlEscape($pid) . ", tid=" . S::sqlEscape($this->tid);
  $this->db->update($sql);
		return $this->db->insert_id();
 }
 
 
 function execute($postdata) {
  global $db_cvtime, $db_ptable, $onlineip, $db_plist;
  $this->setPostData($postdata);
  $ipTable = L::loadClass('IPTable', 'utility');
  $ipfrom = $ipTable->getIpFrom($onlineip);
  //  $timestamp = time();
  //  $db_cvtime!=0 && $timestamp += $db_cvtime*60;
  $timestamp=$this->data['postdate']; //zzcity add
  $pwSQL = array(
   'fid' => $this->data['fid'],
   'tid' => $this->tid,
   'aid' => $this->data['aid'],
   'author' => $this->data['author'],
   'authorid' => $this->data['authorid'],
   'icon' => $this->data['icon'],
   'postdate' => $timestamp,
   'subject' => $this->data['title'],
   'userip' => $onlineip,
   'ifsign' => $this->data['ifsign'],
   'ipfrom' => $ipfrom,
   'ifconvert' => $this->data['convert'],
   'ifwordsfb' => $this->data['ifwordsfb'],
   'ifcheck' => $this->data['ifcheck'],
   'content' => $this->data['content'],
   'anonymous' => $this->data['anonymous'],
			'ifhide' => $this->data['hideatt'],
			'frommob' => $this->data['frommob']
  );
  $pw_posts = GetPtable($this->tpcArr['ptable']);
  if ($db_plist && count($db_plist) > 1) {
   //* $this->db->update("INSERT INTO pw_pidtmp(pid) VALUES(null)");
   //* $pid = $this->db->insert_id();
   $uniqueService = L::loadClass ('unique', 'utility');
   $pid = $uniqueService->getUnique('post'); 
  } else {
   $pid = '';
  }
  $pwSQL['pid'] = $pid;
  //$pwSQL = S::sqlSingle($pwSQL);
  //$this->db->update("INSERT INTO $pw_posts SET $pwSQL");
  pwQuery::insert($pw_posts, $pwSQL);
  !$pid && $pid = $this->db->insert_id();
		$this->tpcArr['openIndex'] && $floor = $this->setPostFloor($pid);
		if (getstatus($this->tpcArr['tpcstatus'], 7)) {
			$robbuildService = L::loadClass ( "robbuild", 'forum' );
			$robbuildService->setRobbuilds($pid,$floor,$this->tid);
		}
  $this->pid = $pid;
  if (is_object($this->att) && ($aids = $this->att->getAids())) {
   $this->db->update("UPDATE pw_attachs SET " . S::sqlSingle(array(
    'tid' => $this->tid,
    'pid' => $this->pid
   )) . ' WHERE aid IN(' . S::sqlImplode($aids) . ')');
   //tucool
   $imgNum = $this->att->getUploadImgNum();
   if ($this->forum->forumset['iftucool'] && $this->forum->forumset['tucoolpic'] && $imgNum) {
    $tucoolService = L::loadClass('tucool','forum');
    $tucoolService->setForum($this->forum->foruminfo);
    $tucoolService->updateTucoolImageNum($this->tid);
   }
  }
  if ($this->data['ifcheck'] == 1) {
   $sqladd1 = '';
   $sqladd = array(
    'lastposter' => $this->data['lastposter']
   );
   $this->tpcArr['locked'] < 3 && $this->tpcArr['lastpost'] < $timestamp && $sqladd['lastpost'] = $timestamp;
   $this->data['ifupload'] && $sqladd['ifupload'] = $this->data['ifupload'];
   $ret = $this->sendMail();
   if ($ret & 2) {
    $sqladd['ifmail'] = 4;
   } elseif ($ret & 1) {
    $sqladd1 = "ifmail=ifmail-1,";
   }
   $this->db->update("UPDATE pw_threads SET {$sqladd1}replies=replies+1,hits=hits+1," . S::sqlSingle($sqladd) . " WHERE tid=" . S::sqlEscape($this->tid));
   Perf::gatherInfo('changeThreads', array('tid'=>$this->tid));
			$userCache = L::loadClass('Usercache', 'user');
			$userCache->delete($this->data['authorid'], 'reply');
  }
		//weibo
		$weiboService = L::loadClass('weibo','sns');/* @var $weiboService PW_Weibo */ 
		$weiboContent = substrs(stripWindCode($weiboService->escapeStr(strip_tags($this->data['content']))), 125);
		$weiboExtra = array(
						'title' => stripslashes($this->tpcArr['subject']),
						'fid' => $this->forum->fid,
						'fname' => $this->forum->name,
						'atusers' =>$this->data['atusers'],
						'pid'	=> $this->pid
					);
		$weiboService->send($this->post->uid,$weiboContent,'article',$this->tid,$weiboExtra);
		$threadService = L::loadClass('threads','forum');
		$threadService->setAtUsers($this->tid,$this->pid,$this->data['atusers']);
		//end weibo
		if ($this->data['ifcheck'] == 1) $this->post->updateUserInfo($this->type, $this->userCreidtSet(), $this->data['content']);
  $this->afterReply();

  if ($this->extraBehavior) {
   $this->extraBehavior->replyPost($this->pid, $this->tid, $this->data);
  }
 }
 
 function sendMail() {
  global $db_msgreplynotice,$db_replysendmail,$db_replysitemail,$windid,$winduid;
  $ret = $msgNotice = 0;
  if ($db_msgreplynotice && $this->replyToUser && $this->replyToUser != $windid) {
   M::sendMessage(
    $winduid,
    array($this->replyToUser),
    array(
     'create_uid' => $winduid,
     'create_username' => $windid,
     'title' => getLangInfo('writemsg','subject_replytouser_title',array(
      'windid' => $windid,
      'title'  => substrs(strip_tags($this->tpcArr['subject']), 30, 'Y')
     )),
     'content' => getLangInfo('writemsg','subject_reply_content',array(
      'tid' => $this->tid,
      'pid' => $this->pid,
      'windid' => $windid,
						'content'	=> substrs(strip_tags($this->data['content']), 100, 'Y')
     )),
    ),
    'sms_reply',
    'sms_reply'
   );
   $msgNotice = 1;
  }
  if ($this->data['authorid'] == $this->tpcArr['authorid']) {
   return $ret;
  }
  if ($db_replysendmail == 1 && ($this->tpcArr['ifmail'] == 1 || $this->tpcArr['ifmail'] == 3)) {
   $userService = L::loadClass('UserService', 'user'); /* @var $userService PW_UserService */
   $receiver = $this->tpcArr['author'];
   $old_title = $this->tpcArr['subject'];
   $detail = $userService->get($this->tpcArr['authorid']);
   $send_address = $detail['email'];
   if (getstatus($detail['userstatus'], PW_USERSTATUS_RECEIVEMAIL)) {
    require_once (R_P . 'require/sendemail.php');
    sendemail($send_address, 'email_reply_subject', 'email_reply_content', 'email_additional');
   }
   $ret = 1;
  }
  if ($db_replysitemail && !$msgNotice && ($this->tpcArr['ifmail'] == 2 || $this->tpcArr['ifmail'] == 3)) {
   /*
   $userService = L::loadClass('UserService', 'user');
   $rt = $userService->get($this->tpcArr['authorid'], true, false, true);
   $replyinfo = $rt['replyinfo'] ? $rt['replyinfo'] . $this->tid . ',' : ",$this->tid,";
   $userService->update($this->tpcArr['authorid'], array(), array(), array('replyinfo' => $replyinfo));
   if (!getstatus($rt['userstatus'], PW_USERSTATUS_NEWRP)) {
    $userService->setUserStatus($this->tpcArr['authorid'], PW_USERSTATUS_NEWRP, true);
   }
   */
   M::sendMessage(
    $winduid,
    array($this->tpcArr['author']),
    array(
     'create_uid' => $winduid,
     'create_username' => $windid,
     'title' => getLangInfo('writemsg','subject_reply_title',array(
      'windid' => $windid,
      'author' => $this->tpcArr['author'],
      'title'  => substrs(strip_tags($this->tpcArr['subject']), 30, 'Y')
     )),
     'content' => getLangInfo('writemsg','subject_reply_content',array(
      'tid' => $this->tid,
      'pid' => $this->pid,
      'windid' => $windid,
						'content'	=> substrs(strip_tags(stripWindCode($this->data['content'])), 100, 'Y')
     )),
    ),
    'sms_reply',
    'sms_reply'
   );
   $ret += 2;
  }
  return $ret;
 }
 
 function afterReply() {
  global $db_ifpwcache, $timestamp, $db_readperpage;
  if ($this->data['ifcheck'] == 1) {
   if ($this->forum->foruminfo['allowhtm'] && !$this->forum->foruminfo['cms'] && $this->tpcArr['replies'] < $db_readperpage) {
    $StaticPage = L::loadClass('StaticPage');
    $StaticPage->update($this->tid);
   }
   if ($this->tpcArr['ifcheck'] == 1) {
    $lastpost = array(
     'subject' => $this->data['title'] ? substrs($this->data['title'], 26) : 'Re:' . substrs($this->tpcArr['subject'], 26),
     'author' => $this->data['lastposter'],
     'lastpost' => $timestamp,
     'tid' => $this->tid,
     't_date' => $this->tpcArr['postdate']
    );
    $this->forum->lastinfo('reply', '+', $lastpost);
   }
   
   //Start Here pwcache
   if ($db_ifpwcache & 270) {
    L::loadClass('elementupdate', '', false);
    $elementupdate = new ElementUpdate($this->forum->fid);
    $elementupdate->special = $this->tpcArr['special'];
    if ($db_ifpwcache & 14) {
     $elementupdate->replySortUpdate($this->tid, $this->forum->fid, $this->tpcArr['postdate'], $this->tpcArr['replies'] + 1);
    }
    if ($db_ifpwcache & 256) {
     $elementupdate->newReplyUpdate($this->tid, $this->forum->fid, $this->tpcArr['postdate']);
    }
    $elementupdate->updateSQL();
   }
   require_once (R_P . 'require/functions.php');
   updateDatanalyse($this->data['authorid'], 'memberThread', 1);
   updateDatanalyse($this->tid, 'threadPost', 1);
   
   // memcache refresh
   // $threadsObj = L::loadclass("threads", 'forum');
   // $threadsObj->clearThreadByThreadId($this->tid);
   
   // memcache refresh
   // $threadlistObj = L::loadclass("threadlist", 'forum');
   // $threadlistObj->updateThreadIdsByForumId($this->forum->fid, $this->tid);
    
   Perf::gatherInfo('changeThreadWithThreadIds', array('tid'=>$this->tid));
   Perf::gatherInfo('changeThreadWithForumIds', array('fid'=>$this->forum->fid));  
   
  }
  if ($this->postdata->filter->filter_weight > 1) {
   $this->postdata->filter->insert($this->tid, $this->pid, implode(',', $this->postdata->filter->filter_word), $this->postdata->filter->filter_weight);
  }
 }
 
 function getNewId() {
  return $this->pid;
 }

 /**
  * 获取用户在版块中的发表回复权限
  * @author zhudong
  * @return int $right
  */
  function getReplyForumRight() {
  $right = false;
  if ($this->post->admincheck) {
   $right = true;
  } elseif ($this->forum->allowreply($this->post->user,$this->post->groupid)) {
   $right = true;
  } elseif ($this->extraBehavior) {//当在群组中
   $this->extraBehavior->replyCheck() && $right = true;
  }
  return $right;
  }
 
}

//replypost.class.php结束


$replypost = new replyPost($pwpost);
$replypost->setTpc($tpcarray);
$replypost->check();

//if (empty($_POST['step'])) {
// ##主题分类
// $db_forcetype = 0;
// require_once(R_P.'require/bbscode.php');
//
// $hideemail = 'disabled';
// if ($action == 'quote') {
//  if ($article == '0') {
//   $atcarray = $tpcarray;
//  } else {
//   !is_numeric($pid) && Showmsg('illegal_tid');
//			$atcarray = $db->get_one("SELECT p.author,p.authorid,p.subject,p.ifsign,p.postdate,p.content,p.ifshield,p.anonymous,m.uid,m.groupid,m.userstatus FROM $pw_posts p LEFT JOIN pw_members m ON m.uid=p.authorid WHERE p.pid=".S::sqlEscape($pid));
//  }
//  if ($atcarray['ifshield']) {//单帖屏蔽
//   $atcarray['content'] = shield($atcarray['ifshield']=='1' ? 'shield_article' : 'shield_del_article');
//  } elseif ($pwforum->forumBan($atcarray)) {
//   $atcarray['content'] = shield('ban_article');
//  }
//  $ifsign = $atcarray['ifsign'];
//  $old_author = $atcarray['anonymous'] ? $db_anonymousname : $atcarray['author'];
//  $replytitle = $atcarray['subject'];
//  $wtof_oldfile = get_date($atcarray['postdate']);
//  $old_content = $atcarray['content'];
//  $old_content = preg_replace("/\[hide=(.+?)\](.+?)\[\/hide\]/is",getLangInfo('post','hide_post'),$old_content);
//  $old_content = preg_replace("/\[post\](.+?)\[\/post\]/is",getLangInfo('post','post_post'),$old_content);
//  $old_content = preg_replace("/\[sell=(.+?)\](.+?)\[\/sell\]/is",getLangInfo('post','sell_post'),$old_content);
//  $old_content = preg_replace("/\[quote\](.*)\[\/quote\]/is","",$old_content);
//  $bit_content = explode("\n",$old_content);
//
//  if (count($bit_content) > 5) {
//   $old_content = "$bit_content[0]\n$bit_content[1]\n$bit_content[2]\n$bit_content[3]\n$bit_content[4]\n.......";
//  }
//  if (strpos($old_content,$db_bbsurl) !== false) {
//			$old_content = str_replace('p_w_picpath',$db_picpath,$old_content);
//			$old_content = str_replace('p_w_upload',$db_attachname,$old_content
//  }
//  $old_content = preg_replace("/\<(.+?)\>/is","",$old_content);
//  $atc_content = "[quote]".($article==0 ? getLangInfo('post','info_post_1') : getLangInfo('post','info_post_2'))."\n{$old_content} [url={$db_bbsurl}/job.php?action=topost&tid=$tid&pid=$pid][img]{$imgpath}/back.gif[/img][/url]\n[/quote]\n";
// }
// list($guidename, $forumtitle) = $pwforum->getTitle();
//	$guidename .= "<em>&gt;</em><a href=\"read.php?tid=$tid\">$tpcarray[subject]</a>";
// if (!$replytitle) {
//  $atc_title = "Re:$tpcarray[subject]";
//  $forumtitle = "$atc_title|$forumtitle";
// } else {
//  $atc_title = "Re:$replytitle";
//  $forumtitle = "$atc_title|$tpcarray[subject]|$forumtitle";
// }
//	$atc_title = substrs(str_replace('&nbsp;',' ',$atc_title), $db_titlemax - 3);
// $db_metakeyword = str_replace(array('|',' - '),',',$forumtitle).'phpwind';
//
// require_once(R_P.'require/header.php');
// $msg_guide = $pwforum->headguide($guidename);
// $post_reply = '';
//	$review_reply = '';
//
// if ($db_showreplynum > 0) {
//  $wordsfb = L::loadClass('FilterUtil', 'filter');
//  $pwAnonyHide = $pwpost->isGM || pwRights($pwpost->isBM,'anonyhide');
//		$query = $db->query("SELECT p.pid,p.author,p.authorid,p.subject,p.postdate,p.content,p.anonymous,p.ifconvert,p.ifwordsfb,p.ifshield,m.uid,m.groupid,m.userstatus FROM $pw_posts p LEFT JOIN pw_members m ON p.authorid=m.uid WHERE tid=".S::sqlEscape($tid)."AND ifcheck='1' ORDER BY postdate DESC LIMIT 0,$db_showreplynum");
//
//  while ($rt = $db->fetch_array($query)) {
//   $tpc_author = ($rt['anonymous'] && !$pwAnonyHide && $windid != $rt['author']) ? $db_anonymousname : $rt['author'];
//			$tpc_pid = $rt['pid'];
//   if ($rt['ifshield']) {
//    $groupid != '3' && $rt['content'] = shield($rt['ifshield'] == '1' ? 'shield_article' : 'shield_del_article');
//   } elseif ($groupid != 3 && $db_shield && $pwforum->forumBan($rt)) {
//    $rt['content'] = shield('ban_article');
//   } else {
//    if (!$wordsfb->equal($rt['ifwordsfb'])) {
//     $rt['content'] = $wordsfb->convert($rt['content']);
//    }
//    $rt['ifconvert'] == 2 && $rt['content'] = convert($rt['content'],$db_windpost);
//    if (strpos($rt['content'],'[p:') !== false || strpos($rt['content'],'[s:') !== false) {
//     $rt['content'] = showface($rt['content']);
//    }
//   }
//   $post_reply .= "<table align=center width=70% cellspacing=1 cellpadding=2 style='TABLE-LAYOUT: fixed;WORD-WRAP: break-word'><tr><td width=100%>$tpc_author:$rt[subject]<br /><br />$rt[content]</td></tr></table><hr size=1 color=$tablecolor width=80%>";
//  }
// }
// if ($winduid && $tpcarray['special'] == 5) {
//  $debatestand = $db->get_value("SELECT standpoint FROM pw_debatedata WHERE pid='0' AND tid=".pwEscape($tid)."AND authorid=".pwEscape($winduid));
//  $debatestand = (int)$debatestand;
//  ${'debate_'.$debatestand} = 'SELECTED';
// }
// /**
//  * 索引设计时为了减少空间,回复的主题可能为空,所以默认为回复主题!
//  */
// require_once PrintEot('post');footer();
//
//} elseif ($_POST['step'] == 2) {

	S::gp(array('atc_title','atc_content','quote_content'), 'P', 0);
	S::gp(array('atc_anonymous','atc_hideatt','atc_enhidetype','atc_credittype','flashatt','replytouser','_usernames'), 'P');
	S::gp(array('atc_iconid','atc_convert','atc_autourl','atc_usesign','atc_html','atc_hide','atc_requireenhide','atc_rvrc','atc_requiresell', 'atc_money', 'go_lastpage'), 'P', 2);
	
 S::gp(array('iscontinue'),'P');//ajax提交时有敏感词时显示是否继续
 ($db_sellset['price'] && (int) $atc_money > $db_sellset['price']) && Showmsg('post_price_limit');
 require_once(R_P . 'require/bbscode.php');
	if ($action == 'quote' && $quote_content) {
		$atc_content = $quote_content . $atc_content;
	}
 $postdata = new replyPostData($pwpost);
 $postdata->data['postdate']=$timestamp; //zzcity add
 
 $atc_title=''; //zzcity add
 $postdata->setTitle($atc_title);

 $etattachs=$_POST['etattachs'];//zzcity add

//zzcity add
 if (!empty($etattachs)) {
  //L::loadClass('attupload', 'upload', false);
  //attupload.class.php开始

  //L::loadClass('upload', '', false);
  //upload.class.php开始

   class PwUpload {
    //zzcity modi开始
    function initCurrUpload($key, $value,$attname) {
/*
     list($t, $i) = explode('_', $key);
     $arr = array(
      'id' => intval($i),
      'attname' => $t,
      'name' => S::escapeChar($value['name']),
      'size' => intval($value['size']),
      'type' => 'zip',
      'ifthumb' => 0,
      'fileuploadurl' => ''
     );
     $arr['ext'] = strtolower(substr(strrchr($arr['name'], '.'), 1));
     return $arr;
*/        
     $arr = array(
     'id' => intval($key),
     'attname' => $attname,
     //'name' => Char_cv(strtolower(substr(strrchr($value, '/'), 1))),
     'name' => Char_cv(substr(strrchr($value, '/'), 1)),
     'size' => 0,
     'type' => 'zip',
     'ifthumb' => 0,
     'fileuploadurl' => ''
     );
     $arr['ext'] = strtolower(substr(strrchr($arr['name'], '.'), 1));
     return $arr;
    }
   
    function upload(&$bhv,$attas,&$content) {
     global $db_attachname;
     $arratt=explode(',',$attas);
     if(count($arratt)==0) break;
     $uploaddb = array();
     foreach ($arratt as $key => $value) {
			//$attpath=strtolower(substr($value, 0,strripos($value, '/')+1)); 
			$attpath=substr($value, 0,strripos($value, '/')+1); 
		 
		 
	/*   if (!PwUpload::if_uploaded_file($value['tmp_name']) || !$bhv->allowType($key)) {
		continue;
	   }
	
		$atc_attachment = $value['tmp_name'];
	 
		$upload = PwUpload::initCurrUpload($key, $value);
	*/   
		if (preg_match("/".preg_quote($value,"/")."/i",$content)){
		 
		   $upload = PwUpload::initCurrUpload($key+1, $value,'attachment');
		   $upid=$key+1;
		   $content=preg_replace("/<a([^>]*?)".preg_quote($value,"/")."([^<]*?)<img([^>]*?)".preg_quote($value,"/")."([^<]*?)<\/(.*?)>/i",'[upload='.$upid.']',$content);
		   $content=preg_replace("/<img([^>]*?)".preg_quote($value,"/")."([^>]*?)>/i",'[upload='.$upid.']',$content);
		   $content=preg_replace("/\[img([^\]]*?)\]".preg_quote($value,"/")."\[\/img\]/i",'[upload='.$upid.']',$content);
		   $content=preg_replace("/<a([^>]*?)".preg_quote($value,"/")."([^>]*?)>([^<]+?)<\/a(.*?)>/i",'\\3[upload='.$upid.']',$content);
		   $content=preg_replace("/\[(flash|rm|wmv)=([^\[]*?)".preg_quote($value,"/")."([^\]]*?)(flash|rm|wmv)\]/i",'\\3[upload='.$upid.']',$content);
		   if (in_array($upload['ext'], array('swf','flv'))) {
			   $content=preg_replace("/<object((?!object)(\s|\S))*".preg_quote($value,"/")."((?!object)(\s|\S))*</(.*?)>/i",'[flash=314,256,1]'.$value.'[/flash]',$content);
			   $content=preg_replace("/<embed((?!embed)(\s|\S))*".preg_quote($value,"/")."((?!embed)(\s|\S))*</(.*?)>/i",'[flash=314,256,1]'.$value.'[/flash]',$content);
		   }elseif  (in_array($upload['ext'], array('rm','rmvb'))){
			   $content=preg_replace("/<object((?!object)(\s|\S))*".preg_quote($value,"/")."((?!object)(\s|\S))*</(.*?)>/i",'[rm=314,256,1]'.$value.'[/rm]',$content);
			   $content=preg_replace("/<embed((?!embed)(\s|\S))*".preg_quote($value,"/")."((?!embed)(\s|\S))*</(.*?)>/i",'[rm=314,256,1]'.$value.'[/rm]',$content);
		   }elseif  (in_array($upload['ext'], array('wmv','mp3','mp4','avi','wma'))){
			   $content=preg_replace("/<object((?!object)(\s|\S))*".preg_quote($value,"/")."((?!object)(\s|\S))*</(.*?)>/i",'[wmv=314,256,1]'.$value.'[/wmv]',$content);
			   $content=preg_replace("/<embed((?!embed)(\s|\S))*".preg_quote($value,"/")."((?!embed)(\s|\S))*</(.*?)>/i",'[wmv=314,256,1]'.$value.'[/wmv]',$content);
		   }      
	   
		   /*
		   if (empty($upload['ext']) || !isset($bhv->ftype[$upload['ext']])) {
		   showUploadMsg('upload_type_error');
		   }
		   
		   if ($upload['size'] < 1 || $upload['size'] > $bhv->ftype[$upload['ext']] * 1024) {
		   $GLOBALS['atc_attachment_name'] = $upload['name'];
		   $GLOBALS['oversize'] = $bhv->ftype[$upload['ext']];
		   showUploadMsg($upload['size'] < 1 ? 'upload_size_0' : 'upload_size_error');
		   }
		   */
		   
		   //       list($filename, $savedir) = $bhv->getFilePath($upload);
		   
		   $filename=$upload['name'];
		   
		   //根据文件名查找文件是否已经入库，如果已经入库，则复制记录
		   $oldatt = $bhv->pw_attachs->gets(array('name'=>$filename));
		   foreach ($oldatt as $rt) {
				$newaid=$bhv->pw_attachs->add(array(
					 'fid'  => $rt['fid'],   'uid'  => $bhv->post->uid,
					 'hits'  => 0,       'name'  => $rt['name'],
					 'type'  => $rt['type'],    'size'  => $rt['size'],
					 'attachurl' => $rt['attachurl'],  'needrvrc' => $rt['needrvrc'],
					 'special' => $rt['special'],   'ctype'  => $rt['ctype'],
					 'uploadtime'=> $rt['uploadtime'],     'descrip' => $rt['descrip'],
					 'ifthumb' => $rt['ifthumb']
				));
				$content=str_replace("[upload=$upid]", "[attachment=$newaid]", $content);
				
			   $bhv->attachs[$newaid] = array(
				'aid'       => $newaid,
				'name'      => $rt['name'],
				'type'      => $rt['type'],
							'attachurl' => $rt['attachurl'],
				'needrvrc'  => $rt['needrvrc'],
				'special' => $rt['special'],
				'ctype'  => $rt['ctype'],
				'size'      => $rt['size'],
				'hits'      => 0,
				'desc'  => str_replace('\\','', $rt['descrip']),
				'ifthumb' => $rt['ifthumb']
			   );
				
				break;					  
		   }
		   if ($newaid){
				continue;   
		   }
		   
		   //$savedir=preg_replace('/(.*)'.$db_attachname.'(\/*)/i','',strtolower($attpath)); 
		   $savedir=preg_replace('/(.*)'.$db_attachname.'(\/*)/i','',$attpath); 
		   $upload['fileuploadurl'] = $savedir . $filename;
		
		   $source = PwUpload::savePath($bhv->ifftp, $filename, $savedir);
		   $source=realpath($source);
		   /*
		   if (!PwUpload::postupload($atc_attachment, $source)) {
		   showUploadMsg('upload_error');
		   }
		   */
		   if (!file_exists($source)) {
		   echo('[err]First upload files,请先上传文件到正确的附件目录[/err]');
		   exit;
		   }
		   $upload['size'] = ceil(filesize($source) / 1024);
		   
		   PwUpload::operateAttach($source, $filename, $savedir, $upload, $bhv);
		   $uploaddb[] = $upload;
		   
		   }
	   }
	  $bhv->update($uploaddb);
    }
    //zzcity modi 结束

  
  /**
   * @static
   */
  function operateAttach($source, $filename, $savedir, &$upload, $bhv) {
   $thumbInfo = array();
   if (PwUpload::isImage($upload['ext'])) {
    list($thumbInfo, $upload['ifthumb'], $upload['type']) = PwUpload::operateImage($source, $filename, $savedir, $upload, $bhv);
   } elseif ($upload['ext'] == 'txt') {
//    if (preg_match('/(onload|submit|post|form)/i', readover($source))) {
//     P_unlink($source);
//     showUploadMsg('upload_content_error');
//    }
    $upload['type'] = 'txt';
   }
   if ($bhv->ifftp) {
    if (!PwUpload::movetoftp($source, $savedir . $filename)) return false;
   } else {
    if (!PwUpload::movefile($source, PwUpload::savePath(0, $filename, $savedir))) return false;
   }
   if ($upload['ifthumb']) {
    PwUpload::operateThumb($thumbInfo, $bhv->allowWaterMark(), $bhv->ifftp, $upload['ext']);
   }
   return true;
  }
  
  function isImage($ext) {
   return in_array($ext, array('gif','jpg','jpeg','png','bmp','swf'));
  }
 
  /**
   * @static
   */
  function operateImage($source, $filename, $savedir, $upload, $bhv) {
   require_once (R_P . 'require/imgfunc.php');
//   if (!$img_size = GetImgSize($source, $upload['ext'])) {
//    P_unlink($source);
//    showUploadMsg('upload_content_error');
//   }
   $thumbInfo = array();
   $ifthumb = 0;
   if ($upload['ext'] != 'swf') {
			if ($bhv->allowThumb() && $upload['ext'] != 'gif') {
     $thumbInfo = PwUpload::makeThumb($source, $bhv->getThumbInfo($filename, $savedir), $bhv->ifftp, $ifthumb);
    }
    $bhv->allowWaterMark() && PwUpload::waterMark($source, $upload['ext'], $img_size);
    $upload['type'] = 'img';
   }
   return array($thumbInfo, $ifthumb, $upload['type']);
  }
  
  /**
   * @static
   */
  function operateThumb($list, $waterMark, $ifftp, $ext) {
   if (empty($list)) return false;
   foreach ($list as $k => $v) {
    $waterMark && PwUpload::waterMark($v[0], $ext);
    $ifftp && PwUpload::movetoftp($v[0], $v[1]);
   }
   return true;
  }
  /**
   * @static
   */
  function makeThumb($source, $thumbInfo, $ifftp, &$ifthumb) {
   $array = array();
   foreach ($thumbInfo as $key => $value) {
    list($thumbw, $thumbh, $cenTer) = explode("\t", $value[2]);
    $thumburl = PwUpload::savePath($ifftp, $value[0], $value[1]);
    PwUpload::createFolder(dirname($thumburl));
    if (($thumb = MakeThumb($source, $thumburl, $thumbw, $thumbh, $cenTer)) && $source != $thumburl) {
     $ifthumb |= (1 << $key);
     $array[] = array($thumburl, $value[1] . $value[0]);
    }
   }
   return $array;
  }
  /**
   * @static
   */
  function waterMark($source, $ext, $imgsize = null) {
   global $db_watermark, $db_waterwidth, $db_waterheight, $db_ifgif, $db_waterimg, $db_waterpos, $db_watertext, $db_waterfont, $db_watercolor, $db_waterpct, $db_jpgquality;
 
   empty($imgsize) && $imgsize = GetImgSize($source, $ext);
   if (empty($imgsize)) {
    return;
   }
   if ($db_watermark && $imgsize['type'] < 4 && $imgsize['width'] > $db_waterwidth && $imgsize['height'] > $db_waterheight && function_exists('imagecreatefromgif') && function_exists('imagealphablending') && ($ext != 'gif' || function_exists('imagegif') && ($db_ifgif == 2 || $db_ifgif == 1 && (PHP_VERSION > '4.4.2' && PHP_VERSION < '5' || PHP_VERSION > '5.1.4'))) && ($db_waterimg && function_exists('imagecopymerge') || !$db_waterimg && function_exists('imagettfbbox'))) {
    ImgWaterMark($source, $db_waterpos, $db_waterimg, $db_watertext, $db_waterfont, $db_watercolor, $db_waterpct, $db_jpgquality);
   }
  }
  /**
   * @static
   */
  function getUploadNum() {
   foreach ($_FILES as $key => $val) {
    if (!$val['tmp_name'] || $val['tmp_name'] == 'none') {
     unset($_FILES[$key]);
    }
   }
   return count($_FILES);
  }
    
  /*检查上传是否有错误*/
  function checkUpload(){
   foreach ($_FILES as $k => $v) {
    switch ($v['error']){
     case UPLOAD_ERR_INI_SIZE:
      $maxuploadsize = @ini_get('upload_max_filesize');
      return '上传的附件超过服务器上传的最大限制' . $maxuploadsize;
      break;
     case UPLOAD_ERR_NO_TMP_DIR:
      return '附件上传失败,服务器TMP目录设置错误';
      break;
     default:
    }
   }
   return true;
  }
  /**
   * @static
   */
  function if_uploaded_file($tmp_name) {
   if (!$tmp_name || $tmp_name == 'none') {
    return false;
   } elseif (function_exists('is_uploaded_file') && !is_uploaded_file($tmp_name) && !is_uploaded_file(str_replace('\\\\', '\\', $tmp_name))) {
    return false;
   } else {
    return true;
   }
  }
  function &getFtpObj() {
   if (!is_object($GLOBALS['ftp'])) {
    require_once (R_P . 'require/functions.php');
    pwFtpNew($GLOBALS['ftp'], true);
   }
   return $GLOBALS['ftp'];
  }
  /**
   * @static
   */
  function movetoftp($srcfile, $dstfile) {
   $ftp =& PwUpload::getFtpObj();
   if ($ftp->upload($srcfile, $dstfile)) {
    P_unlink($srcfile);
    return true;
   }
   return false;
  }
  /**
   * @static
   */
  function movefile($srcfile, $dstfile) {
   if ($srcfile == $dstfile) {
    return true;
   }
   PwUpload::createFolder(dirname($dstfile));
   if (rename($srcfile, $dstfile)) {
    @chmod($dstfile, 0777);
    return true;
   }
   if (@copy($srcfile, $dstfile)) {
    @chmod($dstfile, 0777);
    P_unlink($srcfile);
    return true;
   }
   if (is_readable($srcfile)) {
    pwCache::writeover($dstfile, readover($srcfile));
    if (file_exists($dstfile)) {
     @chmod($dstfile, 0777);
     P_unlink($srcfile);
     return true;
    }
   }
   return false;
  }
  /**
   * @static
   */
  function postupload($tmp_name, $filename) {
   if (strpos($filename, '..') !== false || strpos($filename, '.php.') !== false || eregi("\.php$", $filename)) {
    exit('illegal file type!');
   }
   PwUpload::createFolder(dirname($filename));
   if (function_exists("move_uploaded_file") && @move_uploaded_file($tmp_name, $filename)) {
    @chmod($filename, 0777);
    return true;
   } elseif (@copy($tmp_name, $filename)) {
    @chmod($filename, 0777);
    return true;
   } elseif (is_readable($tmp_name)) {
    pwCache::writeover($filename, readover($tmp_name));
    if (file_exists($filename)) {
     @chmod($filename, 0777);
     return true;
    }
   }
   return false;
  }
  /**
   * @static
   */
  function createFolder($path) {
   if (!is_dir($path)) {
    PwUpload::createFolder(dirname($path));
    @mkdir($path);
    @chmod($path, 0777);
    @fclose(@fopen($path . '/index.html', 'w'));
    @chmod($path . '/index.html', 0777);
   }
  }
  /**
   * @static
   */
  function savePath($ifftp, $filename, $dir) {
   global $attachdir, $timestamp;
   //zzcity modi
//   if ($ifftp) {
//    $source = D_P . 'data/tmp/' . get_date($timestamp, 'j') . '/' . str_replace('/', '_', $dir) . $filename;
//   } else {
    $source = $attachdir . '/' . $dir . $filename;
//   }
   return $source;
  }
 }
    
 /**
  * UploadBehavior
  *
  * @package Upload
  */
 class uploadBehavior {
 
  var $ftype;
  var $ifftp;
 
	var $flashatt = array();
	var $savetoalbum;
	var $albumid;
  function uploadBehavior() {
   global $db_ifftp;
   $this->ifftp = & $db_ifftp;
   $this->ftype = array();
	}

	function setFlashAtt($flashatt = null, $savetoalbum = 0, $albumid = 0) {
		if ($flashatt && is_array($flashatt)) {
			$this->flashatt = $flashatt;
		}
		$this->savetoalbum = $savetoalbum;
		$this->albumid = $albumid;
	}

	function getSaveAttach($uid) {
		$saveAttach = null;
		if ($this->flashatt && $this->savetoalbum && $this->albumid) {
			L::loadClass('saveAttach', '', false);
			$saveAttach = saveAttach::getInstance($uid, $this->albumid, count($this->flashatt));
		}
		return $saveAttach;
	}

	function execute() {
		//PwUpload::upload($this);  //zzcity modi
	}
  function allowThumb() {
   return false;
  }
 
  function allowWaterMark() {
   return false;
  }
  
  /**
   * @abstract 配置生成缩略图策略
   * @retrun array(
   *  array($filename_1, $dir_1, $thumbsize_1),
   *  array($filename_2, $dir_2, $thumbsize_2),
   *  ...
   * )
   */
  function getThumbInfo() {
   return array();
  }
  /**
   * @abstract
   */
  function allowType($key) {
  }
  /**
   * @abstract
   */
  function getFilePath($currUpload) {
  }
  /**
   * @abstract
   */
  function update($uploaddb) {
  }
 }
 function showUploadMsg($msg) {
 // if (function_exists('showExtraMsg')) {
 //  showExtraMsg($msg);
 // } else {
   Showmsg($msg);
 // }
 }
  
  //upload.class.php结束
  
  class AttUpload extends uploadBehavior {
  
 var $db;
 var $pw_attachs;
 var $post;
 var $forum;
 var $uid;

 var $ifupload;
 var $uptype;
 var $ifthumb;
 var $thumbsize;
 var $uploadmoney;
 var $uploadcredit;
 var $uploadImgNum;

 var $attachs = array();
 var $idrelate = array();
 var $replacedb = array();
 var $elementpic = array();
  
 function AttUpload($uid, $flashatt = null, $savetoalbum = 0, $albumid = 0) {
		global $db,$pwforum,$pwpost,$db_ifathumb,$db_athumbsize,$db_uploadfiletype;
  parent::uploadBehavior();

  $this->pw_attachs = L::loadDB('attachs', 'forum');
  $this->uid = $uid;
  $this->db =& $db;
  $this->forum =& $pwforum;
  $this->post =& $pwpost;

  if ($pwforum->forumset['ifthumb'] == 1) {
   $this->ifthumb  = 1;
   $this->thumbsize = $pwforum->forumset['thumbsize'];
  } elseif ($pwforum->forumset['ifthumb'] == 2) {
   $this->ifthumb  = 0;
   $this->thumbsize = 0;
  } else {
   $this->ifthumb  = $db_ifathumb;
   $this->thumbsize = $db_athumbsize;
  }
		list($uploadcredit,$uploadmoney) = explode("\t", $pwforum->forumset['uploadset']);
		$this->uploadmoney = $uploadmoney;
		$this->uploadcredit = $uploadcredit;
  $this->ftype =& $db_uploadfiletype;
  $this->uploadImgNum = 0;
  $this->uptype = 'all';
  $this->setFlashAtt($flashatt, $savetoalbum, $albumid);
 }
  
 function check() {
  global $db_allowupload;
  if (!$db_allowupload) {
   Showmsg('upload_close');
  } elseif (!$this->forum->allowupload($this->post->user, $this->post->groupid)) {
   Showmsg('upload_forum_right');
  } elseif (!$this->forum->foruminfo['allowupload'] && $this->post->_G['allowupload'] == 0) {
   Showmsg('upload_group_right');
  }
  if ($this->post->user['uploadtime'] < $GLOBALS['tdtime']) {
   $this->post->user['uploadnum'] = 0;
  }
		if ($this->post->_G['allownum'] > 0 && ($this->post->user['uploadnum'] + count($_FILES) + count($this->flashatt)) > $this->post->_G['allownum']) {
			Showmsg('upload_num_error');
  }
  if ($this->post->_G['allowupload'] == 1 && $this->uploadmoney) {
   global $credit;
   require_once(R_P.'require/credit.php');
   if ($this->uploadmoney < 0 && $credit->get($this->post->uid, $this->uploadcredit) < abs($this->uploadmoney)) {
    $GLOBALS['creditname'] = $credit->cType[$this->uploadcredit];
    Showmsg('upload_money_limit');
   }
  }
 }

 function setReplaceAtt($replacedb) {
  if ($replacedb && is_array($replacedb)) {
   $this->replacedb = $replacedb;
  }
 }

   function transfer() {
		if (empty($this->flashatt)) {
   			return false;
  		}

  		global $db_enhideset,$db_sellset,$db_ifpwcache,$timestamp;
		require_once(R_P . 'require/functions.php');
		$saveAttach = $this->getSaveAttach($this->post->uid);
		$deltmp = array();
		$attach = $this->pw_attachs->gets(array('tid' => 0, 'pid' => 0, 'uid' => $this->post->uid, 'did' => 0, 'mid' => 0));
		foreach ($attach as $rt) {
			if (!isset($this->flashatt[$rt['aid']])) {
				pwDelatt($rt['attachurl'], $this->ifftp);
				$deltmp[] = $rt['aid'];
				continue;
			}
			$saveAttach && $saveAttach->add($rt);
			$value = $this->flashatt[$rt['aid']];
			$rt['descrip'] = $value['desc'];
			$rt['special'] = intval($value['special']);
			$rt['needrvrc'] = intval($value['needrvrc']);
			$rt['ctype'] = $value['ctype'];
	   $this->attachs[$rt['aid']] = array(
	    'aid'       => $rt['aid'],
	    'name'      => $rt['name'],
	    'type'      => $rt['type'],
					'attachurl' => $rt['attachurl'],
	    'needrvrc'  => 0,
	    'special' => 0,
	    'ctype'  => '',
	    'size'      => $rt['size'],
	    'hits'      => $rt['hits'],
	    'desc'  => str_replace('\\','', $rt['descrip']),
	    'ifthumb' => $rt['ifthumb']
	   );
	   $pwSQL = array(
					'fid' => $this->forum->fid,
					'descrip' => $rt['descrip']
	   );
	   if ($rt['needrvrc'] > 0 && ($rt['special'] == 1 && $this->post->allowencode && in_array($rt['ctype'], $db_enhideset['type']) || $rt['special'] == 2 && $this->post->allowsell && in_array($rt['ctype'], $db_sellset['type']))) {
	    $this->attachs[$rt['aid']]['needrvrc'] = $pwSQL['needrvrc'] = $rt['needrvrc'];
	    $this->attachs[$rt['aid']]['special'] = $pwSQL['special']  = $rt['special'];
	    $this->attachs[$rt['aid']]['ctype']  = $pwSQL['ctype']  = $rt['ctype'];
	   }
				if ($rt['type'] == 'img') {
	    $this->uploadImgNum++;
	   }
	   $this->post->user['uploadnum']++;
	   $this->post->user['uploadtime'] = $timestamp;
	   $this->pw_attachs->updateById($rt['aid'], $pwSQL);
	   $this->ifupload = ($rt['type'] == 'img' ? 1 : ($rt['type'] == 'txt' ? 2 : 3));
	   if (($db_ifpwcache & 512) && !$rt['needrvrc'] && $rt['type'] == 'img' && !$this->elementpic) {
					$this->elementpic = array('aid' => $rt['aid'], 'attachurl' => $rt['attachurl'], 'ifthumb' => $rt['ifthumb']);
	   }
	  }
		$saveAttach && $saveAttach->execute();
		$deltmp && $this->pw_attachs->delete($deltmp);
  return true;
 }
  
 function allowType($key) {
  list($t) = explode('_', $key);
  return in_array($t, array('replace', 'attachment'));
 }

 function getFilePath($currUpload) {
  if ($currUpload['attname'] == 'replace' && isset($this->replacedb[$currUpload['id']])) {
   $arr = explode('/', $this->replacedb[$currUpload['id']]['attachurl']);
   $filename = array_pop($arr);
   $savedir  = $arr ? implode('/',$arr) . '/' : '';
  } else {
   global $timestamp;
   $prename  = substr(md5($timestamp . $currUpload['id'] . randstr(8)),10,15);
   $filename = $this->forum->fid . "_{$this->uid}_$prename." . preg_replace('/(php|asp|jsp|cgi|fcgi|exe|pl|phtml|dll|asa|com|scr|inf)/i', "scp_\\1", $currUpload['ext']);
   $savedir = $this->getSaveDir($currUpload['ext']);
  }
  return array($filename, $savedir);
 }
  
 function allowThumb() {
  return $this->ifthumb;
 }

 function getThumbInfo($filename, $dir) {
		global $db_athumbtype;
  return array(
   array($filename, 'thumb/' . $dir, $this->thumbsize),
			array($filename, 'thumb/mini/' . $dir, "200\t150\t$db_athumbtype")
  );
 }

 function allowWaterMark() {
  return $this->forum->forumset['watermark'];
 }

 function getSaveDir($ext) {
  global $db_attachdir;
  $savedir = '';
  if ($db_attachdir) {
   if ($db_attachdir == 2) {
    $savedir = "Type_$ext/";
   } elseif ($db_attachdir == 3) {
    $savedir = 'Mon_'.date('ym').'/';
   } elseif ($db_attachdir == 4) {
    $savedir = 'Day_'.date('ymd').'/';
   } else {
    $savedir = "Fid_{$this->forum->fid}/";
   }
  }
  return $savedir;
 }
  
 function update($uploaddb) {
  global $db_enhideset,$db_sellset,$timestamp,$db_ifpwcache;
		$this->transfer();
  foreach ($uploaddb as $value) {
   $value['name'] = addslashes($value['name']);
   if ($value['attname'] == 'replace' && isset($this->replacedb[$value['id']])) {
    $aid = $value['id'];
    $value['needrvrc'] = $this->replacedb[$aid]['needrvrc'];
    $value['special'] = $this->replacedb[$aid]['special'];
    $value['ctype']  = $this->replacedb[$aid]['ctype'];
    $value['descrip'] = $this->replacedb[$aid]['desc'];
    $this->pw_attachs->updateById($aid, array(
     'name'  => $value['name'],   'type'  => $value['type'],
     'size'  => $value['size'],   'attachurl' => $value['fileuploadurl'],
     'needrvrc' => $value['needrvrc'],  'special' => $value['special'],
     'ctype'  => $value['ctype'],   'uploadtime'=> $timestamp,
     'descrip' => $value['descrip'],  'ifthumb' => $value['ifthumb']
    ));
    $this->replacedb[$aid]['name'] = $value['name'];
    $this->replacedb[$aid]['type'] = $value['type'];
    $this->replacedb[$aid]['size'] = $value['size'];
    $this->replacedb[$aid]['ifthumb'] = $value['ifthumb'];
   } else {
    $value['descrip'] = S::escapeChar(S::getGP('atc_desc'.$value['id'], 'P'));
    $value['needrvrc'] = intval(S::getGP('atc_needrvrc'.$value['id'], 'P'));
    $value['special'] = intval(S::getGP('att_special'.$value['id'], 'P'));
    $value['ctype']  = S::getGP('att_ctype'.$value['id'], 'P');
    if ($value['needrvrc'] > 0 && ($value['special'] == 1 && $this->post->allowencode && in_array($value['ctype'], $db_enhideset['type']) || $value['special'] == 2 && $this->post->allowsell && in_array($value['ctype'],$db_sellset['type']))) {

    } else {
     $value['needrvrc'] = $value['special'] = 0;
     $value['ctype'] = '';
    }
    $aid = $this->pw_attachs->add(array(
     'fid'  => $this->forum->fid,   'uid'  => $this->post->uid,
     'hits'  => 0,       'name'  => $value['name'],
     'type'  => $value['type'],    'size'  => $value['size'],
     'attachurl' => $value['fileuploadurl'],  'needrvrc' => $value['needrvrc'],
     'special' => $value['special'],   'ctype'  => $value['ctype'],
     'uploadtime'=> $timestamp,     'descrip' => $value['descrip'],
     'ifthumb' => $value['ifthumb']
    ));
    $this->attachs[$aid] = array(
     'aid'       => $aid,
     'name'      => stripslashes($value['name']),
     'type'      => $value['type'],
     'attachurl' => $value['fileuploadurl'],
     'needrvrc'  => $value['needrvrc'],
     'special' => $value['special'],
     'ctype'  => $value['ctype'],
     'size'      => $value['size'],
     'hits'      => 0,
     'desc'  => str_replace('\\','',$value['descrip']),
     'ifthumb' => $value['ifthumb']
    );
    $this->idrelate[$aid] = $value['id'];
    $this->post->user['uploadnum']++;
    $this->post->user['uploadtime'] = $timestamp;
   }
   if ($value['type'] == 'img') {
    $this->ifupload = 1;
    $this->uploadImgNum++;
   } else {
    $this->ifupload = ($value['type'] == 'txt') ? 2 : 3;
   }
   //Start elementupdate
   if (($db_ifpwcache & 512) && $value['type'] == 'img' && !$value['needrvrc'] && !$this->elementpic) {
    $this->elementpic = array('aid' => $aid, 'attachurl' => $value['fileuploadurl'], 'ifthumb' => $value['ifthumb']);
   }
   //End elementupdate
  }
  $this->addCredit();
  return true;
 }
  
 function addCredit() {
  if ($this->attachs && $this->post->_G['allowupload'] == 1 && $this->uploadmoney) {
   global $credit,$onlineip;
   $credit->addLog('topic_upload', array($this->uploadcredit => $this->uploadmoney), array(
    'uid'  => $this->post->uid,
    'username' => $this->post->username,
    'ip'  => $onlineip,
    'fname'  => $this->forum->name
   ));
   if (!$credit->set($this->post->uid, $this->uploadcredit, $this->uploadmoney, false)) {
    require_once(R_P.'require/updateforum.php');
    delete_att($this->attachs);
    Showmsg('undefined_action');
   }
  }
 }
  
 function getIdRelate() {
  return $this->idrelate;
 }

 function getAttachs() {
  return $this->attachs;
 }

 function getImages($num) {
  $imgs = array();
  foreach ($this->attachs as $key => $value) {
   if ($value['type'] == 'img') {
    $imgs[] = array('attachurl' => $value['attachurl'], 'ifthumb' => $value['ifthumb']);
    $num = $num - 1;
    if (empty($num)) break;
   }
  }
  return $imgs;
 }

 function getUploadImgNum() {
  return $this->uploadImgNum;
 }

 function getAids() {
  return array_keys($this->attachs);
 }

 function getAttachNum() {
  return count($this->attachs);
 }
  }
  
  //attupload.class.php结束

// /*上传错误检查
// $return = PwUpload::checkUpload();
// $return !== true && Showmsg($return);
// end*/
// if (PwUpload::getUploadNum() || $flashatt) {
//  S::gp(array('savetoalbum', 'albumid'), 'P', 2);
//  $postdata->att = new AttUpload($winduid, $flashatt, $savetoalbum, $albumid);
//  $postdata->att->check();
// }
   S::gp(array('savetoalbum', 'albumid'), 'P', 2);
  $postdata->att = new AttUpload($winduid, $flashatt, $savetoalbum, $albumid);
//  $postdata->att->check();
  //$postdata->att->transfer();
  PwUpload::upload($postdata->att,$etattachs,$atc_content); //zzcity modi
 }
//zzcity add end
 
 
	!$postdata->setContent($atc_content) && Showmsg('post_price_limit');

 $postdata->setConvert($atc_convert, $atc_autourl);
 $postdata->setAnonymous($atc_anonymous);
 $postdata->setHideatt($atc_hideatt);
 $postdata->setIconid($atc_iconid);
 if(empty($atc_html)){
  $postdata->setIfsign($atc_usesign, $atc_html);}
 else{
  $postdata->data['ifsign']=2; 
 }
 
 $postdata->setHide($atc_hide);
 $postdata->setEnhide($atc_requireenhide, $atc_rvrc, $atc_enhidetype);
 $postdata->setSell($atc_requiresell, $atc_money, $atc_credittype);
	$postdata->setAtUsers($_usernames);
  //$replypost->checkdata();
  $postdata->conentCheck();
//
// L::loadClass('attupload', 'upload', false);
// /*上传错误检查
// $return = PwUpload::checkUpload();
// $return !== true && Showmsg($return);
// end*/
// if (PwUpload::getUploadNum() || $flashatt) {
//  S::gp(array('savetoalbum', 'albumid'), 'P', 2);
//  $postdata->att = new AttUpload($winduid, $flashatt, $savetoalbum, $albumid);
//  $postdata->att->check();
// }

 $replypost->setToUser($replytouser);
 $postdata->iscontinue = (int)$iscontinue;
	$postdata->setIfGoLastPage($go_lastpage);
 $replypost->execute($postdata);
 $pid = $replypost->getNewId();
	// defend start	
	CloudWind::yunUserDefend('postreply', $winduid, $windid, $timestamp, ($cloud_information[1] ? $timestamp - $cloud_information[1] : 0), ($pid ? 101 : 102),'',$postdata->data['content'],'','');
	// defend end
 if ($winduid && $tpcarray['special'] == 5) {
  L::loadClass("post_5", 'forum/special', false);
  $postdebate = new postSpecial($pwpost);
  $postdebate->reply($tid, $pid);
 }
 
 	echo('[ok]pid='.$pid); 
	
//	pwHook::runHook('after_reply');	
	//defend start
	CloudWind::YunPostDefend ( $winduid, $windid, $groupid, $pid, $atc_title, $atc_content, 'reply',array('tid'=>$tid,'fid'=>$fid,'forumname'=>$pwforum->foruminfo['name']) );
	//defend end
 
//	//job sign
//	/*
//	require_once(R_P.'require/functions.php');
//	$_cacheService = Perf::gatherCache('pw_threads');
//	$thread = ($page>1) ? $_cacheService->getThreadByThreadId($tid) : $_cacheService->getThreadAndTmsgByThreadId($tid);	
//	initJob($winduid,"doReply",array('tid'=>$tid,'user'=>$thread['author']));
//	*/
//	$j_p = "read.php?tid=$tid&ds=1&page=e#a";
//	if ($db_htmifopen)
//		$j_p = urlRewrite ( $j_p );
//	$pinfo = getLangInfo('refreshto', 'enter_thread');
//	defined('AJAX') && $pinfo = "success\t" . $j_p;
//	$flag = false;
//	if (!$iscontinue && $postdata->getIfcheck()) {
//		if (!isset($_POST['go_lastpage']) && 'ajax_addfloor' == $_POST['type']) {
//			require_once S::escapePath(R_P.'require/addfloor.php');
//			exit;
//		}
//		defined('AJAX') && $flag && ($pinfo = "continue\t" . getLangInfo('refreshto', $pinfo));
//	} elseif ($go_lastpage && !$postdata->getIfcheck()) {
//		$pinfo = getLangInfo('refreshto', 'success_check');
//	}
//	refreshto($j_p,$pinfo);
// }
//}
//  require/postreply.php结束

//} elseif ($action == "modify") {
// require_once(R_P.'require/postmodify.php');
//} else {
// Showmsg('undefined_action');
//}
?>