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

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



  @ include ('inc/city/getcity.php');


if (!isset($_GET['area_id'])) {
  $_GET['area_id'] = $_POST['area_id'];
}

if ($_GET['area_id'] == '' || !preg_match('/^\d+\-\d+(\_\d+)*$/', $_GET['area_id'])) {
  err('标签参数为空或错误！请重选分类。');
}

          /**************** 此处可删除，但需要列表页部分代码的配合 **************
          if (is_numeric($_GET['area_id'])) {
            err('此大类没有创建二级分类，不能发表。');
          }
          **************** 此处可删除，但需要列表页部分代码的配合 **************/

$total_funds = 0;
$wother = '';

@ require ('inc/set/set_userface.php');

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

$sql['sql_version'] = @mysql_get_server_info();
/*
echo '<span class="grayword">检测MYSQL版本…</span>';
@ob_flush();
@flush();
*/
if ($sql['sql_version'] < '5.0') {
  err('服务器数据库版本（'.$sql['sql_version'].'）太低！本重要命令页禁止执行，以免出错。本程序建设基于MySQL版本5.0以上');
}
/*
echo '√<br />';
echo '<span class="grayword">检测栏目、分类参数…</span>';
@ob_flush();
@flush();
*/
//栏目属性
$result = @mysql_query('SELECT * FROM '.$sql['pref'].''.$sql['data']['承载版区分类的表名'].' WHERE area_id="'.get_arearoot($_GET['area_id']).'" LIMIT 1', $db);
if (!$area_power = @mysql_fetch_assoc($result)) {
  err('系统错误：标签参数不合法（数据库找不到该类别根栏目）！请重选分类。');
}
@mysql_free_result($result);

//取版区信息
$result = @mysql_query('SELECT id FROM '.$sql['pref'].''.$sql['data']['承载版区分类的表名'].' WHERE area_id="'.$_GET['area_id'].'" LIMIT 1', $db);
if (!@mysql_num_rows($result) > 0) {
  err('系统错误：标签参数不合法（数据库找不到该类别）！请重选分类。');
}
@mysql_free_result($result);
/*
echo '√<br />';
echo '<span class="grayword">身份验证…</span>';
@ob_flush();
@flush();
*/
/* 身份验证 */
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
    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'].'_', 't')) { //a所有，t主题
      err('提交被拒绝！您已经被限制发表，具体请询问管理员，以获得发表权限。');
    }
    if (floatval($web['write_start']) > 0 && $row_member['point'] < floatval($web['write_start'])) {
      err('提交被拒绝！系统设置发表需等级分达到'.$web['write_start'].'分。');
    }
    if (floatval($area_power['area_power_write']) > 0 && $row_member['point'] < floatval($area_power['area_power_write'])) {
      err('提交被拒绝！本类别发表积分需达到'.$area_power['area_power_write'].'分。');
    }
  }
  $linkpr = POWER > 1 ? true : ($row_member['point'] < $web['link_start'] ? false : true);
  $wother = 'del_uploadfiles();';

} else {

  if (!empty($area_power['area_power_write'])) {
    err('提交被拒绝！该分类禁止匿名发表！<a href="./reg.php" target="_blank">先去注册</a>或<a href="./login.php" target="_blank">登陆</a>，以获得发表权限。');
  }
  //$session[0] = POWER == 0.5 ? $session[0] : user_ip();
  $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段已被屏蔽，禁止操作。');
  }
  if (!$_COOKIE['regimcode'] || !$_POST['imcode'] || $_POST['imcode'] != $_COOKIE['regimcode']) {
    err('验证码缺失或不符！');
  }
  $linkpr = false;

}
/*
echo '√<br />';
echo '<span class="grayword">过滤、检测文本…</span>';
@ob_flush();
@flush();
*/
/* 过滤、检测 */
@ require ('inc/function/filter.php');
@ require ('inc/function/write_file.php');
$subject = filter1($_POST['subject'], true);
server_sbj($subject);
$content = filter2($_POST['content']);
server_chk($content, $web['list_wordcount']);

//FULLTEXT
$subject_fulltext = preg_replace('/[[:punct:]]/i', ' ', $subject);
$subject_fulltext = preg_replace('/\pP/u', ' ', $subject_fulltext);
$subject_fulltext = preg_replace('/[\xe0-\xef][\x80-\xbf]{2}/e', '"".toUnicode("$0").""', $subject_fulltext);

$keyword_fulltext = preg_replace('/[[:punct:]]/i', ' ', filter1($_POST['keyword'], true));
$keyword_fulltext = preg_replace('/\pP/u', ' ', $keyword_fulltext);
$keyword_fulltext = preg_replace('/[\xe0-\xef][\x80-\xbf]{2}/e', '"".toUnicode("$0").""', $keyword_fulltext);

$title_key = ''.$subject_fulltext.'|TMD| '.$keyword_fulltext;
/*
echo '√<br />';
@ob_flush();
@flush();
*/
//处理悬赏
$reward = round(floatval($_POST['reward']), 2);
if ($reward > 0) {
  if (POWER > 0 && POWER < 4) {
    //求和货币值
    $result = @mysql_query('SELECT SUM(money) AS total FROM '.$sql['pref'].''.$sql['data']['承载财务数据的表名'].' WHERE (username="'.$session[0].'" AND type="0")', $db);
    $row = @mysql_fetch_assoc($result);
    $total_funds = floatval($row['total']);
    unset($row);
    @mysql_free_result($result);
    if ($reward > $total_funds) {
      err('你的悬赏值（'.$reward.'）超过了你的货币值余额（'.$total_funds.'）！');
    }
    $eval_reward = '@mysql_query(\'INSERT INTO `'.$sql['pref'].''.$sql['data']['承载财务数据的表名'].'` (`username`,`type`,`description`,`money`,`date`,`other`) VALUES ("'.$session[0].'","0","设置悬赏","-'.$reward.'",DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),"文章ID：<a href=\"article.php?mode='.$web['sitemode'].'&id=\'.$now_id.\'\" target=\"_blank\">\'.$now_id.\'</a>")\', $db);
';
  }
  $title_mark_ = '<img src="inc/images/coin.gif" title="悬赏" />';
  $insert_eval_2 .= ',`reward`="'.$reward.'"';
}
/*
echo '<span class="grayword">发表间隔及日发表限量检测…</span>';
@ob_flush();
@flush();
*/
$date = gmdate("Y-m-d H:i:s", 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,MAX(date),DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR)) AS t FROM `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` WHERE author_ip="'.$session[0].'"', $db); //
    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 || $web['send_re'] == 2) {
    if ($web['send_re'] == 2) {
      $ko1 = ' B.author_ip="'.$session[0].'" AND';
      $ko2 = '您所发布的';
    }

    $result = @mysql_query('SELECT COUNT(A.id) AS cf FROM '.$sql['pref'].''.$sql['data']['承载关键词的表名'].' AS A,'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].' AS B WHERE'.$ko1.' A.id=B.id AND (MATCH (A.title) AGAINST (\'"'.$subject_fulltext.'|TMD|"\' IN BOOLEAN MODE))', $db);
    $row = @mysql_fetch_assoc($result);
    @mysql_free_result($result);
    if ($row['cf'] > 0) {
      err(''.$ko2.'文章库中已有相同题目的记录！禁止信息重复。');
    }
    unset($row);
  }

  /*限制发布数量*/
  if ($web['send_mx'] == 1) {
    //求和信誉值
    $result = @mysql_query('SELECT SUM(money) AS total FROM '.$sql['pref'].''.$sql['data']['承载财务数据的表名'].' WHERE (username="'.$session[0].'" AND type="1")', $db);
    $row = @mysql_fetch_assoc($result);
    $total_credit = (float)$row['total'];
    unset($row);
    @mysql_free_result($result);

    require ('inc/function/send_mx.php');
    $yijing = 0;
    if ($send_mx = send_mx(abs($session[3]), $total_credit)) {
      $result = @mysql_query('SELECT COUNT(id) AS total FROM `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` WHERE author_ip="'.$session[0].'" AND `date` LIKE "'.$date.'%"', $db);
      $row = @mysql_fetch_assoc($result);
      $yijing = (float)$row['total'];
      unset($row);
      @mysql_free_result($result);
      if ($yijing >= $send_mx) {
        err('今天您已经达到最大发布量'.$send_mx.'条。');
      }
      $limiterr = '<br />
      <br />
      你每日发布限量为'.$send_mx.'条<br />
      今日已经发布'.($yijing + 1).'条<br />
      今日还可发布'.($send_mx - ($yijing + 1)).'条';
    }
  }
}
/*
echo '√<br />';
@ob_flush();
@flush();
*/

/*
@mysql_query('INSERT INTO `'.$sql['pref'].''.$sql['data']['承载关键词的表名'].'` (`title`) VALUES ("")', $db);
$now_id_ = @mysql_insert_id();
*/
@mysql_query('INSERT INTO `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` (`title`,`text`) VALUES ("","")', $db);
$now_id = @mysql_insert_id();

if (!is_numeric($now_id) || $now_id == 0) {
  err('插入数据出错！数据没有加入数据库。程序出错['.mysql_errno().':'.mysql_error().']。');
}
/*
if ($now_id_ != $now_id) {
  $sql_err = mysql_errno().':'.mysql_error();
  @mysql_query('DELETE FROM '.$sql['pref'].''.$sql['data']['承载关键词的表名'].' WHERE id="'.$now_id_.'"', $db);
  @mysql_query('DELETE FROM '.$sql['pref'].''.$sql['data']['承载主题文章的表名'].' WHERE id="'.$now_id.'"', $db);
  err('插入数据出错['.$sql_err.']！主数据表与搜索关键词表未同步生成记录。请返回重新提交。<br />（正在同步处理…）');
}
*/


$up_arr = array();
//图
if (preg_match('/<img [^>]*src[\s\r\n]*=(?![\s\r\n]*\"?('.preg_quote($web['path'], '/').')?inc\/images\/)[^>]*>/i', $content, $mi)) {
  $title_mark .= '<img src="inc/images/picye.gif" title="文中含图" />';

  @ require ('inc/function/img.php');
/*
  @ob_flush();
  @flush();
  echo '<span class="grayword">正在处理缩略图…</span>';
*/
  //处理缩略图
  $temp_thumb = 'thuml';
  $thumb = urldecode(preg_replace('/.+src[\s\r\n]*=[\s\r\n]*(\"|\')?([^\"\>\s]+\.(gif|jpg|png)).+/i', '$2', $mi[0]));
  $thumb_format = strtolower(ltrim(strrchr($thumb, '.'), '.'));
  $thumb_here = '__temp__/temp/'.$temp_thumb.'-'.$now_id.'.'.$thumb_format.'';

  if (substr($thumb, 0, 14) == 'obj.php?title=') {
    $result = @mysql_query('SELECT `text` FROM '.$sql['pref'].''.$sql['data']['承载上传数据的表名'].' WHERE title="'.substr($thumb, 14).'" LIMIT 1', $db);
    if ($row_t = @mysql_fetch_assoc($result)) {
      $thumb_contents = $row_t['text'];
    }
    unset($row_t);
    @mysql_free_result($result);
  } else {
    $thumb_contents = @file_get_contents($thumb);
  }
  if ($thumb_contents) {
    write_file($thumb_here, $thumb_contents);
    //if (run_img_resize($thumb_here, $thumb_here, 120, false, 75)) {
    run_img_resize($thumb_here, $thumb_here, 120, false, 75);
      $thumb_here = typeto($thumb_here, 'jpg');
      if ($thumb_content = @file_get_contents($thumb_here)) {
        $up_arr[$thumb_here] = '
      @mysql_query(\'REPLACE INTO `'.$sql['pref'].''.$sql['data']['承载上传数据的表名'].'` (`title`,`text`,`type`,`username`,`date`) VALUES ("'.basename($thumb_here).'","\'.mysql_real_escape_string($thumb_content).\'","image/jpeg","'.$session[0].'",DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR))\', $db);
        unlink($thumb_content);
      ';
      }
    //}
  }
/*
  echo '√<br />';
*/
}
if (preg_match('/<embed [^>]*src[\s\r\n]*=[^>]+>|<object [^>]*><param [^>]*value[\s\r\n]*=[^>]+>/i', $content)) {
  $title_mark .= '<img src="inc/images/picfil.gif" title="文中含影辑" />';
}
if (preg_match('/<a [^>]*href[\s\r\n]*=[^\>]+\.('.$web['_18_type'].')[^>]*>/i', $content)) {
  $title_mark .= '<img src="inc/images/picenc.gif" title="文中含附件" />';
}
$title_mark .= $title_mark_;
/*
echo '<span class="grayword">处理上传附件…</span>';
@ob_flush();
@flush();
*/
$content = preg_replace('/(<[^>]+)(__temp__\/temp\/\d+-[^\/\"\s]+)/ie', '"$1".cha_up("$2").""', $content);
/*
echo '√<br />';
@ob_flush();
@flush();
*/
function cha_up($file) {
  global $web, $sql, $now_id, $up_arr, $session;
  $filename = urldecode(basename($file));
  $format = strtolower(ltrim(strrchr($filename, '.'), '.'));
  $title = 'info-'.$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);
        unlink($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);
}


$insert_eval_3 = '';
if (!empty($area_power['area_check'])) {
  if (POWER <= 1) {
    //$insert_eval_1 = ',`area_check`';
    //$insert_eval_2 = ',"1"';
    $insert_eval_2 .= ',`area_check`="1"';
    $insert_output = '你的发表已提交管理员审核，请待候。';
  } else {
    $insert_eval_3 = '@mysql_query(\'UPDATE `'.$sql['pref'].''.$sql['data']['承载成员档案的表名'].'` SET writecount=writecount+1,point=point+'.abs($web['writeadd']).' WHERE username="'.$session[0].'"\', $db);';
  }
} else {
  if (POWER > 0) {
    $insert_eval_3 = '@mysql_query(\'UPDATE `'.$sql['pref'].''.$sql['data']['承载成员档案的表名'].'` SET writecount=writecount+1,point=point+'.abs($web['writeadd']).' WHERE username="'.$session[0].'"\', $db);';
  }
}
/*
echo '<span class="grayword">存入数据库…</span>';
@ob_flush();
@flush();
*/
$youcity = $city['province'] == $city['city'] ? $city['city'] : $city['province'].' '.$city['city'];

@mysql_query('UPDATE `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` SET
`city`="'.mysql_real_escape_string($youcity).'",
`title`="'.mysql_real_escape_string($subject).'",
`text`="'.mysql_real_escape_string($content).'",
`title_mark`="'.mysql_real_escape_string($title_mark).'",
`date`=DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),
`area_id`="'.$_GET['area_id'].'",
`author_ip`="'.$session[0].'",
`topdate`=DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR)'.$insert_eval_2.'
WHERE id="'.$now_id.'"', $db);
$new_add2 = @mysql_affected_rows();
/*
echo '√<br />';
@ob_flush();
@flush();
*/


if (/*$new_add1 > 0 && */$new_add2 > 0) {
  @mysql_query('REPLACE INTO `'.$sql['pref'].''.$sql['data']['承载关键词的表名'].'` (`id`,`title`) VALUES ("'.$now_id.'","'.$title_key.'")', $db);
  if (count($up_arr) > 0) {
    //print_r($up_arr);die();
    foreach ($up_arr as $k => $s) {
      eval($s);
    }
  }
  if (isset($insert_eval_3)) {
    eval($insert_eval_3);
    if ($wother != '') {

      //更新用户档案
      $cookie_time = time() + (floatval($web['time_pos']) * 3600);
      setcookie('usercookie', $session[0].'|'.$session[1].'|'.$session[2].'|'.($row_member['point'] + abs($web['writeadd'])).'|'.$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'] + abs($web['writeadd'])).'|'.$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'] + abs($web['writeadd'])).'|'.$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'] + abs($web['writeadd'])).'|'.$row_member['power'].'|'.$session[5].'|'.$session[6].'|'.$web['path'].'")+";'.$expires.' path=/;";
      -->
      </script>';
	  */
    }
    require ('inc/function/area_statistics.php');

    add_total(get_arearoot($_GET['area_id']), $db, '+1');
    add_today(get_arearoot($_GET['area_id']), $db, '+1');
  }


  eval($eval_reward);
  //更新热标签
  require ('inc/function/hot_user.php');
  require ('inc/function/hot_mark.php');
  @mysql_close();

  eval($wother);

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

  if (file_exists('get_newinfo_for162100_run.php')) {
    include ('get_newinfo_for162100_run.php');
  }

  if ($_POST['m']==1) {
    err('
<script>
  if (parent.$("submit_safe_in")!=null) parent.$("submit_safe_in").innerHTML="发布成功！";
  parent.runReset();
  setTimeout("parent.location.href=\''.$article_url.'\';", 1000);
</script>发布成功！', 'ok');
    
  }

  alert('发布成功！'.$insert_output.$limiterr.'', $article_url);
} else {
  $sql_err = mysql_errno().':'.mysql_error();
  @mysql_close();
  eval($wother);
  err('添加数据不成功['.$sql_err.']！');
}

?>