<?php
require ('authentication_member.php');
?>
<?php

/* 发表回复提交 */
/* 162100源码 - 162100.com */

if ($_POST['id'] == '' || !is_numeric($_POST['id'])) {
  err('ID参数为空或错误！');
}

@ require ('inc/function/filter.php');
@ require ('inc/set/set_userface.php');
$wother = '';

if (!isset($sql['db_err'])) {
  db_conn();
}
if ($sql['db_err'] != '') {
  err($sql['db_err']);
}

$sql['sql_version'] = @mysql_get_server_info();

if (isset($sql['sql_version']) && $sql['sql_version'] < '5.0') {
  err('服务器数据库版本（'.$sql['sql_version'].'）太低！本重要命令页禁止执行，以免出错。本程序建设基于MySQL版本5.0以上');
}

$result = @mysql_query('SELECT id,area_check,area_id,topdate,reply,author_ip FROM `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` WHERE id="'.$_POST['id'].'"', $db);
if (!$row_this = @mysql_fetch_assoc($result)) {
  err('数据库查不到你要回复的文章！可能参数出错或已被删除。');
}
if ($row_this['area_check'] == '1' || $row_this['area_check'] == '2') {
  err('文章正提交管理员审核中！暂不允回复评论。');
}
@mysql_free_result($result);

//栏目属性
$result = @mysql_query('SELECT * FROM '.$sql['pref'].''.$sql['data']['承载版区分类的表名'].' WHERE area_id="'.get_arearoot($row_this['area_id']).'" LIMIT 1', $db);
if (!$area_power = @mysql_fetch_assoc($result)) {
  err('<script> alert("系统错误：标签参数不合法（找不到该类别根栏目）！请放弃此次发表。"); </script>');
}
@mysql_free_result($result);

//取版区信息
$result = @mysql_query('SELECT id FROM '.$sql['pref'].''.$sql['data']['承载版区分类的表名'].' WHERE area_id="'.$row_this['area_id'].'" LIMIT 1', $db);
if (!@mysql_num_rows($result) > 0) {
  err('<script> alert("系统错误：标签参数不合法（找不到该类别）！请放弃此次发表。"); </script>');
}
@mysql_free_result($result);

//过期
if (floatval($area_power['area_expires']) > 0) {
  if ($row_this['topdate'] < gmdate('Y-m-d H:i:s', time() + (floatval($web['time_pos']) * 3600) - floatval($area_power['area_expires']) * 86400)) {
    err('<script> alert("该文时效期已过，回复评论被关闭！"); </script>');
  }
}

/* 身份验证 */
if (POWER >= 1) {
  if (is_numeric($web['reg_to_send']) && $web['reg_to_send'] > 0) {
    $date_diff = ',TIMESTAMPDIFF(SECOND,regdate,DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR)) AS t_diff';
    $date_eval = '
    if ($row_member["t_diff"] < $web["reg_to_send"]) {
      err("提交被拒绝！系统设定：新注册成员".$web["reg_to_send"]."秒（".round($web["reg_to_send"] / 3600, 2)."小时）之后才能发表。你还要等".round(($web["reg_to_send"] - $row_member["t_diff"])/ 3600, 2)."小时。");
    }';
  }
  $result = @mysql_query('SELECT power,point,check_reg'.$date_diff.' FROM '.$sql['pref'].''.$sql['data']['承载成员档案的表名'].' WHERE username="'.$session[0].'"', $db);
  if (!$row_member = @mysql_fetch_assoc($result)) {
    err('查无您的档案！您不是合法的注册成员。');
  }
  @mysql_free_result($result);
  if ($row_member['check_reg'] == '1') {
    err('您的注册尚在审核中！您不是合法的注册成员。');
  }
  if ($row_member['check_reg'] == '2') {
    err('您的帐户已被管理员移除至<a href="list_member.php?act=punished" target="_blank">黑名单</a>。');
  }
  //if (POWER == 1) { //不计管理员5、4、版主3、2
  if (POWER < 4) {
    eval($date_eval);
    if ($web['send_face'] == 1) {
      if (!(@mysql_num_rows(@mysql_query('SELECT id FROM `'.$sql['pref'].''.$sql['data']['承载上传数据的表名'].'` WHERE title LIKE "face-'.$session[0].'.%"', $db)) > 0)) {
        err('提交被拒绝！注册成员必须<a href="member.php" target="_blank">上传</a>了头像才允许发表。');
      }
    }
    if (strstr($row_member['power'].'_', 'a') || strstr($row_member['power'].'_', 'r')) { //a所有，r回复
      err('提交被拒绝！您已经被限制评论或回复，具体请询问管理员，以获得权限。');
    }
    if (floatval($area_power['area_power_reply']) > 0 && $row_member['point'] < floatval($area_power['area_power_reply'])) {
      err('提交被拒绝！本类别回复积分需达到'.$area_power['area_power_reply'].'分。');
    }
  }
  $linkpr = POWER > 1 ? true : ($row_member['point'] < $web['link_start'] ? false : true);
  $wother = 'del_uploadfiles();';

} else {

  if (!empty($area_power['area_power_reply'])) {
    err('提交被拒绝！该分类禁止匿名回复！<a href="./reg.php" target="_blank">先去注册</a>或<a href="./login.php" target="_blank">登陆</a>，以获得回复权限。');
  }
  if (!$_COOKIE['regimcode'] || !$_POST['imcode'] || $_POST['imcode'] != $_COOKIE['regimcode']) {
    err('验证码缺失或不符！');
  }
  $session[0] = user_ip();
  if (@mysql_num_rows(@mysql_query('SELECT id FROM `'.$sql['pref'].''.$sql['data']['承载上传数据的表名'].'` WHERE title LIKE "'.preg_replace('/(\d+|\*+)$/', '%', $session[0]).'" AND type="ip"', $db)) > 0) {
    err('抱歉，你所处的IP段已被屏蔽，禁止操作。');
  }
  $linkpr = false;

}
@ require ('inc/function/cutstr.php');

if (!empty($_POST['lou'])) {
  list($bu, $reto_author, $re_id, $re_text) = @explode('|', $_POST['lou']);
  if (!empty($re_id) && is_numeric($re_id)) {
    $re_eval = '
  var nextObj=parent.$("reply_'.$re_id.'").nextSibling;
  while(nextObj!=null && nextObj.nodeType!=1){
    nextObj=nextObj.nextSibling;
  }
  if(nextObj==null){
    intoP=null;
  }else{
    intoP=nextObj;
  }
';
  }
  //$re_eval_for_mess = ''; //发短信

  $insert_eval_quote = ',`quote`="'.$re_id.'"';
  $re_text = filter2($re_text);
  $short_str=cutstr($re_text, 450);
  if (preg_match('/<img [^>]*src[\s\r\n]*=(?![\s\r\n]*\"?('.preg_quote($web['path'], '/').')?inc\/images\/)[^>]*>/i', $re_text, $mi)) {
    $first_img='<br /><span class="iface_s">'.$mi[0].'</span>';
  }
  $content_quote = '<div class="text"><fieldset><legend><b><a href="user.php?get=card&username='.urlencode($reto_author).'" target="_blank">'.$reto_author.'</a> 发表在 <a href="?mode='.$_POST['mode'].'&id='.$_POST['id'].'&reply_id='.$re_id.'#reply_'.$re_id.'">'.$bu.' 楼</a>：</b></legend>'.$short_str.$first_img.'</fieldset></div>';
  unset($bu, $reto_author, $re_id, $re_text);
}

//过滤、检测
$content = filter2($_POST['content']);
server_chk($content, $web['re_wordcount']);
//$date = gmdate('YmdHis', time() + (floatval($web['time_pos']) * 3600));

if (POWER <= 1) {

  /*限制回复间隔*/
  if (is_numeric($web['send_ms']) && $web['send_ms'] > 0) {
    $result = @mysql_query('SELECT TIMESTAMPDIFF(SECOND,date,DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR)) AS t FROM `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` WHERE author_ip="'.$session[0].'" ORDER BY id DESC LIMIT 1', $db); //(UNIX_TIMESTAMP()-UNIX_TIMESTAMP(date)) AS t
    if (($row = @mysql_fetch_assoc($result)) && !empty($row['t'])) {
      if ($web['send_ms'] - $row['t'] > 0) {
        err('你要'.($web['send_ms'] - $row['t']).'秒后再发下一篇回复。');
      }
      unset($row);
    }
    @mysql_free_result($result);
  }

  /*限制回复重复
  if ($web['send_re'] == 1) {
    $cf = 0;
    $result = @mysql_query('SELECT text,date FROM `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` WHERE r_id="'.$_POST['id'].'" AND author_ip="'.$session[0].'" ORDER BY id DESC',$db);
    $yijing = abs(@mysql_num_rows($result)) + 1; //你已回复记录数
    while ($row = @mysql_fetch_assoc($result)) {
	  similar_text($row['text'], $content, $percent2);
      if($percent2 >= 80){
	    $cf = 1;
	    break;
	  }
    }
    @mysql_free_result($result);
    unset($row);
    if ($cf == 1) {
      err('你已经发布过相似的文章！禁止信息重复。');
    }
  }
  */

  /*限制回复数量*/
  if ($web['send_mx'] == 1) {
    require ('inc/function/send_mx.php');
    $web['reply_mx'] = $web['reply_mx'] ? abs($web['reply_mx']) : 30;
    $result = @mysql_query('SELECT COUNT(id) AS total FROM `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` WHERE r_id="'.$_POST['id'].'" AND author_ip="'.$session[0].'"',$db);
    $row = @mysql_fetch_assoc($result);
    if (abs($row['total']) >= $web['reply_mx']) {
      err('该主题你回复得太多了，已达到'.$web['reply_mx'].'条，歇歇吧。');
    }
    unset($row);
    @mysql_free_result($result);
  }

}

$result = @mysql_query('SELECT `floor` FROM `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` WHERE r_id="'.$_POST['id'].'" ORDER BY id DESC LIMIT 1', $db);// AND text<>"<赞>" AND text<>"<拍>"
$row_re = @mysql_fetch_assoc($result);
@mysql_free_result($result);
$n_re = abs($row_re['floor']);
if ($n_re == 0) {
  $result = @mysql_query('SELECT COUNT(id) AS total FROM `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` WHERE r_id="'.$_POST['id'].'"', $db);
  $row_re = @mysql_fetch_assoc($result);
  $n_re = abs($row_re['total']);
  @mysql_free_result($result);
}
unset($row_re);
$n_re += 1;

@mysql_query('INSERT INTO `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` (`text`) values ("")', $db);
$now_id = @mysql_insert_id();

if (!is_numeric($now_id) || $now_id == 0) {
  err('插入数据出错！数据没有加入数据库。程序出错['.mysql_errno().':'.mysql_error().']。');
}

$up_arr = array();

$content = preg_replace('/(<[^>]+)(__temp__\/temp\/\d+-[^\/\"\s]+)/ie', '"$1".cha_up("$2").""', $content);

function cha_up($file) {
  global $web, $sql, $now_id, $up_arr, $session;
  $filename = urldecode(basename($file));
  $format = strtolower(ltrim(strrchr($filename, '.'), '.'));
  $title = 'reply-'.$_POST['id'].'_'.$now_id.'-'.substr($filename, 0, 14).'.'.$format;
  if ($GLOBALS['ofile'] != $filename) {
    if (file_exists('__temp__/temp/'.$filename)) {
      $mime = preg_replace('/^.+--/i', '', $filename);
      $mime = preg_replace('/\.'.$format.'$/i', '', $mime);
      $up_arr['__temp__/temp/'.$filename] = $web['uploadto'] == 1 ? '
      if ($obj_contents = @file_get_contents($k)) {
        @mysql_query(\'REPLACE INTO `'.$sql['pref'].''.$sql['data']['承载上传数据的表名'].'` (`title`,`text`,`type`,`username`,`date`) VALUES ("'.$title.'","\'.mysql_real_escape_string($obj_contents).\'","'.urldecode($mime).'","'.$session[0].'",DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR))\', $db);
        unset($obj_contents);
      }
      '.($web['temp'] == 1 ? '@rename($k, \'__temp__/temp/'.$title.'\');' : '@unlink($k);').'' : '@rename($k, \'__temp__/temp/'.$title.'\');';
      $GLOBALS['ofile'] = $filename;

    } else {
      err('转移上传文件出错！上传源文件已经不存在，可能是重复提交造成。');
    }
  } else {
    $GLOBALS['ofile'] = $filename;
  }
  return 'obj.php?title='.$title;

}


//过滤链接
if ($linkpr == false) {
  $content = preg_replace('/<a [^>]*>|<\/a\s*>/i', '', $content);
}

if (POWER <= 1 && !empty($area_power['area_check_reply'])) {
  $insert_eval_2 = ',`area_check_reply`="1"';
  $insert_output = '你的回复已提交管理员审核，请待候。';
} else {
  if (abs($web['re_update']) == 1) {
    //$topdate = gmdate('YmdHis', time() + (floatval($web['time_pos']) * 3600));
    @mysql_query('UPDATE `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` SET reply=reply+1,other="'.$session[0].'",topdate=IF(topdate<DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),topdate) WHERE id="'.$_POST['id'].'"', $db);
  } else {
    @mysql_query('UPDATE `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` SET reply=reply+1,other="'.$session[0].'" WHERE id="'.$_POST['id'].'"', $db);
  }
  $insert_eval_3 = '@mysql_query(\'UPDATE `'.$sql['pref'].''.$sql['data']['承载成员档案的表名'].'` SET replycount=replycount+1,point=point+'.abs($web['replyadd']).' WHERE username="'.$session[0].'"\', $db);';
}

@mysql_query('ALTER TABLE `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` ADD COLUMN `floor` int(10) NOT NULL DEFAULT "0"');
@mysql_query('ALTER TABLE `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` ADD COLUMN `quote` int(10) NOT NULL DEFAULT "0"');

@mysql_query('UPDATE `'.$sql['pref'].''.$sql['data']['承载回复评论的表名'].'` SET
`r_id`="'.$_POST['id'].'",
`text`="'.mysql_real_escape_string($content).'",
`date`=DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),
`floor`="'.$n_re.'",
`author_ip`="'.$session[0].'"'.$insert_eval_2.''.$insert_eval_quote.'
WHERE id="'.$now_id.'"', $db);

if (@mysql_affected_rows() > 0) {
  if (count($up_arr) > 0) {
    //print_r($up_arr);die();
    foreach ($up_arr as $k => $s) {
      eval($s);
    }
  }
  if ($wother != '' && $insert_eval_3) {
    //更新用户档案
    eval($insert_eval_3);

    $cookie_time = time() + (floatval($web['time_pos']) * 3600);
    setcookie('usercookie', $session[0].'|'.$session[1].'|'.$session[2].'|'.($row_member['point'] + $web['replyadd']).'|'.$row_member['power'].'|'.$session[5].'|'.$session[6].'|'.$web['path'], (!empty($session[5]) && is_numeric($session[5]) && $session[5] > $cookie_time ? $session[5] : $cookie_time), '/', '.'.$web['root']);
    setcookie('usercookie', $session[0].'|'.$session[1].'|'.$session[2].'|'.($row_member['point'] + $web['replyadd']).'|'.$row_member['power'].'|'.$session[5].'|'.$session[6].'|'.$web['path'], (!empty($session[5]) && is_numeric($session[5]) && $session[5] > $cookie_time ? $session[5] : $cookie_time), '/');
	/*
      $expires = '';
	  if (!empty($session[5]) && is_numeric($session[5]) && $session[5] > (time() + floatval($web['time_pos']) * 3600)) {
	    $GMT = gmdate('D, d M Y H:i:s T', $session[5]);
		$expires = ' expires='.$GMT.';';
      }
      echo '
      <script language="javascript" type="text/javascript">
      <!--
      var expiration=new Date(new Date().getTime()+'.(31536000 + floatval($web["time_pos"]) * 3600).'*1000);
      try{
	  document.cookie="usercookie="+encodeURIComponent("'.$session[0].'|'.$session[1].'|'.$session[2].'|'.($row_member['point'] + $web['replyadd']).'|'.$row_member['power'].'|'.$session[5].'|'.$session[6].'|'.$web['path'].'")+";'.$expires.' path=/; domain=.'.$web['root'].';";
	  }catch (e) {
	  }
	  document.cookie="usercookie="+encodeURIComponent("'.$session[0].'|'.$session[1].'|'.$session[2].'|'.($row_member['point'] + $web['replyadd']).'|'.$row_member['power'].'|'.$session[5].'|'.$session[6].'|'.$web['path'].'")+";'.$expires.' path=/;";
      -->
      </script>';
	*/
	
	
  }
  eval($wother);
  @mysql_close();
  






  $sitemode = (!empty($_POST['mode']) && file_exists('inc/css/'.$_POST['mode'].'/article.php')) ? $_POST['mode'] : $web['sitemode'];
  $totalpages = ceil($n_re / $web['pagesize']);
  $article_url = ($web['url_html_article'] == 1 ? 'article.'.$sitemode.'.'.$_POST['id'].'.'.$totalpages.'.html' : 'article.php?mode='.$sitemode.'&id='.$_POST['id'].'&p='.$totalpages.'').'#reply_'.$now_id.'';




  if ($_POST['m']==1) {
    err('
<script>
if(parent && parent!=self){
  var nowMode="'.$sitemode.'";
  var parMode=parent.$("mode").value;
  if(nowMode==parMode){
    var intoP=null;
    var newDiv=document.createElement("DIV");
    newDiv.innerHTML=\''.for_par_re_js($sitemode, $now_id, $n_re, $content).'\';
    '.$re_eval.'
    if(intoP==null){
      if(parent.$("reply_last")!=null){ 
        intoP=parent.$("reply_last");
      }else{
        intoP=parent.$("reply_last_temp");
        intoP.style.display="block";
        intoP.id="reply_last";
      }
    }
    intoP.parentNode.insertBefore(newDiv, intoP);

    parent.location.href=parent.location.href.toString().replace(/(\#.*)?$/,"")+"#reply_'.$now_id.'";
    if (parent.$("submit_safe_in")!=null) parent.$("submit_safe_in").innerHTML="回复成功！";
    parent.runReset();
    parent.closeLouEditor();
    if(parent.$("tempcode")!=null){parent.$("tempcode").value="";}
    if(parent.$("imFrame")!=null){parent.$("imFrame").src="inc/js/imcode.html";}
  }else{
    parent.location.href="'.$article_url.'";
  }
}else{
  parent.location.href="'.$article_url.'";
}
</script>


回复成功！'.$insert_output, 'ok');
    
  }


  
  alert('评论回复成功！'.$insert_output, preg_replace('/\#.*$/i', '', $article_url).'#reply_'.$now_id.'');
} else {
  $s_err = mysql_errno().':'.mysql_error();
  @mysql_close();
  eval($wother);
  err('评论回复不成功！可能是查不到此ID数据！可能传递出错['.$s_err.']。');
}

function for_par_re_js($sitemode, $now_id, $n_re, $content) {
  global $web, $session, $insert_output, $content_quote;
  $content = isset($insert_output) ? $insert_output : $content;
  switch ($sitemode) {
    case 'f' :
    case 's' :
    if (POWER >= 2) {
      $del_bar = "<span class=\"li_article_r_title2\"><a href=\"webmaster_central.php?post=unity_run&id=".$now_id."&dataname=reply&limit=del&m=1\" target=\"lastFrame\">删除</a></span>";
    }
    return '<table class="li_article" width="100%" border="0" cellspacing="0" cellpadding="0" id="reply_'.$now_id.'"><tr valign="top"><td rowspan="2" class="li_article_l"><a href="member.php" target="_blank">'.(!strstr($session[0], '.')?'<span class="iface_b"><img src="obj.php?title=face-'.urlencode($session[0]).'.'.$web['img_up_format'].'" width="'.$web['img_w_b'].'" height="'.$web['img_h_b'].'" /></span><br />' : '').''.$session[0].'</a></td><td class="li_article_r"><div class="li_article_r_title">回复时间：刚刚 | <b>#'.$n_re.'</b> <a class="add_collect" href="member.php?post=unity_run&dataname=myaccount&id[]='.$now_id.'&limit=collect_reply&m=1" target="lastFrame" title="将回帖加入“我的收藏”"></a></div>'.$content_quote.'<div id="#'.$n_re.'" class="text">'.$content.'</div></td></tr><tr><td valign="bottom" class="li_article_r2">'.$del_bar.'<span class="li_article_r_title2"><a href="#session">TOP</a></span></td></tr></table>';
    break;

    case 'i' :
    case 'a' :
    if (POWER >= 2) {
      $del_bar = " <a href=\"webmaster_central.php?post=unity_run&id=".$now_id."&dataname=reply&limit=del&m=1\" target=\"lastFrame\">删除</a>";
    }
    return '<div id="reply_'.$now_id.'"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="author"><tr><td width="400"><span class="grayword">#'.$n_re.'：</span> '.$session[0].' - <i>刚刚</i></td><td align="right"><a class="add_collect" href="member.php?post=unity_run&dataname=myaccount&id[]='.$now_id.'&limit=collect_reply&m=1" target="lastFrame" title="将回帖加入“我的收藏”"></a>'.$del_bar.'</td></tr></table>'.$content_quote.'<div id="#'.$n_re.'" class="text">'.$content.'</div></div>';

    break;

    default :
    return '';

  }
}



















?>