<?php

foreach($_POST as $key=>$value){
        $_GET[$key]=$value;
}


$_GET['mod']='post'; //zzcityadd
$_GET['action']='reply'; //zzcityadd
if(isset($_GET['adddynamic'])){
    $_POST['adddynamic'] =$_GET['adddynamic'] = trim($_GET['adddynamic'])=='' ? '' : $_GET['adddynamic']; //zzcity add 如果未设置则默认回复不转播
}else{
    $_POST['adddynamic'] =$_GET['adddynamic']='';
}

define('APPTYPEID', 2);
define('CURSCRIPT', 'forum');
define('DISABLEXSSCHECK', true);
require './source/class/class_core.php';
require './source/function/function_forum.php';

$modarray = array('ajax','announcement','attachment','forumdisplay',
    'group','image','index','medal','misc','modcp','notice','post','redirect',
    'relatekw','relatethread','rss','topicadmin','trade','viewthread','tag','collection','guide'
);

$modcachelist = array(
    'index'        => array('announcements', 'onlinelist', 'forumlinks',
            'heats', 'historyposts', 'onlinerecord', 'userstats', 'diytemplatenameforum'),
    'forumdisplay'    => array('smilies', 'announcements_forum', 'globalstick', 'forums',
            'onlinelist', 'forumstick', 'threadtable_info', 'threadtableids', 'stamps', 'diytemplatenameforum'),
    'viewthread'    => array('smilies', 'smileytypes', 'forums', 'usergroups',
            'stamps', 'bbcodes', 'smilies',    'custominfo', 'groupicon', 'stamps',
            'threadtableids', 'threadtable_info', 'posttable_info', 'diytemplatenameforum'),
    'redirect'    => array('threadtableids', 'threadtable_info', 'posttable_info'),
    'post'        => array('bbcodes_display', 'bbcodes', 'smileycodes', 'smilies', 'smileytypes',
            'domainwhitelist', 'albumcategory'),
    'space'        => array('fields_required', 'fields_optional', 'custominfo'),
    'group'        => array('grouptype', 'diytemplatenamegroup'),
);

$mod = !in_array(C::app()->var['mod'], $modarray) ? 'index' : C::app()->var['mod'];


define('CURMODULE', $mod);
$cachelist = array();
if(isset($modcachelist[CURMODULE])) {
	$cachelist = $modcachelist[CURMODULE];

	$cachelist[] = 'plugin';
	$cachelist[] = 'pluginlanguage_system';
}
if(C::app()->var['mod'] == 'group') {
    $_G['basescript'] = 'group';
}

C::app()->cachelist = $cachelist;
C::app()->init();
//zzcity add
$member = array();
$member = c::t('common_member')->fetch_by_username($_POST['username']);
    $cookietime=$_G['gp_cookietime'] ? 2592000 : 0;
    $_G['uid'] = $member['uid'];
    $_G['username'] = $member['username'];
    $_G['adminid'] = $member['adminid'];
    $_G['groupid'] = $member['groupid'];
    $_G['formhash'] = formhash();
    $_G['session']['invisible'] = getuserprofile('invisible');
    $_G['member'] = $member;
    loadcache('usergroup_'.$_G['groupid']);
    C::app()->session->isnew = true;
    C::app()->session->updatesession();

    dsetcookie('auth', authcode("{$member['password']}\t{$member['uid']}", 'ENCODE'), $cookietime, 1, true);
    dsetcookie('loginuser');
    dsetcookie('activationauth');
    dsetcookie('pmnum');

    include_once libfile('function/stat');
    updatestat('login', 1);
    if(defined('IN_MOBILE')) {
        updatestat('mobilelogin', 1);
    }
    if($_G['setting']['connect']['allow'] && $_G['member']['conisbind']) {
        updatestat('connectlogin', 1);
    }
    $rule = updatecreditbyaction('daylogin', $_G['uid']);
    if(!$rule['updatecredit']) {
        checkusergroup($_G['uid']);
    }
    $_G['gp_htmlon']=$_GET['htmlon'] = trim($_GET['htmlon'])=='' ? '1' : $_GET['htmlon'];
//zzcity
loadforum();

//zzcityadd
$_G['tid']=$_POST['tid'];
$_G['group']['allowhtml']=$_G['gp_htmlon'];
$_G['forum']['allowhtml']=$_G['gp_htmlon'];

$zzhour =!isset($_G['gp_zzhour']) ? '1' : intval($_G['gp_zzhour']); //zzcity add

$replyno =!isset($_G['gp_replyno']) ? '1' : intval($_G['gp_replyno']); //zzcity add

$zztimestamp =time()-$zzhour*60*60; //zzcity add

$zztimestamp =$_G['timestamp']= $zztimestamp+$replyno*5*60+rand(0,4)*60;  //zzcity add

//zzcity

set_rssauth();
//runhooks();
$navtitle = str_replace('{bbname}', $_G['setting']['bbname'], $_G['setting']['seotitle']['forum']);

//require DISCUZ_ROOT.'./source/module/forum/forum_'.$mod.'.php';替换开始
if(!defined('IN_DISCUZ')) {
 exit('Access Denied');
}
define('NOROBOT', TRUE);

cknewuser();

require_once libfile('class/credit');
require_once libfile('function/post');


$pid = intval(getgpc('pid'));
$sortid = intval(getgpc('sortid'));
$typeid = intval(getgpc('typeid'));
$special = intval(getgpc('special'));

$postinfo = array('subject' => '');
$thread = array('readperm' => '', 'pricedisplay' => '', 'hiddenreplies' => '');

$_G['forum_dtype'] = $_G['forum_checkoption'] = $_G['forum_optionlist'] = $tagarray = $_G['forum_typetemplate'] = array();


if($sortid) {
    require_once libfile('post/threadsorts', 'include');
}

if($_G['forum']['status'] == 3) {
    if(!helper_access::check_module('group')) {
        showmessage('group_status_off');
    }
    require_once libfile('function/group');
    $status = groupperm($_G['forum'], $_G['uid'], 'post');
    if($status == -1) {
        //showmessage('forum_not_group', 'index.php');
        exit('[err]该版块不是群组[/err]');
    } elseif($status == 1) {
        //showmessage('forum_group_status_off');
        exit('[err]该群组已经关闭[/err]');
    } elseif($status == 2) {
        //showmessage('forum_group_noallowed', "forum.php?mod=group&fid=$_G[fid]");
        exit('[err]您没有权限访问该群组[/err]');
    } elseif($status == 3) {
        //showmessage('forum_group_moderated', "forum.php?mod=group&fid=$_G[fid]");
        exit('[err]请等待群主审核[/err]');
    } elseif($status == 4) {
        if($_G['uid']) {
            //showmessage('forum_group_not_groupmember', "", array('fid' => $_G['fid']), array('showmsg' => 1));
            exit('[err]非本群组成员不能发帖[/err]');
        } else {
            //showmessage('forum_group_not_groupmember_guest', "", array('fid' => $_G['fid']), array('showmsg' => 1, 'login' => 1));
            exit('[err]非本群组成员不能发帖[/err]');
        }
    } elseif($status == 5) {
        //showmessage('forum_group_moderated', "", array('fid' => $_G['fid']), array('showmsg' => 1));
        exit('[err]请等待群主审核[/err]');
    }
}

/*
if(empty($_GET['action'])) {
    showmessage('undefined_action', NULL);
} elseif($_GET['action'] == 'albumphoto') {
    require libfile('post/albumphoto', 'include');
} elseif(($_G['forum']['simple'] & 1) || $_G['forum']['redirect']) {
    showmessage('forum_disablepost');
}
*/
require_once libfile('function/discuzcode');
$space = array();
space_merge($space, 'field_home');


//if($_GET['action'] == 'reply') {
    $addfeedcheck = !empty($space['privacy']['feed']['newreply']) ? 'checked="checked"': '';
//} else {
//    $addfeedcheck = !empty($space['privacy']['feed']['newthread']) ? 'checked="checked"': '';
//}

$navigation = $navtitle = '';

if(!empty($_GET['cedit'])) {
    unset($_G['inajax'], $_GET['infloat'], $_GET['ajaxtarget'], $_GET['handlekey']);
}

if($_GET['action'] == 'edit' || $_GET['action'] == 'reply') {

    $thread = C::t('forum_thread')->fetch($_G['tid']);
    if(!$_G['forum_auditstatuson'] && !($thread['displayorder']>=0 || (in_array($thread['displayorder'], array(-4, -2)) && $thread['authorid']==$_G['uid']))) {
        $thread = array();
    }
    if(!empty($thread)) {

        if($thread['readperm'] && $thread['readperm'] > $_G['group']['readaccess'] && !$_G['forum']['ismoderator'] && $thread['authorid'] != $_G['uid']) {
//   showmessage('thread_nopermission', NULL, array('readperm' => $thread['readperm']), array('login' => 1));
   exit('[err]'.lang('message', 'thread_nopermission',array('readperm' => $thread['readperm']), array('login' => 1)).'[/err]');
  }

  $_G['fid'] = $thread['fid'];
  $special = $thread['special'];

 } else {
//  showmessage('thread_nonexistence');
  exit('[err]'.lang('message', 'thread_nonexistence').'[/err]');
 }

    if($thread['closed'] == 1 && !$_G['forum']['ismoderator']) {
//  showmessage('post_thread_closed');
  exit('[err]'.lang('message', 'post_thread_closed').'[/err]');
 }

}

if($_G['forum']['status'] == 3) {
    $returnurl = 'forum.php?mod=forumdisplay&fid='.$_G['fid'].(!empty($_GET['extra']) ? '&action=list&'.preg_replace("/^(&)*/", '', $_GET['extra']) : '').'#groupnav';
    $nav = get_groupnav($_G['forum']);
    $navigation = ' <em>&rsaquo;</em> <a href="group.php">'.$_G['setting']['navs'][3]['navname'].'</a> '.$nav['nav'];
} else {
    loadcache('forums');
    $returnurl = 'forum.php?mod=forumdisplay&fid='.$_G['fid'].(!empty($_GET['extra']) ? '&'.preg_replace("/^(&)*/", '', $_GET['extra']) : '');
    $navigation = ' <em>&rsaquo;</em> <a href="forum.php">'.$_G['setting']['navs'][2]['navname'].'</a>';

    if($_G['forum']['type'] == 'sub') {
        $fup = $_G['cache']['forums'][$_G['forum']['fup']]['fup'];
        $t_link = $_G['cache']['forums'][$fup]['type'] == 'group' ? 'forum.php?gid='.$fup : 'forum.php?mod=forumdisplay&fid='.$fup;
        $navigation .= ' <em>&rsaquo;</em> <a href="'.$t_link.'">'.($_G['cache']['forums'][$fup]['name']).'</a>';
    }

    if($_G['forum']['fup']) {
        $fup = $_G['forum']['fup'];
        $t_link = $_G['cache']['forums'][$fup]['type'] == 'group' ? 'forum.php?gid='.$fup : 'forum.php?mod=forumdisplay&fid='.$fup;
        $navigation .= ' <em>&rsaquo;</em> <a href="'.$t_link.'">'.($_G['cache']['forums'][$fup]['name']).'</a>';
    }

    $t_link = 'forum.php?mod=forumdisplay&fid='.$_G['fid'].($_GET['extra'] && !IS_ROBOT ? '&'.$_GET['extra'] : '');
    $navigation .= ' <em>&rsaquo;</em> <a href="'.$t_link.'">'.($_G['forum']['name']).'</a>';

    unset($t_link, $t_name);
}

periodscheck('postbanperiods');

//if($_G['forum']['password'] && $_G['forum']['password'] != $_G['cookie']['fidpw'.$_G['fid']]) {
// showmessage('forum_passwd', "forum.php?mod=forumdisplay&fid=$_G[fid]");
//}

/*if(empty($_G['forum']['allowview'])) {
 if(!$_G['forum']['viewperm'] && !$_G['group']['readaccess']) {
  showmessage('group_nopermission', NULL, array('grouptitle' => $_G['group']['grouptitle']), array('login' => 1));
 } elseif($_G['forum']['viewperm'] && !forumperm($_G['forum']['viewperm'])) {
  showmessagenoperm('viewperm', $_G['fid']);
 }
} elseif($_G['forum']['allowview'] == -1) {
 showmessage('forum_access_view_disallow');
}
*/
formulaperm($_G['forum']['formulaperm']);

/*
if(!$_G['adminid'] && $_G['setting']['newbiespan'] && (!getuserprofile('lastpost') || TIMESTAMP - getuserprofile('lastpost') < $_G['setting']['newbiespan'] * 60) && TIMESTAMP - $_G['member']['regdate'] < $_G['setting']['newbiespan'] * 60) {
 showmessage('post_newbie_span', '', array('newbiespan' => $_G['setting']['newbiespan']));
}
*/
$special = $special > 0 && $special < 7 || $special == 127 ? intval($special) : 0;

$_G['forum']['allowpostattach'] = isset($_G['forum']['allowpostattach']) ? $_G['forum']['allowpostattach'] : '';
$_G['group']['allowpostattach'] = $_G['forum']['allowpostattach'] != -1 && ($_G['forum']['allowpostattach'] == 1 || (!$_G['forum']['postattachperm'] && $_G['group']['allowpostattach']) || ($_G['forum']['postattachperm'] && forumperm($_G['forum']['postattachperm'])));
$_G['forum']['allowpostimage'] = isset($_G['forum']['allowpostimage']) ? $_G['forum']['allowpostimage'] : '';
$_G['group']['allowpostimage'] = $_G['forum']['allowpostimage'] != -1 && ($_G['forum']['allowpostimage'] == 1 || (!$_G['forum']['postimageperm'] && $_G['group']['allowpostimage']) || ($_G['forum']['postimageperm'] && forumperm($_G['forum']['postimageperm'])));
$_G['group']['attachextensions'] = $_G['forum']['attachextensions'] ? $_G['forum']['attachextensions'] : $_G['group']['attachextensions'];
require_once libfile('function/upload');
$swfconfig = getuploadconfig($_G['uid'], $_G['fid']);
$imgexts = str_replace(array(';', '*.'), array(', ', ''), $swfconfig['imageexts']['ext']);
$allowuploadnum = $allowuploadtoday = TRUE;
if($_G['group']['allowpostattach'] || $_G['group']['allowpostimage']) {
 if($_G['group']['maxattachnum']) {
  $allowuploadnum = $_G['group']['maxattachnum'] - getuserprofile('todayattachs');
  $allowuploadnum = $allowuploadnum < 0 ? 0 : $allowuploadnum;
  if(!$allowuploadnum) {
   $allowuploadtoday = false;
  }
 }
 if($_G['group']['maxsizeperday']) {
  $allowuploadsize = $_G['group']['maxsizeperday'] - getuserprofile('todayattachsize');
  $allowuploadsize = $allowuploadsize < 0 ? 0 : $allowuploadsize;
  if(!$allowuploadsize) {
   $allowuploadtoday = false;
  }
  $allowuploadsize = $allowuploadsize / 1048576 >= 1 ? round(($allowuploadsize / 1048576), 1).'MB' : round(($allowuploadsize / 1024)).'KB';
 }
}
$allowpostimg = $_G['group']['allowpostimage'] && $imgexts;
$enctype = ($_G['group']['allowpostattach'] || $_G['group']['allowpostimage']) ? 'enctype="multipart/form-data"' : '';
$maxattachsize_mb = $_G['group']['maxattachsize'] / 1048576 >= 1 ? round(($_G['group']['maxattachsize'] / 1048576), 1).'MB' : round(($_G['group']['maxattachsize'] / 1024)).'KB';

$_G['group']['maxprice'] = isset($_G['setting']['extcredits'][$_G['setting']['creditstrans']]) ? $_G['group']['maxprice'] : 0;

$extra = !empty($_GET['extra']) ? rawurlencode($_GET['extra']) : '';
$notifycheck = empty($emailnotify) ? '' : 'checked="checked"';
$stickcheck = empty($sticktopic) ? '' : 'checked="checked"';
$digestcheck = empty($addtodigest) ? '' : 'checked="checked"';

$subject = isset($_GET['subject']) ? dhtmlspecialchars(censor(trim($_GET['subject']))) : '';
$subject = !empty($subject) ? str_replace("\t", ' ', $subject) : $subject;
$message = isset($_GET['message']) ? censor($_GET['message']) : '';

$polloptions = isset($polloptions) ? censor(trim($polloptions)) : '';
$readperm = isset($_GET['readperm']) ? intval($_GET['readperm']) : 0;
$price = isset($_GET['price']) ? intval($_GET['price']) : 0;

/*
if(empty($bbcodeoff) && !$_G['group']['allowhidecode'] && !empty($message) && preg_match("/\[hide=?\d*\].+?\[\/hide\]/is", preg_replace("/(\[code\](.+?)\[\/code\])/is", ' ', $message))) {
 showmessage('post_hide_nopermission');
}
*/

$urloffcheck = $usesigcheck = $smileyoffcheck = $codeoffcheck = $htmloncheck = $emailcheck = '';

$seccodecheck = ($_G['setting']['seccodestatus'] & 4) && (!$_G['setting']['seccodedata']['minposts'] || getuserprofile('posts') < $_G['setting']['seccodedata']['minposts']);
$secqaacheck = $_G['setting']['secqaa']['status'] & 2 && (!$_G['setting']['secqaa']['minposts'] || getuserprofile('posts') < $_G['setting']['secqaa']['minposts']);

$_G['group']['allowpostpoll'] = $_G['group']['allowpost'] && $_G['group']['allowpostpoll'] && ($_G['forum']['allowpostspecial'] & 1);
$_G['group']['allowposttrade'] = $_G['group']['allowpost'] && $_G['group']['allowposttrade'] && ($_G['forum']['allowpostspecial'] & 2);
$_G['group']['allowpostreward'] = $_G['group']['allowpost'] && $_G['group']['allowpostreward'] && ($_G['forum']['allowpostspecial'] & 4);
$_G['group']['allowpostactivity'] = $_G['group']['allowpost'] && $_G['group']['allowpostactivity'] && ($_G['forum']['allowpostspecial'] & 8);
$_G['group']['allowpostdebate'] = $_G['group']['allowpost'] && $_G['group']['allowpostdebate'] && ($_G['forum']['allowpostspecial'] & 16);
$usesigcheck = $_G['uid'] && $_G['group']['maxsigsize'] ? 'checked="checked"' : '';
$ordertypecheck = !empty($thread['tid']) && getstatus($thread['status'], 4) ? 'checked="checked"' : '';
$imgcontentcheck = !empty($thread['tid']) && getstatus($thread['status'], 15) ? 'checked="checked"' : '';
$specialextra = !empty($_GET['specialextra']) ? $_GET['specialextra'] : '';
$_G['forum']['threadplugin'] = dunserialize($_G['forum']['threadplugin']);

if($specialextra && $_G['group']['allowpost'] && $_G['setting']['threadplugins'] &&
    (!array_key_exists($specialextra, $_G['setting']['threadplugins']) ||
    !@in_array($specialextra, is_array($_G['forum']['threadplugin']) ? $_G['forum']['threadplugin'] : dunserialize($_G['forum']['threadplugin'])) ||
    !@in_array($specialextra, $_G['group']['allowthreadplugin']))) {
    $specialextra = '';
}
if($special == 3 && !isset($_G['setting']['extcredits'][$_G['setting']['creditstrans']])) {
    //showmessage('reward_credits_closed');
    exit('[err]交易积分被关闭，请联系管理员[/err]');
}
$_G['group']['allowanonymous'] = $_G['forum']['allowanonymous'] || $_G['group']['allowanonymous'] ? 1 : 0;

if($_GET['action'] == 'newthread' && $_G['forum']['allowspecialonly'] && !$special) {
    if($_G['group']['allowpostpoll']) {
        $special = 1;
    } elseif($_G['group']['allowposttrade']) {
        $special = 2;
    } elseif($_G['group']['allowpostreward']) {
        $special = 3;
    } elseif($_G['group']['allowpostactivity']) {
        $special = 4;
    } elseif($_G['group']['allowpostdebate']) {
        $special = 5;
    } elseif($_G['group']['allowpost'] && $_G['setting']['threadplugins'] && $_G['group']['allowthreadplugin']) {
		if(empty($_GET['specialextra'])) {
			foreach($_G['forum']['threadplugin'] as $tpid) {
				if(array_key_exists($tpid, $_G['setting']['threadplugins']) && @in_array($tpid, $_G['group']['allowthreadplugin'])){
					$specialextra=$tpid;
					break;
				}
			}
		}
        $threadpluginary = array_intersect($_G['forum']['threadplugin'], $_G['group']['allowthreadplugin']);
        $specialextra = in_array($specialextra, $threadpluginary) ? $specialextra : '';
    }

 if(!$special && !$specialextra) {
  //showmessage('group_nopermission', NULL, array('grouptitle' => $_G['group']['grouptitle']), array('login' => 1));
    exit('[err]您所在的用户组无法进行此操作[/err]');
 }
}
if(!$sortid && !$specialextra) {
 $postspecialcheck[$special] = ' class="a"';
}


$editorid = 'e';
$_G['setting']['editoroptions'] = str_pad(decbin($_G['setting']['editoroptions']), 3, 0, STR_PAD_LEFT);
$editormode = $_G['setting']['editoroptions']{0};
$allowswitcheditor = $_G['setting']['editoroptions']{1};
$editor = array(
 'editormode' => $editormode,
 'allowswitcheditor' => $allowswitcheditor,
 'allowhtml' => $_G['forum']['allowhtml'],
 'allowsmilies' => $_G['forum']['allowsmilies'],
 'allowbbcode' => $_G['forum']['allowbbcode'],
 'allowimgcode' => $_G['forum']['allowimgcode'],
 'allowresize' => 1,
 'allowchecklength' => 1,
 'allowtopicreset' => 1,
 'textarea' => 'message',
 'simplemode' => !isset($_G['cookie']['editormode_'.$editorid]) ? !$_G['setting']['editoroptions']{2} : $_G['cookie']['editormode_'.$editorid],
);
if($specialextra) {
 $special = 127;
}


if($_GET['action'] == 'newthread') {
    $policykey = 'post';
} elseif($_GET['action'] == 'reply') {
    $policykey = 'reply';
} else {
    $policykey = '';
}
if($policykey) {
    $postcredits = $_G['forum'][$policykey.'credits'] ? $_G['forum'][$policykey.'credits'] : $_G['setting']['creditspolicy'][$policykey];
}

$albumlist = array();
if(helper_access::check_module('album') && $_G['group']['allowupload'] && $_G['uid']) {
    $query = C::t('home_album')->fetch_all_by_uid($_G['uid'], 'updatetime');
    foreach($query as $value) {
        if($value['picnum']) {
            $albumlist[] = $value;
        }
    }
}

$posturl = "action=$_GET[action]&fid=$_G[fid]".
    (!empty($_G['tid']) ? "&tid=$_G[tid]" : '').
    (!empty($pid) ? "&pid=$pid" : '').
    (!empty($special) ? "&special=$special" : '').
    (!empty($sortid) ? "&sortid=$sortid" : '').
    (!empty($typeid) ? "&typeid=$typeid" : '').
    (!empty($_GET['firstpid']) ? "&firstpid=$firstpid" : '').
    (!empty($_GET['addtrade']) ? "&addtrade=$addtrade" : '');

if($_GET['action'] == 'reply') {
    check_allow_action('allowreply');
} else {
    check_allow_action('allowpost');
}

if($special == 4) {
    $_G['setting']['activityfield'] = $_G['setting']['activityfield'] ? dunserialize($_G['setting']['activityfield']) : array();
}
if(helper_access::check_module('album') && $_G['group']['allowupload'] && $_G['setting']['albumcategorystat'] && !empty($_G['cache']['albumcategory'])) {
    require_once libfile('function/portalcp');
}
$navtitle = lang('core', 'title_'.$_GET['action'].'_post');
/*
if($_GET['action'] == 'newthread' || $_GET['action'] == 'newtrade') {
    loadcache('groupreadaccess');
    $navtitle .= ' - '.$_G['forum']['name'];
    require_once libfile('post/newthread', 'include');
} elseif($_GET['action'] == 'reply') {
    $navtitle .= ' - '.$thread['subject'].' - '.$_G['forum']['name'];
    require_once libfile('post/newreply', 'include');
} elseif($_GET['action'] == 'edit') {
    loadcache('groupreadaccess');
    $navtitle .= ' - '.$thread['subject'].' - '.$_G['forum']['name'];
    require_once libfile('post/editpost', 'include');
} elseif($_GET['action'] == 'newtrade') {
    $navtitle .= ' - '.$_G['forum']['name'];
    require_once libfile('post/newtrade', 'include');
}
*/

//require_once libfile('post/newreply', 'include');替换开始
//if(!defined('IN_DISCUZ')) {
// exit('Access Denied');
//}

require_once libfile('function/forumlist');

$isfirstpost = 0;
$_G['group']['allowimgcontent'] = 0;
$showthreadsorts = 0;
$quotemessage = '';
/*
if($special == 5) {
    $debate = array_merge($thread, daddslashes(C::t('forum_debate')->fetch($_G['tid'])));
    $firststand = C::t('forum_debatepost')->get_firststand($_G['tid'], $_G['uid']);
    $stand = $firststand ? $firststand : intval($_GET['stand']);

    if($debate['endtime'] && $debate['endtime'] < TIMESTAMP) {
        showmessage('debate_end');
    }
}

if(!$_G['uid'] && !((!$_G['forum']['replyperm'] && $_G['group']['allowreply']) || ($_G['forum']['replyperm'] && forumperm($_G['forum']['replyperm'])))) {
    showmessage('replyperm_login_nopermission', NULL, array(), array('login' => 1));
} elseif(empty($_G['forum']['allowreply'])) {
    if(!$_G['forum']['replyperm'] && !$_G['group']['allowreply']) {
        showmessage('replyperm_none_nopermission', NULL, array(), array('login' => 1));
    } elseif($_G['forum']['replyperm'] && !forumperm($_G['forum']['replyperm'])) {
        showmessagenoperm('replyperm', $_G['forum']['fid']);
    }
} elseif($_G['forum']['allowreply'] == -1) {
    showmessage('post_forum_newreply_nopermission', NULL);
}

if(!$_G['uid'] && ($_G['setting']['need_avatar'] || $_G['setting']['need_email'] || $_G['setting']['need_friendnum'])) {
    showmessage('replyperm_login_nopermission', NULL, array(), array('login' => 1));
}
*/
if(empty($thread)) {
// showmessage('thread_nonexistence');
 exit('[err]'.lang('message', 'thread_nonexistence').'[/err]');
} elseif($thread['price'] > 0 && $thread['special'] == 0 && !$_G['uid']) {
// showmessage('group_nopermission', NULL, array('grouptitle' => $_G['group']['grouptitle']), array('login' => 1));
 exit('[err]'.lang('message', 'group_nopermission',array('grouptitle' => $_G['group']['grouptitle']), array('login' => 1)).'[/err]');
}

//checklowerlimit('reply', 0, 1, $_G['forum']['fid']);
if($_G['setting']['commentnumber'] && !empty($_GET['comment'])) {
    if(!submitcheck('commentsubmit', 0, $seccodecheck, $secqaacheck)) {
//        showmessage('submitcheck_error', NULL);
      exit('[err]'.lang('message', 'submitcheck_error').'[/err]');
    }
    $post = C::t('forum_post')->fetch('tid:'.$_G['tid'], $_GET['pid']);
    if(!$post) {
//        showmessage('post_nonexistence', NULL);
      exit('[err]'.lang('message', 'post_nonexistence').'[/err]');
        
    }
/*
    if($thread['closed'] && !$_G['forum']['ismoderator'] && !$thread['isgroup']) {
        showmessage('post_thread_closed');
    } elseif(!$thread['isgroup'] && $post_autoclose = checkautoclose($thread)) {
        showmessage($post_autoclose, '', array('autoclose' => $_G['forum']['autoclose']));
    } elseif(checkflood()) {
        showmessage('post_flood_ctrl', '', array('floodctrl' => $_G['setting']['floodctrl']));
    } elseif(checkmaxperhour('pid')) {
        showmessage('post_flood_ctrl_posts_per_hour', '', array('posts_per_hour' => $_G['group']['maxpostsperhour']));
    }
*/
    $commentscore = '';
    if(!empty($_GET['commentitem']) && !empty($_G['uid']) && $post['authorid'] != $_G['uid']) {
        foreach($_GET['commentitem'] as $itemk => $itemv) {
            if($itemv !== '') {
                $commentscore .= strip_tags(trim($itemk)).': <i>'.intval($itemv).'</i> ';
            }
        }
    }
    $comment = cutstr(($commentscore ? $commentscore.'<br />' : '').censor(trim(dhtmlspecialchars($_GET['message'])), '***'), 200, ' ');
    if(!$comment) {
//  showmessage('post_sm_isnull');
        exit('[err]'.lang('message', 'post_sm_isnull').'[/err]');
    }
    C::t('forum_postcomment')->insert(array(
        'tid' => $post['tid'],
        'pid' => $post['pid'],
        'author' => $_G['username'],
        'authorid' => $_G['uid'],
        'dateline' => $zztimestamp,
        'comment' => $comment,
        'score' => $commentscore ? 1 : 0,
        'useip' => $_G['clientip'],
    ));
    C::t('forum_post')->update('tid:'.$_G['tid'], $_GET['pid'], array('comment' => 1));
	$comments = $thread['comments'] ? $thread['comments'] + 1 : C::t('forum_postcomment')->count_by_tid($_G['tid']);
	C::t('forum_thread')->update($_G['tid'], array('comments' => $comments));
    !empty($_G['uid']) && updatepostcredits('+', $_G['uid'], 'reply', $_G['fid']);
    if(!empty($_G['uid']) && $_G['uid'] != $post['authorid']) {
        notification_add($post['authorid'], 'pcomment', 'comment_add', array(
            'tid' => $_G['tid'],
            'pid' => $_GET['pid'],
            'subject' => $thread['subject'],
			'from_id' => $_G['tid'],
			'from_idtype' => 'pcomment',
            'commentmsg' => cutstr(str_replace(array('[b]', '[/b]', '[/color]'), '', preg_replace("/\[color=([#\w]+?)\]/i", "", $comment)), 200)
        ));
    }
    update_threadpartake($post['tid']);
    $pcid = C::t('forum_postcomment')->fetch_standpoint_by_pid($_GET['pid']);
    $pcid = $pcid['id'];
    if(!empty($_G['uid']) && $_GET['commentitem']) {
        $totalcomment = array();
        foreach(C::t('forum_postcomment')->fetch_all_by_pid_score($_GET['pid'], 1) as $comment) {
            $comment['comment'] = addslashes($comment['comment']);
            if(strexists($comment['comment'], '<br />')) {
                if(preg_match_all("/([^:]+?):\s<i>(\d+)<\/i>/", $comment['comment'], $a)) {
                    foreach($a[1] as $k => $itemk) {
                        $totalcomment[trim($itemk)][] = $a[2][$k];
                    }
                }
            }
        }
        $totalv = '';
        foreach($totalcomment as $itemk => $itemv) {
            $totalv .= strip_tags(trim($itemk)).': <i>'.(floatval(sprintf('%1.1f', array_sum($itemv) / count($itemv)))).'</i> ';
        }

        if($pcid) {
            C::t('forum_postcomment')->update($pcid, array('comment' => $totalv, 'dateline' => TIMESTAMP + 1));
        } else {
            C::t('forum_postcomment')->insert(array(
                'tid' => $post['tid'],
                'pid' => $post['pid'],
                'author' => '',
                'authorid' => '-1',
                'dateline' => $zztimestamp + 1,
                'comment' => $totalv
            ));
        }
    }
    C::t('forum_postcache')->delete($post['pid']);
    //showmessage('comment_add_succeed', "forum.php?mod=viewthread&tid=$post[tid]&pid=$post[pid]&page=$_G[gp_page]&extra=$extra#pid$post[pid]", array('tid' => $post['tid'], 'pid' => $post['pid']));
    exit('[err]'.lang('message', 'comment_add_succeed').'[/err]');
}

if($special == 127) {
    $postinfo = C::t('forum_post')->fetch_threadpost_by_tid_invisible($_G['tid']);
    $sppos = strrpos($postinfo['message'], chr(0).chr(0).chr(0));
    $specialextra = substr($postinfo['message'], $sppos + 3);
}
if(getstatus($thread['status'], 3)) {
    $rushinfo = C::t('forum_threadrush')->fetch($_G['tid']);
    if($rushinfo['creditlimit'] != -996) {
        $checkcreditsvalue = $_G['setting']['creditstransextra'][11] ? getuserprofile('extcredits'.$_G['setting']['creditstransextra'][11]) : $_G['member']['credits'];
        if($checkcreditsvalue < $rushinfo['creditlimit']) {
            $creditlimit_title = $_G['setting']['creditstransextra'][11] ? $_G['setting']['extcredits'][$_G['setting']['creditstransextra'][11]]['title'] : lang('forum/misc', 'credit_total');
//            showmessage('post_rushreply_creditlimit', '', array('creditlimit_title' => $creditlimit_title, 'creditlimit' => $rushinfo['creditlimit']));
                exit('[err]'.lang('message', 'post_rushreply_creditlimit',array('creditlimit_title' => $creditlimit_title, 'creditlimit' => $rushinfo['creditlimit'])).'[/err]');
        }
    }

}

/*
if(!submitcheck('replysubmit', 0, $seccodecheck, $secqaacheck)) {

    if($thread['special'] == 2 && ((!isset($_GET['addtrade']) || $thread['authorid'] != $_G['uid']) && !$tradenum = C::t('forum_trade')->fetch_counter_thread_goods($_G['tid']))) {
        showmessage('trade_newreply_nopermission', NULL);
    }

    $language = lang('forum/misc');
    $noticeauthor = $noticetrimstr = '';
    if(isset($_GET['repquote']) && $_GET['repquote'] = intval($_GET['repquote'])) {
        $thaquote = C::t('forum_post')->fetch('tid:'.$_G['tid'], $_GET['repquote']);
        if(!($thaquote && ($thaquote['invisible'] == 0 || $thaquote['authorid'] == $_G['uid'] && $thaquote['invisible'] == -2))) {
            $thaquote = array();
        }
        if($thaquote['tid'] != $_G['tid']) {
            showmessage('reply_quotepost_error', NULL);
        }

        if(getstatus($thread['status'], 2) && $thaquote['authorid'] != $_G['uid'] && $_G['uid'] != $thread['authorid'] && $thaquote['first'] != 1 && !$_G['forum']['ismoderator']) {
            showmessage('reply_quotepost_error', NULL);
        }

        if(!($thread['price'] && !$thread['special'] && $thaquote['first'])) {
            $quotefid = $thaquote['fid'];
            $message = $thaquote['message'];
			if(strpos($message, '[/password]') !== FALSE) {
				$message = '';
			}

            if($_G['setting']['bannedmessages'] && $thaquote['authorid']) {
                $author = getuserbyuid($thaquote['authorid']);
                if(!$author['groupid'] || $author['groupid'] == 4 || $author['groupid'] == 5) {
                    $message = $language['post_banned'];
                } elseif($thaquote['status'] & 1) {
                    $message = $language['post_single_banned'];
                }
            }

            $time = dgmdate($thaquote['dateline']);
            $message = messagecutstr($message, 100);
            $message = implode("\n", array_slice(explode("\n", $message), 0, 3));

            $thaquote['useip'] = substr($thaquote['useip'], 0, strrpos($thaquote['useip'], '.')).'.x';
            if($thaquote['author'] && $thaquote['anonymous']) {
                $thaquote['author'] = lang('forum/misc', 'anonymoususer');
            } elseif(!$thaquote['author']) {
                $thaquote['author'] = lang('forum/misc', 'guestuser').' '.$thaquote['useip'];
            } else {
                $thaquote['author'] = $thaquote['author'];
            }

            $post_reply_quote = lang('forum/misc', 'post_reply_quote', array('author' => $thaquote['author'], 'time' => $time));
            $noticeauthormsg = dhtmlspecialchars($message);
            if(!defined('IN_MOBILE')) {
				$message = "[quote][size=2][url=forum.php?mod=redirect&goto=findpost&pid=$_GET[repquote]&ptid={$_G['tid']}][color=#999999]{$post_reply_quote}[/color][/url][/size]\n{$message}[/quote]";
            } else {
                $message = "[quote][color=#999999]{$post_reply_quote}[/color]\n[color=#999999]{$message}[/color][/quote]";
            }
            $quotemessage = discuzcode($message, 0, 0);
            $noticeauthor = dhtmlspecialchars(authcode('q|'.$thaquote['authorid'], 'ENCODE'));
            $noticetrimstr = dhtmlspecialchars($message);
            $message = '';
        }
        $reppid = $_GET['repquote'];

    } elseif(isset($_GET['reppost']) && $_GET['reppost'] = intval($_GET['reppost'])) {
        $thapost = C::t('forum_post')->fetch('tid:'.$_G['tid'], $_GET['reppost']);
        if(!($thapost && ($thapost['invisible'] == 0 || $thapost['authorid'] == $_G['uid'] && $thapost['invisible'] == -2))) {
            $thapost = array();
        }
        if($thapost['tid'] != $_G['tid']) {
            showmessage('targetpost_donotbelongto_thisthread', NULL);
        }

        $thapost['useip'] = substr($thapost['useip'], 0, strrpos($thapost['useip'], '.')).'.x';
        if($thapost['author'] && $thapost['anonymous']) {
            $thapost['author'] = '[color=Olive]'.lang('forum/misc', 'anonymoususer').'[/color]';
        } elseif(!$thapost['author']) {
            $thapost['author'] = '[color=Olive]'.lang('forum/misc', 'guestuser').'[/color] '.$thapost['useip'];
        } else {
            $thapost['author'] = '[color=Olive]'.$thapost['author'].'[/color]';
        }
        $quotemessage = discuzcode($message, 0, 0);
        $noticeauthormsg = dhtmlspecialchars(messagecutstr($thapost['message'], 100));
        $noticeauthor = dhtmlspecialchars(authcode('r|'.$thapost['authorid'], 'ENCODE'));
        $noticetrimstr = dhtmlspecialchars($message);
        $message = '';
        $reppid = $_GET['reppost'];
    }


    if(isset($_GET['addtrade']) && $thread['special'] == 2 && $_G['group']['allowposttrade'] && $thread['authorid'] == $_G['uid']) {
        $expiration_7days = date('Y-m-d', TIMESTAMP + 86400 * 7);
        $expiration_14days = date('Y-m-d', TIMESTAMP + 86400 * 14);
        $trade['expiration'] = $expiration_month = date('Y-m-d', mktime(0, 0, 0, date('m')+1, date('d'), date('Y')));
        $expiration_3months = date('Y-m-d', mktime(0, 0, 0, date('m')+3, date('d'), date('Y')));
        $expiration_halfyear = date('Y-m-d', mktime(0, 0, 0, date('m')+6, date('d'), date('Y')));
        $expiration_year = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y')+1));
    }

    if($thread['replies'] <= $_G['ppp']) {
        $postlist = array();
        if($thread['price'] > 0 && $thread['special'] == 0) {
            $postlist = C::t('forum_post')->fetch_all_by_tid('tid:'.$_G['tid'], $_G['tid'], true, 'DESC', 0, 0, 0, 0);
        } else {
            $postlist = C::t('forum_post')->fetch_all_by_tid('tid:'.$_G['tid'], $_G['tid'], true, 'DESC', 0, 0, null, 0);
        }
        if($_G['setting']['bannedmessages']) {
            $uids = array();
            foreach($postlist as $post) {
                $uids[] = $post['authorid'];
            }
            $users = C::t('common_member')->fetch_all($uids);
        }
        foreach($postlist as $k => $post) {

            $post['dateline'] = dgmdate($post['dateline'], 'u');

            if($_G['setting']['bannedmessages'] && ($post['authorid'] && (!$post['groupid'] || $post['groupid'] == 4 || $post['groupid'] == 5))) {
                $post['message'] = $language['post_banned'];
            } elseif($post['status'] & 1) {
                $post['message'] = $language['post_single_banned'];
            } else {
                $post['message'] = preg_replace("/\[hide=?\d*\](.*?)\[\/hide\]/is", "[b]$language[post_hidden][/b]", $post['message']);
                $post['message'] = discuzcode($post['message'], $post['smileyoff'], $post['bbcodeoff'], $post['htmlon'] & 1, $_G['forum']['allowsmilies'], $_G['forum']['allowbbcode'], $_G['forum']['allowimgcode'], $_G['forum']['allowhtml'], $_G['forum']['jammer']);
            }

            if($_G['setting']['bannedmessages']) {
                $post['groupid'] = $users[$post['authorid']]['groupid'];
            }

            $postlist[$k] = $post;
        }
    }
    unset($uids, $users);

    if($_G['group']['allowpostattach'] || $_G['group']['allowpostimage']) {
        $attachlist = getattach(0);
        $attachs = $attachlist['attachs'];
        $imgattachs = $attachlist['imgattachs'];
        unset($attachlist);
    }

    getgpc('infloat') ? include template('forum/post_infloat') : include template('forum/post');

} else {
*/

//类开始
class model_zz_forum_post extends discuz_model {
	public $forum;

	public $thread;

	public $post;







	public $pid = 0;

	public $feed = array();

	public function __construct($tid = null, $pid = null) {
		parent::__construct();
		require_once libfile('function/post');
		require_once libfile('function/forumlist');
		if($tid) {
			include_once libfile('function/forum');
			loadforum(null, $tid);
			if($pid) {
				$this->post = get_post_by_tid_pid($tid, $pid);
			}
		}
		$this->forum = &$this->app->var['forum'];
		$this->thread = &$this->app->var['thread'];
		$this->group = &$this->app->var['group'];
	}

	protected function _init_parameters($parameters) {
		$varname = array(
			'member', 'group', 'forum', 'thread', 'extramessage', 'special',//'nauthorid' 'modnewreplies' 'tid'
			'message','clientip', 'invisible', 'isanonymous', 'usesig',
			'htmlon', 'bbcodeoff', 'smileyoff', 'parseurloff', 'pstatus',
			'noticetrimstr', 'noticeauthor', 'from', 'sechash', 'geoloc',

			'subject', 'special', 'sortid', 'typeid', 'isanonymous', 'cronpublish', 'cronpublishdate', 'save',
			'readperm', 'price', 'ordertype', 'hiddenreplies', 'allownoticeauthor', 'audit', 'tags', 'bbcodeoff', 'imgcontent', 'imgcontentwidth',
			'smileyoff', 'parseurloff', 'usesig', 'htmlon', 'extramessage',

		);
		foreach($varname as $name) {
			if(!isset($this->param[$name]) && isset($parameters[$name])) {
				$this->param[$name] = $parameters[$name];
			}
		}

	}

	public function newreply($parameters) {

		$this->_init_parameters($parameters);

		if($this->thread['closed'] && !$this->forum['ismoderator'] && !$this->thread['isgroup']) {
//			return $this->showmessage('post_thread_closed');
			exit('[err]'.lang('message', 'post_thread_closed').'[/err]');

		} elseif(!$this->thread['isgroup'] && $post_autoclose = checkautoclose($this->thread)) {
//			return $this->showmessage($post_autoclose, '', array('autoclose' => $this->forum['autoclose']));
			exit('[err]'.lang('message', 'post_autoclose',array('autoclose' => $this->forum['autoclose'])).'[/err]');
		} if(trim($this->param['subject']) == '' && trim($this->param['message']) == '' && $this->thread['special'] != 2) {
//			return $this->showmessage('post_sm_isnull');
			exit('[err]'.lang('message', 'post_sm_isnull').'[/err]');
		} elseif($post_invalid = checkpost($this->param['subject'], $this->param['message'], $this->param['special'] == 2 && $this->group['allowposttrade'])) {
//			return $this->showmessage($post_invalid, '', array('minpostsize' => $this->setting['minpostsize'], 'maxpostsize' => $this->setting['maxpostsize']));
			exit('[err]'.lang('message', $post_invalid,array('minpostsize' => $this->setting['minpostsize'], 'maxpostsize' => $this->setting['maxpostsize'])).'[/err]');
//		} elseif(checkflood()) {
//			return $this->showmessage('post_flood_ctrl', '', array('floodctrl' => $this->setting['floodctrl']));
//		} elseif(checkmaxperhour('pid')) {
//			return $this->showmessage('post_flood_ctrl_posts_per_hour', '', array('posts_per_hour' => $this->group['maxpostsperhour']));
		}


		$heatthreadset = update_threadpartake($this->thread['tid'], true);


		$bbcodeoff = checkbbcodes($this->param['message'], !empty($this->param['bbcodeoff']));
		$smileyoff = checksmilies($this->param['message'], !empty($this->param['smileyoff']));
		$parseurloff = !empty($this->param['parseurloff']);
		$htmlon = $this->group['allowhtml'] && !empty($this->param['htmlon']) ? 1 : 0;
		$usesig = !empty($this->param['usesig']) && $this->group['maxsigsize'] ? 1 : 0;

		$this->param['isanonymous'] = $this->group['allowanonymous'] && !empty($this->param['isanonymous'])? 1 : 0;
		$author = empty($this->param['isanonymous']) ? $this->member['username'] : '';

		list(, $this->param['modnewreplies']) = threadmodstatus($this->param['subject']."\t".$this->param['message'].$this->param['extramessage']);

		if($this->thread['displayorder'] == -4) {
			$this->param['modnewreplies'] = 0;
		}
		$pinvisible = $this->param['modnewreplies'] ? -2 : ($this->thread['displayorder'] == -4 ? -3 : 0);
		$this->param['message'] = preg_replace('/\[attachimg\](\d+)\[\/attachimg\]/is', '[attach]\1[/attach]', $this->param['message']);


		if(!empty($this->param['noticetrimstr'])) {
			$this->param['message'] = $this->param['noticetrimstr']."\n\n".$this->param['message'];
			$bbcodeoff = false;
		}

		$status = (defined('IN_MOBILE') ? 8 : 0);

		if($this->param['modstatus']) {
			foreach($this->param['modstatus'] as $modbit => $modvalue) {
				$status = setstatus($modbit, $modvalue, $status);
			}
		}

		$this->pid = insertpost(array(
			'fid' => $this->forum['fid'],
			'tid' => $this->thread['tid'],
			'first' => '0',
			'author' => $this->member['username'],
			'authorid' => $this->member['uid'],
			'subject' => $this->param['subject'],
			'dateline' => $this->param['timestamp'] ? $this->param['timestamp'] : getglobal('timestamp'),
			'message' => $this->param['message'],
			'useip' => $this->param['clientip'] ? $this->param['clientip'] : getglobal('clientip'),
			'invisible' => $pinvisible,
			'anonymous' => $this->param['isanonymous'],
			'usesig' => $usesig,
			'htmlon' => $htmlon,
			'bbcodeoff' => $bbcodeoff,
			'smileyoff' => $smileyoff,
			'parseurloff' => $parseurloff,
			'attachment' => '0',
			'status' => $status,
		));


		$heatthreadset ? $heatthreadset : array();
		$this->param['maxposition'] = C::t('forum_post')->fetch_maxposition_by_tid($this->thread['posttableid'], $this->thread['tid']);
		$this->param['updatethreaddata'][] = DB::field('maxposition', $this->param['maxposition']);


		useractionlog($this->member['uid'], 'pid');

		if($this->param['geoloc'] && IN_MOBILE == 2) {
			list($mapx, $mapy, $location) = explode('|', $this->param['geoloc']);
			if($mapx && $mapy && $location) {
				C::t('forum_post_location')->insert(array(
					'pid' => $this->pid,
					'tid' => $this->thread['tid'],
					'uid' => $this->member['uid'],
					'mapx' => $mapx,
					'mapy' => $mapy,
					'location' => $location,
				));
			}
		}

		$nauthorid = 0;
		if(!empty($this->param['noticeauthor']) && !$this->param['isanonymous'] && !$this->param['modnewreplies']) {
			list($ac, $nauthorid) = explode('|', authcode($this->param['noticeauthor'], 'DECODE'));
			if($nauthorid != $this->member['uid']) {
				if($ac == 'q') {
					notification_add($nauthorid, 'post', 'reppost_noticeauthor', array(
						'tid' => $this->thread['tid'],
						'subject' => $this->thread['subject'],
						'fid' => $this->forum['fid'],
						'pid' => $this->pid,
						'from_id' => $this->pid,
						'from_idtype' => 'quote',
					));
				} elseif($ac == 'r') {
					notification_add($nauthorid, 'post', 'reppost_noticeauthor', array(
						'tid' => $this->thread['tid'],
						'subject' => $this->thread['subject'],
						'fid' => $this->forum['fid'],
						'pid' => $this->pid,
						'from_id' => $this->thread['tid'],
						'from_idtype' => 'post',
					));
				}
			}

		}

		if($this->thread['authorid'] != $this->member['uid'] && getstatus($this->thread['status'], 6) && empty($this->param['noticeauthor']) && !$this->param['isanonymous'] && !$this->param['modnewreplies']) {
			$thapost = C::t('forum_post')->fetch_threadpost_by_tid_invisible($this->thread['tid'], 0);
			notification_add($thapost['authorid'], 'post', 'reppost_noticeauthor', array(
				'tid' => $this->thread['tid'],
				'subject' => $this->thread['subject'],
				'fid' => $this->forum['fid'],
				'pid' => $this->pid,
				'from_id' => $this->thread['tid'],
				'from_idtype' => 'post',
			));
		}


		$this->forum['threadcaches'] && deletethreadcaches($this->thread['tid']);

		include_once libfile('function/stat');
		updatestat($this->thread['isgroup'] ? 'grouppost' : 'post');

		$this->param['showmsgparam']['fid'] = $this->forum['fid'];
		$this->param['showmsgparam']['tid'] = $this->thread['tid'];
		$this->param['showmsgparam']['pid'] = $this->pid;
		$this->param['showmsgparam']['from'] = $this->param['from'];
		$this->param['showmsgparam']['sechash'] = !empty($this->param['sechash']) ? $this->param['sechash'] : '';


		dsetcookie('clearUserdata', 'forum');

		if($this->thread['replies'] <= 0) {
			C::t('forum_sofa')->delete($this->thread['tid']);
		}

		if($this->param['modnewreplies']) {
			updatemoderate('pid', $this->pid);
			unset($this->param['showmsgparam']['pid']);
			if($this->param['updatethreaddata']) {
				C::t('forum_thread')->update($this->thread['tid'], $this->param['updatethreaddata'], false, false, 0, true);
			}
			C::t('forum_forum')->update_forum_counter($this->forum['fid'], 0, 0, 1, 1);


			manage_addnotify('verifypost');


			return 'post_reply_mod_succeed';

		} else {

			$fieldarr = array(
				'lastposter' => array($author),
				'replies' => 1
			);
			if($this->thread['lastpost'] < getglobal('timestamp')) {
				$fieldarr['lastpost'] = array(getglobal('timestamp'));
			}
			$row = C::t('forum_threadaddviews')->fetch($this->thread['tid']);
			if(!empty($row)) {
				C::t('forum_threadaddviews')->update($this->thread['tid'], array('addviews' => 0));
				$fieldarr['views'] = $row['addviews'];
			}
			$this->param['updatethreaddata'] = array_merge($this->param['updatethreaddata'], C::t('forum_thread')->increase($this->thread['tid'], $fieldarr, false, 0, true));
			if($this->thread['displayorder'] != -4) {
				updatepostcredits('+', $this->member['uid'], 'reply', $this->forum['fid']);
				if($this->forum['status'] == 3) {
					if($this->forum['closed'] > 1) {
						C::t('forum_thread')->increase($this->forum['closed'], $fieldarr, true);
					}
					C::t('forum_groupuser')->update_counter_for_user($this->member['uid'], $this->forum['fid'], 0, 1);
					C::t('forum_forumfield')->update($this->forum['fid'], array('lastupdate' => TIMESTAMP));
					require_once libfile('function/grouplog');
					updategroupcreditlog($this->forum['fid'], $this->member['uid']);
				}

				$lastpost = $this->thread['tid']."\t".$this->thread['subject']."\t".getglobal('timestamp')."\t".$author;
				C::t('forum_forum')->update($this->forum['fid'], array('lastpost' => $lastpost));
				C::t('forum_forum')->update_forum_counter($this->forum['fid'], 0, 1, 1);
				if($this->forum['type'] == 'sub') {
					C::t('forum_forum')->update($this->forum['fup'], array('lastpost' => $lastpost));
				}
			}


			$this->param['page'] = getstatus($this->thread['status'], 4) ? 1 : @ceil(($this->thread['special'] ? $this->thread['replies'] + 1 : $this->thread['replies'] + 2) / getglobal('ppp'));

			if($this->param['updatethreaddata']) {
				C::t('forum_thread')->update($this->thread['tid'], $this->param['updatethreaddata'], false, false, 0, true);
			}




			return 'post_reply_succeed';
		}
	}

	public function replyfeed() {
		if(!$this->feed) {
			if($this->forum['allowfeed'] && !$this->param['isanonymous']) {
				if($this->thread['authorid'] != $this->member['uid']) {
					$post_url = "forum.php?mod=redirect&goto=findpost&pid=".$this->pid."&ptid=".$this->thread['tid'];

					$this->feed['icon'] = 'post';
					$this->feed['title_template'] = !empty($this->thread['author']) ? 'feed_reply_title' : 'feed_reply_title_anonymous';
					$this->feed['title_data'] = array(
						'subject' => "<a href=\"$post_url\">".$this->thread['subject']."</a>",
						'author' => "<a href=\"home.php?mod=space&uid=".$this->thread['authorid']."\">".$this->thread['author']."</a>"
					);
					$forum_attachexist = getglobal('forum_attachexist');
					if(!empty($forum_attachexist)) {
						$imgattach = C::t('forum_attachment_n')->fetch_max_image('tid:'.$this->thread['tid'], 'pid', $this->pid);
						$firstaid = $imgattach['aid'];
						unset($imgattach);
						if($firstaid) {
							$this->feed['images'] = array(getforumimg($firstaid));
							$this->feed['image_links'] = array($post_url);
						}
					}
				}
			}
		}

		$this->feed['title_data']['hash_data'] = "tid".$this->thread['tid'];
		$this->feed['id'] = $this->pid;
		$this->feed['idtype'] = 'pid';
		if($this->feed['icon']) {
			postfeed($this->feed);
		}
	}

	public function thread($name = null, $val = null) {
		if(isset($val)) {
			return $this->setvar($this->thread, $name, $val);
		} else {
			return $this->getvar($this->thread, $name);
		}
	}

	public function forum($name = null, $val = null) {
		if(isset($val)) {
			return $this->setvar($this->forum, $name, $val);
		} else {
			return $this->getvar($this->forum, $name);
		}
	}

	public function editpost($parameters) {

		$this->_init_parameters($parameters);
		$isfirstpost = $this->post['first'] ? 1 : 0;
		$isorigauthor = $this->member['uid'] && $this->member['uid'] == $this->post['authorid'];
		$this->param['audit'] = $this->post['invisible'] == -2 || $this->thread['displayorder'] == -2 ? $this->param['audit'] : 0;

		list($this->param['modnewthreads'], $this->param['modnewreplies']) = threadmodstatus($this->param['subject']."\t".$this->param['message'].$this->param['extramessage']);

		if($post_invalid = checkpost($this->param['subject'], $this->param['message'], $isfirstpost && ($this->param['special'] || $this->param['sortid']))) {
			showmessage($post_invalid, '', array('minpostsize' => $this->setting['minpostsize'], 'maxpostsize' => $this->setting['maxpostsize']));
		}
		if(!$isorigauthor && !$this->group['allowanonymous']) {
			if($this->post['anonymous'] && !$this->param['isanonymous']) {
				$this->param['isanonymous'] = 0;
				$this->param['threadupdatearr']['author'] = $this->post['author'];
				$anonymousadd = 0;
			} else {
				$this->param['isanonymous'] = $this->post['anonymous'];
				$anonymousadd = '';
			}
		} else {
			$this->param['threadupdatearr']['author'] = $this->param['isanonymous'] ? '' : $this->post['author'];
			$anonymousadd = $this->param['isanonymous'];
		}

		if($isfirstpost) {
			if(trim($this->param['subject']) == '' && $this->thread['special'] != 2) {
				showmessage('post_sm_isnull');
			}

			if(!$this->param['sortid'] && !$this->thread['special'] && trim($this->param['message']) == '') {
				showmessage('post_sm_isnull');
			}


			$publishdate = null;
			if ($this->group['allowsetpublishdate'] && $this->thread['displayorder'] == -4) {
				$cron_publish_ids = dunserialize($this->cache('cronpublish'));
				if (!$this->param['cronpublish'] && in_array($this->thread['tid'], $cron_publish_ids)) {
					unset($cron_publish_ids[$this->thread['tid']]);
					$cron_publish_ids = serialize($cron_publish_ids);
					savecache('cronpublish', $cron_publish_ids);
				} elseif ($this->param['cronpublish'] && $this->param['cronpublishdate']) {
					$this->param['threadupdatearr']['dateline'] = $publishdate = strtotime($this->param['cronpublishdate']);
					$this->param['save'] = 1;
					if (!in_array($this->thread['tid'], $cron_publish_ids)) {
						$cron_publish_ids[$this->thread['tid']] = $this->thread['tid'];
						$cron_publish_ids = serialize($cron_publish_ids);
						savecache('cronpublish', $cron_publish_ids);
					}
				}
			}



			$this->param['readperm'] = $this->group['allowsetreadperm'] ? intval($this->param['readperm']) : ($isorigauthor ? 0 : 'ignore');
			if($this->thread['special'] != 3) {
				$this->param['price'] = intval($this->param['price']);
				$this->param['price'] = $this->thread['price'] < 0 && !$this->thread['special']
					?($isorigauthor || !$this->param['price'] ? -1 : $this->param['price'])
					:($this->group['maxprice'] ? ($this->param['price'] <= $this->group['maxprice'] ? ($this->param['price'] > 0 ? $this->param['price'] : 0) : $this->group['maxprice']) : ($isorigauthor ? $this->param['price'] : $this->thread['price']));

				if($this->param['price'] > 0 && floor($this->param['price'] * (1 - $this->setting['creditstax'])) == 0) {
					return $this->showmessage('post_net_price_iszero');
				}
			}

			$this->thread['status'] = setstatus(4, $this->param['ordertype'], $this->thread['status']);
			$this->thread['status'] = setstatus(15, $this->param['imgcontent'], $this->thread['status']);
			if($this->param['imgcontent']) {
				stringtopic($this->param['message'], $this->post['tid'], true, $this->param['imgcontentwidth']);
			}

			$this->thread['status'] = setstatus(2, $this->param['hiddenreplies'], $this->thread['status']);

			$this->thread['status'] = setstatus(6, $this->param['allownoticeauthor'] ? 1 : 0, $this->thread['status']);

			$displayorder = empty($this->param['save']) ? ($this->thread['displayorder'] == -4 ? -4 : $this->thread['displayorder']) : -4;


			$this->param['threadupdatearr']['typeid'] = $this->param['typeid'];
			$this->param['threadupdatearr']['sortid'] = $this->param['sortid'];
			$this->param['threadupdatearr']['subject'] = $this->param['subject'];
			if($this->param['readperm'] !== 'ignore') {
				$this->param['threadupdatearr']['readperm'] = $this->param['readperm'];
			}
			$this->param['threadupdatearr']['price'] = $this->param['price'];
			$this->param['threadupdatearr']['status'] = $this->thread['status'];
			if(getglobal('forum_auditstatuson') && $this->param['audit'] == 1) {
				$this->param['threadupdatearr']['displayorder'] = 0;
				$this->param['threadupdatearr']['moderated'] = 1;
			} else {
				$this->param['threadupdatearr']['displayorder'] = $displayorder;
			}
			C::t('forum_thread')->update($this->thread['tid'], $this->param['threadupdatearr'], true);

			if($this->thread['tid'] > 1) {
				if($this->thread['closed'] > 1) {
					C::t('forum_thread')->update($this->thread['closed'], array('subject' => $this->param['subject']), true);
				} elseif(empty($this->thread['isgroup'])) {
					$threadclosed = C::t('forum_threadclosed')->fetch($thread['tid']);
					if($threadclosed['redirect']) {
						C::t('forum_thread')->update($threadclosed['redirect'], array('subject' => $this->param['subject']), true);
					}
				}
			}
			$class_tag = new tag();
			$tagstr = $class_tag->update_field($this->param['tags'], $this->thread['tid'], 'tid', $this->thread);

		} else {
			if($this->param['subject'] == '' && $this->param['message'] == '' && $this->thread['special'] != 2) {
				showmessage('post_sm_isnull');
			}
		}


		$this->param['htmlon'] = $this->group['allowhtml'] && !empty($this->param['htmlon']) ? 1 : 0;

		if($this->setting['editedby'] && (TIMESTAMP - $this->post['dateline']) > 60 && $this->member['adminid'] != 1) {
			$editor = $this->param['isanonymous'] && $isorigauthor ? lang('forum/misc', 'anonymous') : $this->member['username'];
			$edittime = dgmdate(TIMESTAMP);
			$this->param['message'] = lang('forum/misc', $this->param['htmlon'] ? 'post_edithtml' : (!$this->forum['allowbbcode'] || $this->param['bbcodeoff'] ? 'post_editnobbcode' : 'post_edit'), array('editor' => $editor, 'edittime' => $edittime)) . $this->param['message'];
		}


		$this->param['bbcodeoff'] = checkbbcodes($this->param['message'], !empty($this->param['bbcodeoff']));
		$this->param['smileyoff'] = checksmilies($this->param['message'], !empty($this->param['smileyoff']));
		$tagoff = $isfirstpost ? !empty($tagoff) : 0;


		if(getglobal('forum_auditstatuson') && $this->param['audit'] == 1) {
			C::t('forum_post')->update($this->thread['posttableid'], $this->post['pid'], array('status' => 4), false, false, null, -2, null, 0);
			updatepostcredits('+', $this->post['authorid'], ($isfirstpost ? 'post' : 'reply'), $this->forum['fid']);
			updatemodworks('MOD', 1);
			updatemodlog($this->thread['tid'], 'MOD');
		}

		$displayorder = $pinvisible = 0;
		if($isfirstpost) {
			$displayorder = $this->param['modnewthreads'] ? -2 : $this->thread['displayorder'];
			$pinvisible = $this->param['modnewthreads'] ? -2 : (empty($this->param['save']) ? 0 : -3);
		} else {
			$pinvisible = $this->param['modnewreplies'] ? -2 : ($this->thread['displayorder'] == -4 ? -3 : 0);
		}

		$this->param['message'] = preg_replace('/\[attachimg\](\d+)\[\/attachimg\]/is', '[attach]\1[/attach]', $this->param['message']);
		$this->param['parseurloff'] = !empty($this->param['parseurloff']);
		$setarr = array(
			'message' => $this->param['message'],
			'usesig' => $this->param['usesig'],
			'htmlon' => $this->param['htmlon'],
			'bbcodeoff' => $this->param['bbcodeoff'],
			'parseurloff' => $this->param['parseurloff'],
			'smileyoff' => $this->param['smileyoff'],
			'subject' => $this->param['subject'],
			'tags' => $tagstr
		);

		$setarr['status'] = $this->post['status'];
		if($this->param['modstatus']) {
			foreach($this->param['modstatus'] as $modbit => $modvalue) {
				$setarr['status'] = setstatus($modbit, $modvalue, $setarr['status']);
			}
		}

		if($anonymousadd !== '') {
			$setarr['anonymous'] = $anonymousadd;
		}
		if($publishdate) {
			$setarr['dateline'] = $publishdate;
		}
		if(getglobal('forum_auditstatuson') && $this->param['audit'] == 1) {
			$setarr['invisible'] = 0;
		} else {
			$setarr['invisible'] = $pinvisible;
		}
		C::t('forum_post')->update('tid:'.$this->thread['tid'], $this->post['pid'], $setarr);


		$this->forum['lastpost'] = explode("\t", $this->forum['lastpost']);

		if($this->post['dateline'] == $this->forum['lastpost'][2] && ($this->post['author'] == $this->forum['lastpost'][3] || ($this->forum['lastpost'][3] == '' && $this->post['anonymous']))) {
			$lastpost = $this->thread['tid']."\t".($isfirstpost ? $this->param['subject'] : $this->thread['subject'])."\t".$this->post['dateline']."\t".($this->param['isanonymous'] ? '' : $this->post['author']);
			C::t('forum_forum')->update($this->forum['fid'], array('lastpost' => $lastpost));

		}

		if(!getglobal('forum_auditstatuson') || $this->param['audit'] != 1) {
			if($isfirstpost && $this->param['modnewthreads']) {
				C::t('forum_thread')->update($this->thread['tid'], array('displayorder' => -2));
				manage_addnotify('verifythread');
			} elseif(!$isfirstpost && $this->param['modnewreplies']) {
				C::t('forum_thread')->increase($this->thread['tid'], array('replies' => -1));
				manage_addnotify('verifypost');
			}
			if($this->param['modnewreplies'] || $this->param['modnewthreads']) {
				C::t('forum_forum')->update($this->forum['fid'], array('modworks' => '1'));
			}
		}


		if($this->thread['lastpost'] == $this->post['dateline'] && ((!$this->post['anonymous'] && $this->thread['lastposter'] == $this->post['author']) || ($this->post['anonymous'] && $this->thread['lastposter'] == '')) && $this->post['anonymous'] != $this->param['isanonymous']) {
			C::t('forum_thread')->update($this->thread['tid'], array('lastposter' => $this->param['isanonymous'] ? '' : $this->post['author']), true);
		}

		if(!$isorigauthor) {
			updatemodworks('EDT', 1);
			require_once libfile('function/misc');
			modlog($this->thread, 'EDT');
		}

		if($isfirstpost && $this->thread['displayorder'] == -4 && empty($this->param['save'])) {
			threadpubsave($this->thread['tid']);
		}
	}

	public function deletepost($parameters) {

		$this->_init_parameters($parameters);
		if(!$this->setting['editperdel']) {
			return $this->showmessage('post_edit_thread_ban_del', NULL);
		}

		$isfirstpost = $this->post['first'] ? 1 : 0;

		if($isfirstpost && $this->thread['replies'] > 0) {
			return $this->showmessage(($this->thread['special'] == 3 ? 'post_edit_reward_already_reply' : 'post_edit_thread_already_reply'), NULL);
		}


		if($this->thread['displayorder'] >= 0) {
			updatepostcredits('-', $this->post['authorid'], ($isfirstpost ? 'post' : 'reply'), $this->forum['fid']);
		}


		if(!$this->param['handlereplycredit']) {
			if(!$isfirstpost && !$this->param['isanonymous']) {
				$postreplycredit = C::t('forum_post')->fetch('tid:'.$this->thread['tid'], $this->post['pid']);
				$postreplycredit = $postreplycredit['replycredit'];
				if($postreplycredit) {
					C::t('forum_post')->update('tid:'.$this->thread['tid'], $this->post['pid'], array('replycredit' => 0));
					updatemembercount($this->post['authorid'], array($replycredit_rule['extcreditstype'] => '-'.$postreplycredit));
				}
			}
		}


		C::t('forum_post')->delete('tid:'.$this->thread['tid'], $this->post['pid']);


		$forumcounter = array();
		if($isfirstpost) {
			$forumcounter['threads'] = $forumcounter['posts'] = -1;
			$tablearray = array('forum_relatedthread', 'forum_debate', 'forum_debatepost', 'forum_polloption', 'forum_poll');
			foreach ($tablearray as $table) {
				DB::query("DELETE FROM ".DB::table($table)." WHERE tid='".$this->thread['tid']."'", 'UNBUFFERED');
			}
			C::t('forum_thread')->delete_by_tid($this->thread['tid']);
			C::t('common_moderate')->delete($this->thread['tid'], 'tid');
			C::t('forum_threadmod')->delete_by_tid($this->thread['tid']);
			if($this->setting['globalstick'] && in_array($this->thread['displayorder'], array(2, 3))) {
				require_once libfile('function/cache');
				updatecache('globalstick');
			}
		} else {
			$forumcounter['posts'] = -1;
			$lastpost = C::t('forum_post')->fetch_visiblepost_by_tid('tid:'.$this->thread['tid'], $this->thread['tid'], 0, 1);
			$lastpost['author'] = !$lastpost['anonymous'] ? addslashes($lastpost['author']) : '';

			$this->param['updatefieldarr']['replies'] = -1;
			$this->param['updatefieldarr']['lastposter'] = array($lastpost['author']);
			$this->param['updatefieldarr']['lastpost'] = array($lastpost['dateline']);

			C::t('forum_thread')->increase($this->thread['tid'], $this->param['updatefieldarr']);
		}

		$this->forum['lastpost'] = explode("\t", $this->forum['lastpost']);
		if($this->post['dateline'] == $this->forum['lastpost'][2] && ($this->post['author'] == $this->forum['lastpost'][3] || ($this->forum['lastpost'][3] == '' && $this->post['anonymous']))) {
			$lastthread = C::t('forum_thread')->fetch_by_fid_displayorder($this->forum['fid']);
			C::t('forum_forum')->update($this->forum['fid'], array('lastpost' => "$lastthread[tid]\t$lastthread[subject]\t$lastthread[lastpost]\t$lastthread[lastposter]"));
		}
		C::t('forum_forum')->update_forum_counter($this->forum['fid'], $forumcounter['threads'], $forumcounter['posts']);

	}

}
//类结束

	$modpost = C::m('zz_forum_post', $_G['tid']);
	$bfmethods = $afmethods = array();

//zzcity add
   //
   function zzfileext($filename) {
    return strtolower(substr(strrchr($filename, '.'), 1, 10));
   }

 $attachlist=explode(',',$_POST['etattachs']);

 $curattachs='';
 $message=preg_replace("/\[img([^\]]*?)\]/i",'[img]',$message);
 foreach ($attachlist as $key => $value) {
 $value=trim($value);
 if(empty($value))continue;
    if (preg_match("/".preg_quote($value,"/")."/i",$message)){
     $message=preg_replace("/<a([^>]*?)".preg_quote($value,"/")."([^<]*?)<img([^>]*?)".preg_quote($value,"/")."([^<]*?)<\/(.*?)>/i",'[attachimg]'.$value.'[/attachimg]',$message);
     $message=preg_replace("/<img([^>]*?)".preg_quote($value,"/")."([^>]*?)>/i",'[attachimg]'.$value.'[/attachimg]',$message);
     $message=preg_replace("/\[img([^\]]*?)\]".preg_quote($value,"/")."\[\/img\]/i",'[attachimg]'.$value.'[/attachimg]',$message);

     $message=preg_replace("/<a([^>]*?)".preg_quote($value,"/")."([^>]*?)>([^<]+?)<\/a(.*?)>/i",'[attach]'.$value.'[/attach]',$message);
     $message=preg_replace("/\[url=".preg_quote($value,"/")."(.*?)\[\/url\]/i",'[attach]'.$value.'[/attach]',$message);
		 if (in_array(zzfileext($value),array("wma","mp3","ra","rm"))) {

			$message=preg_replace("/<embed([^>]*?)".preg_quote($value,"/")."([^<]*?)<\/embed>/i",'[audio=1]'.$value.'[/audio]',$message);
			$message=preg_replace("/<embed([^>]*?)".preg_quote($value,"/")."([^>]*?)>/i",'[audio=1]'.$value.'[/audio]',$message);
		 }elseif  (in_array(zzfileext($value), array('wmv','rmvb','avi','mov'))){
			$message=preg_replace("/<embed([^>]*?)".preg_quote($value,"/")."([^<]*?)<\/embed>/i",'[media='.zzfileext($value).',500,375,1]'.$value.'[/media]',$message);
			$message=preg_replace("/<embed([^>]*?)".preg_quote($value,"/")."([^>]*?)>/i",'[media='.zzfileext($value).',500,375,1]'.$value.'[/media]',$message);
		 }elseif  (in_array(zzfileext($value), array('swf','flv'))){
			$message=preg_replace("/<embed([^>]*?)".preg_quote($value,"/")."([^<]*?)<\/embed>/i",'[flash]'.$value.'[/flash]',$message);
			$message=preg_replace("/<embed([^>]*?)".preg_quote($value,"/")."([^>]*?)>/i",'[flash]'.$value.'[/flash]',$message);
		 }
   $curattachs.= empty($curattachs) ? $value:','.$value;
   
  }
 }

	$message = preg_replace('/\[attachimg\](.+?)\[\/attachimg\]/is', '[attach]\1[/attach]', $message);
//zzcity close
 
 	$subject='';
	$params = array(
		'subject' => $subject,
		'message' => $message,
		'special' => $special,
		'timestamp' => $_G['timestamp'], //zzcity
		'extramessage' => $extramessage,
		'bbcodeoff' => $_GET['bbcodeoff'],
		'smileyoff' => $_GET['smileyoff'],
		'htmlon' => $_GET['htmlon'],
		'parseurloff' => $_GET['parseurloff'],
		'usesig' => $_GET['usesig'],
		'isanonymous' => $_GET['isanonymous'],
		'noticetrimstr' => $_GET['noticetrimstr'],
		'noticeauthor' => $_GET['noticeauthor'],
		'from' => $_GET['from'],
		'sechash' => $_GET['sechash'],
		'geoloc' => diconv($_GET['geoloc'], 'UTF-8'),
	);


	if(!empty($_GET['trade']) && $thread['special'] == 2 && $_G['group']['allowposttrade']) {
		$bfmethods[] = array('class' => 'extend_thread_trade', 'method' => 'before_newreply');
	}


	$attentionon = empty($_GET['attention_add']) ? 0 : 1;
	$attentionoff = empty($attention_remove) ? 0 : 1;
	$bfmethods[] = array('class' => 'extend_thread_rushreply', 'method' => 'before_newreply');
	if($_G['group']['allowat']) {
		$bfmethods[] = array('class' => 'extend_thread_allowat', 'method' => 'before_newreply');
	}

	$bfmethods[] = array('class' => 'extend_thread_comment', 'method' => 'before_newreply');
	$modpost->attach_before_method('newreply', array('class' => 'extend_thread_filter', 'method' => 'before_newreply'));



	if($_G['group']['allowat']) {
		$afmethods[] = array('class' => 'extend_thread_allowat', 'method' => 'after_newreply');
	}


	$afmethods[] = array('class' => 'extend_thread_rushreply', 'method' => 'after_newreply');



		$afmethods[] = array('class' => 'extend_thread_comment', 'method' => 'after_newreply');



	if(helper_access::check_module('follow') && !empty($_GET['adddynamic'])) {
		$afmethods[] = array('class' => 'extend_thread_follow', 'method' => 'after_newreply');
	}


	if($thread['replycredit'] > 0 && $thread['authorid'] != $_G['uid'] && $_G['uid']) {
		$afmethods[] = array('class' => 'extend_thread_replycredit', 'method' => 'after_newreply');
	}


	if($special == 5) {
		$afmethods[] = array('class' => 'extend_thread_debate', 'method' => 'after_newreply');
	}



	$afmethods[] = array('class' => 'extend_thread_image', 'method' => 'after_newreply');



	if($special == 2 && $_G['group']['allowposttrade'] && $thread['authorid'] == $_G['uid']) {
		$afmethods[] = array('class' => 'extend_thread_trade', 'method' => 'after_newreply');
	}
	$afmethods[] = array('class' => 'extend_thread_filter', 'method' => 'after_newreply');





		if($_G['forum']['allowfeed']) {
			if($special == 2 && !empty($_GET['trade'])) {
				$modpost->attach_before_method('replyfeed', array('class' => 'extend_thread_trade', 'method' => 'before_replyfeed'));
				$modpost->attach_after_method('replyfeed', array('class' => 'extend_thread_trade', 'method' => 'after_replyfeed'));
			} elseif($special == 3 && $thread['authorid'] != $_G['uid']) {
				$modpost->attach_before_method('replyfeed', array('class' => 'extend_thread_reward', 'method' => 'before_replyfeed'));
			} elseif($special == 5 && $thread['authorid'] != $_G['uid']) {
				$modpost->attach_before_method('replyfeed', array('class' => 'extend_thread_debate', 'method' => 'before_replyfeed'));
			}
		}




	if(!isset($_GET['addfeed'])) {
		$space = array();
		space_merge($space, 'field_home');
		$_GET['addfeed'] = $space['privacy']['feed']['newreply'];
	}

	$modpost->attach_before_methods('newreply', $bfmethods);
	$modpost->attach_after_methods('newreply', $afmethods);

	$return = $modpost->newreply($params);	
	$pid = $modpost->pid;

//zzcity add attachment
 $ashowurl =  empty($_POST['ashowurl']) ? "/data/attachment/forum" : trim($_POST['ashowurl']);
 
 $ashowurl = substr($ashowurl,-1)=="/" ? $ashowurl: $ashowurl.'/';
 

 $curalist=explode(',',$curattachs);
 $attachnum =  empty($curattachs) ? 0 :count($curalist);
 $zzattachtype=0;
 if ($attachnum){

   $zzattachtype=1;
   //
   function zzis_image_ext($ext) {
    static $imgext  = array('jpg', 'jpeg', 'gif', 'png', 'bmp');
    return in_array($ext, $imgext) ? 1 : 0;
   }
   //
   function zzget_target_extension($ext) {
    static $safeext  = array('attach', 'jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp', 'txt', 'zip', 'rar', 'mp3');
    return strtolower(!in_array(strtolower($ext), $safeext) ? 'attach' : $ext);
   }
   function zzforum_upload($filename) {
    global $_G,$zzattachtype;
 
    $zzuid = intval($_G['uid']);
//    $swfhash = md5(substr(md5($_G['config']['security']['authkey']), 8).$this->uid);
  
     $zzaid = 0;
//     $zzsimple = !empty($_G['gp_simple']) ? $_G['gp_simple'] : 0;
  
//     $_G['groupid'] = intval(DB::result_first("SELECT groupid FROM ".DB::table('common_member')." WHERE uid='".$this->uid."'"));
//     loadcache('usergroup_'.$_G['groupid']);
//     $_G['group'] = $_G['cache']['usergroup_'.$_G['groupid']];
  
 
//     $upload = new discuz_upload();
//     $upload->init($_FILES['Filedata'], 'forum');
//     $this->attach = &$upload->attach;

     $thistype='forum';
     $attach=array();
  
  	 if (strpos($filename,'/')){
     	$attach['name'] =  trim(substr(strrchr($filename,'/'),1));
		 }else{
     	$attach['name'] =  trim($filename);
		 }
     $attach['thumb'] = '';
     
     $attach['name'] =  dhtmlspecialchars($attach['name'], ENT_QUOTES);
     if(strlen($attach['name']) > 90) {
      $attach['name'] = cutstr($attach['name'], 90, '').'.'.$attach['ext'];
     }
     $attach['ext'] = zzfileext($attach['name']);
     $attach['isimage'] = zzis_image_ext($attach['ext']);
    
     $attach['extension'] = zzget_target_extension($attach['ext']);
     
//     $attach['attachdir'] = $this->get_target_dir($thistype, $extid);
//     $attach['attachment'] = $attach['attachdir'].$this->get_target_filename($this->type, $this->extid, $this->forcename).'.'.$attach['extension'];
     $attach['attachment'] = $filename;
     $attach['target'] = getglobal('setting/attachdir').'./'.$thistype.'/'.$attach['attachment'];
     $attach['size'] = intval(filesize($attach['target']));

  
//     if($upload->error()) {
//      $this->uploadmsg(2);
//     }
//  
//     $allowupload = !$_G['group']['maxattachnum'] || $_G['group']['maxattachnum'] && $_G['group']['maxattachnum'] > DB::result_first("SELECT count(*) FROM ".DB::table('forum_attachment')." WHERE uid='$_G[uid]' AND dateline>'$_G[timestamp]'-86400");
//     if(!$allowupload) {
//      $this->uploadmsg(9);
//     }
  
//     if($_G['group']['attachextensions'] && (!preg_match("/(^|\s|,)".preg_quote($upload->attach['ext'], '/')."($|\s|,)/i", $_G['group']['attachextensions']) || !$upload->attach['ext'])) {
//      $this->uploadmsg(1);
//     }
  
//     if(empty($upload->attach['size'])) {
//      $this->uploadmsg(2);
//     }
  
//     if($_G['group']['maxattachsize'] && $upload->attach['size'] > $_G['group']['maxattachsize']) {
//      $this->uploadmsg(3);
//     }
//  
//     if($type = DB::fetch_first("SELECT maxsize FROM ".DB::table('forum_attachtype')." WHERE extension='".addslashes($upload->attach['ext'])."'")) {
//      if($type['maxsize'] == 0) {
//       $this->uploadmsg(4);
//      } elseif($upload->attach['size'] > $type['maxsize']) {
//       $this->uploadmsg(5);
//      }
//     }
  
//     if($upload->attach['size'] && $_G['group']['maxsizeperday']) {
//      $todaysize = intval(DB::result_first("SELECT SUM(filesize) FROM ".DB::table('forum_attachment')." WHERE uid='$_G[uid]' AND dateline>'$_G[timestamp]'-86400"));
//      $todaysize += $upload->attach['size'];
//      if($todaysize >= $_G['group']['maxsizeperday']) {
//       $this->uploadmsg(6);
//      }
//     }
//     $upload->save();
//     if($upload->error() == -103) {
//      $this->uploadmsg(8);
//     } elseif($upload->error()) {
//      $this->uploadmsg(9);
//     }
  $thumb = $remote = $width = 0;
  if($attach['isimage']) {
   $zzattachtype=2;
        require_once libfile('class/image');
        $image = new image;    
        
        
        if($_G['setting']['thumbstatus']) {
        //$thumb = $image->Thumb($upload->attach['target'], '', $_G['setting']['thumbwidth'], $_G['setting']['thumbheight'], $_G['setting']['thumbstatus'], $_G['setting']['thumbsource']) ? 1 : 0;
        $thumb = $image->Thumb($attach['target'], '', $_G['setting']['thumbwidth'], $_G['setting']['thumbheight'], $_G['setting']['thumbstatus'], $_G['setting']['thumbsource']) ? 1 : 0;
        
        }
        
        if($_G['setting']['watermarkstatus'] && empty($_G['forum']['disablewatermark'])) {
            $image->Watermark($attach['target']);
        }    
         
        $width = $image->imginfo['width'];
   if($_G['setting']['thumbsource'] || !$_G['setting']['thumbstatus']) {
    list($width) = @getimagesize($attach['target']);
   }
   
  }
  
//     if(!$zzsimple) {
//      $attach['name'] = diconv($attach['name'], 'utf-8');
//     }
//     if($_G['gp_type'] != 'image' && $attach['isimage']) {
//      $attach['isimage'] = -1;
//     }
  $zzaid=getattachnewaid($zzuid);
  DB::query("INSERT INTO ".DB::table('forum_attachment_unused')." (aid, dateline, filename, filesize, attachment, isimage, uid, thumb, remote, width)
   VALUES ('$zzaid', '$_G[timestamp]', '".$attach['name']."', '".$attach['size']."', '".$attach['attachment']."', '".$attach['isimage']."', '".$zzuid."', '$thumb', '$remote', '$width')");
 
     return $zzaid;
//     $this->uploadmsg(0);
  
   }
  
 foreach ($curalist as $key => $value) {
  $oldvalue=$value;
  $value=str_replace($ashowurl,'',$value);
  
  $aid=zzforum_upload($value);
  $message=str_replace(']'.$oldvalue.'[',']'.$aid.'[',$message);
	$message=str_replace("attach://".$oldvalue,'attach://'.$aid.'.'.zzfileext($oldvalue),$message);
  $aids[]=$aid;

  }
 
	C::t('forum_post')->update('tid:'.$_G['tid'], $pid, array('message' => $message,'attachment' => $zzattachtype), true);

 foreach($aids as $key => $value){
  convertunusedattach($value,$_G['tid'],$pid); 
 }
 if(getglobal('setting/ftp/on')){
  ftpupload($aids,intval($_G['uid']));
 }
 
}

//zzcity add attachment close



	if($specialextra) {

		@include_once DISCUZ_ROOT.'./source/plugin/'.$_G['setting']['threadplugins'][$specialextra]['module'].'.class.php';
		$classname = 'threadplugin_'.$specialextra;
		if(class_exists($classname) && method_exists($threadpluginclass = new $classname, 'newreply_submit_end')) {
			$threadpluginclass->newreply_submit_end($_G['fid'], $_G['tid']);
		}

	}

	if($modpost->pid && !$modpost->param('modnewreplies')) {

		if(!empty($_GET['addfeed'])) {
			$modpost->replyfeed();
		}
	}


	if($modpost->param('modnewreplies')) {
		$url = "forum.php?mod=viewthread&tid=".$_G['tid'];
	} else {
		$url = "forum.php?mod=viewthread&tid=".$_G['tid']."&pid=".$modpost->pid."&page=".$modpost->param('page')."&extra=".$extra."#pid".$modpost->pid;
	}
//
//	if(!isset($inspacecpshare)) {
//		showmessage($return , $url, $modpost->param('showmsgparam'));
//	}
//
//}
exit('[ok]replyno='.$_G['gp_replyno']); //zzcityadd  


//require_once libfile('post/newreply', 'include');替换结束



function check_allow_action($action = 'allowpost') {
 global $_G;
// if(isset($_G['forum'][$action]) && $_G['forum'][$action] == -1) {
//  showmessage('forum_access_disallow');
// }
}

function recent_use_tag() {
    $tagarray = $stringarray = array();
    $string = '';
    $i = 0;
    $query = C::t('common_tagitem')->select(0, 0, 'tid', 'itemid', 'DESC', 10);
    foreach($query as $result) {
        if($i > 4) {
            break;
        }
        if($tagarray[$result['tagid']] == '') {
            $i++;
        }
        $tagarray[$result['tagid']] = 1;
    }
    if($tagarray) {
        $query = C::t('common_tag')->fetch_all(array_keys($tagarray));
        foreach($query as $result) {
            $tagarray[$result[tagid]] = $result['tagname'];
        }
    }
    return $tagarray;
}




//require DISCUZ_ROOT.'./source/module/forum/forum_'.$mod.'.php';替换结束

?>