<?php

require_once('conf/dbc.php');
require_once('conf/session_start.php');
require_once('conf/ban.php');
if ((!isset($_SESSION['id'])) and (!isset($_SESSION['nick'])))  {
  ?>
  <script type="text/javascript">
  document.location.href = "reg.php?err_login=1";
  </script>
  <?php
}
$H=getenv("HTTP_REFERER");
if (empty($H)) {
  ?>
  <script type="text/javascript">
  document.location.href = "index.php";
  </script>
  <?php
  exit();
}
$subforum = abs(intval($_GET['subforum']));
if (empty($subforum)) {
  ?>
  <script type="text/javascript">
  document.location.href = "index.php";
  </script>
  <?php
  exit(); 
}
/////////////Указали subforum
$user_id = abs(intval($_SESSION['id']));
$query= "Select clan, rangs_cre, main, gruppa, name_subf from subforums where id_subf='$subforum' limit 1";
$result = mysqli_query($dbc, $query) or die ('Ошибка передачи запроса к БД');
$row = mysqli_fetch_array($result);
if (empty($row)) {
  ?>
  <script type="text/javascript">
  document.location.href = "index.php";
  </script>
  <?php
  exit(); 
}
//////////////SUBFORUM ТОЧНО СУЩЕСТВУЕТ
$query_user = "Select clan, clan_rang, gruppa, f_ban, lvl, admin from users where id='$user_id' limit 1";
$result_user = mysqli_query($dbc, $query_user) or die ('Ошибка передачи запроса к БД');
$row_user = mysqli_fetch_array($result_user);
if ($subforum == 1 and $row_user['admin'] <> 1) {
      ?>
      <script type="text/javascript">
      document.location.href = "subforum.php?subforum=<?php echo "$subforum";?>&err=1";
      </script>
      <?php
      exit(); 
} 
$row = $pdo->query("Select rangs_read, rangs_cre, name_subf, main, clan, gruppa from subforums where id_subf = '$subforum' limit 1")->fetch();
if ($row['main'] == 0) {//////////////Если это клан подфорум
  if ($row['clan'] == $row_user['clan']) {/////////Если это клан юзера
    if ($row['rangs_cre'] > $row_user['clan_rang']) {////////Если ранг не позволяет.
	  ?>
      <script type="text/javascript">
      document.location.href = "subforum.php?subforum=<?php echo "$subforum";?>";
      </script>
      <?php
      exit(); 
	} 
  }
  else {////////Если это клан НЕ ЮЗЕРА
    if ($row['rangs_cre'] <> 0) {////////Если писать всем нельзя
	  ?>
      <script type="text/javascript">
      document.location.href = "subforum.php?subforum=<?php echo "$subforum be";?>";
      </script>
      <?php
      exit(); 
	} 
  }
}
else {
 if ($row_user['admin'] <> 1 and $row_user['admin'] <> 2) {
  if ($row_user['f_ban'] == 1 or $row_user['lvl'] < 10) {
	  ?>
      <script type="text/javascript">
      document.location.href = "subforum.php?subforum=<?php echo "$subforum";?>&err=4";
      </script>
      <?php
      exit(); 
  }
  else {
    if ($row['gruppa'] <> 'all' and $row['gruppa'] <> $row_user['gruppa']) {
      ?>
      <script type="text/javascript">
      document.location.href = "subforum.php?subforum=<?php echo "$subforum";?>";
      </script>
      <?php
      exit(); 
	}
}
  } 
}
///////////////////////////////////На всё проверили.
$create = filter($_POST['create']);
if (isset($create)) {
$name = filter($_POST['name']);
  $cr = 1;
  $long_name = strlen($name);
  if (($long_name<2) or ($long_name>32)) {
    $err = 1;
	$cr = 0;
  }
$text = filter($_POST['text']);
  $long_text = strlen($text);
  if (($long_text<1) or ($long_text>20000)) {
    $err = 2;
	$cr = 0;
  }
  if ($cr == 1) {
    $name = str_replace('<','&lt;', $name);
	$name = str_replace('<img src = "1.jpg">','=)', $name);
    $name = str_replace('>','&gt;', $name);
    $name = str_replace('"','&quot', $name);
    $name=stripslashes("$name");
    $name =  mysqli_real_escape_string($dbc, trim($name));
    $text = preg_replace('/(\r\n)+/', "\r\n", $text);
    $text = preg_replace('/(\r)+/', "\r", $text);
    $text = preg_replace('/(\n)+/', "\n", $text);
	$text = str_replace('<','&lt;', $text);
    $text = str_replace('<img src = "1.jpg">','=)', $text);
    $text = str_replace('>','&gt;', $text);
    $text = str_replace('"','&quot', $text);
    $text = strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />', '=D' => '<img src="img/smiles/D.gif" />', ':-D' => '<img src="img/smiles/D.gif" />', ':D' => '<img src="img/smiles/D.gif" />','mobstalker' => '<img src="img/smiles/smile.gif" />', '.net' => '<img src="img/smiles/smile.gif" />', '.com' => '<img src="img/smiles/smile.gif" />', '.tk' => '<img src="img/smiles/smile.gif" />', '.su' => '<img src="img/smiles/smile.gif" />', '.ru' => '<img src="img/smiles/smile.gif" />', 'sta1ker' => '<img src="img/smiles/smile.gif" />',':-)' => '<img src="img/smiles/smile.gif" />', '=)' => '<img src="img/smiles/smile.gif" />',':)' => '<img src="img/smiles/smile.gif" />',':(' => '<img src="img/smiles/sad.gif" />', ':собака' => '<img src="img/monsters/3.png" width="30" height="30" border="0"/>', "[b]" => '<b>', "[/b]" => '</b>',':зло' => '<img src="img/smiles/zlo.gif" />', ":хмм" =>'<img src="img/smiles/xmm.gif" />', ":пишу" =>'<img src="img/smiles/mail.gif" />', ":хаха" => '<img src="img/smiles/xaxa.gif" />', ":ого" => '<img src="img/smiles/vau.gif" />', ":тихо" => '<img src="img/smiles/tiho.gif" />', ":смерть" => '<img src="img/smiles/smert.gif" />', ":поиск" => '<img src="img/smiles/poisk.gif" />', ":накрыло" => '<img src="img/smiles/pizdec.gif" />', ":оу" => '<img src="img/smiles/oy.gif" />', ":упс" => '<img src="img/smiles/oops.gif" />', ":ням" => '<img src="img/smiles/nyam.gif" />', ":ноно" => '<img src="img/smiles/nono.gif" />', ":нет" => '<img src="img/smiles/no.gif" />', ":ниндзя" => '<img src="img/smiles/ninja.gif" />', ":незнаю" => '<img src="img/smiles/neznaju.gif" />', ":неа" => '<img src="img/smiles/nea.gif" />', ":муз" => '<img src="img/smiles/music.gif" />', ":мистер" => '<img src="img/smiles/mister.gif" />', ":ламер" => '<img src="img/smiles/lamer.gif" />', ":кыш" => '<img src="img/smiles/kulak.gif" />', ":крут" => '<img src="img/smiles/krut.gif" />', ":кул" => '<img src="img/smiles/klass.gif" />', ":класс" => '<img src="img/smiles/klass.gif" />', ":супер" => '<img src="img/smiles/klass.gif" />', ":пока" => '<img src="img/smiles/hello.gif" />', ":фак" => '<img src="img/smiles/fuck.gif" />', ":флуд" => '<img src="img/smiles/flood.gif" />', ":фингал" => '<img src="img/smiles/fingal.gif" />', ":холодно" => '<img src="img/smiles/cold.gif" />', ":бомба" => '<img src="img/smiles/bomba.gif" />', ":блин" => '<img src="img/smiles/blin.gif" />', ":бан" => '<img src="img/smiles/ban.gif" />', ":атлет" => '<img src="img/smiles/atlet.gif" />', ":ааа" => '<img src="img/smiles/aaa.gif" />', ":8" => '<img src="img/smiles/8.gif" />', "[i]" => '<i>', "[/i]" => '</i>', "[big]" => '<big>', "[/big]" => '</big>', "[small]" => '<small>', "[/small]" => '</small>', "[s]" => '<s>', "[/s]" => '</S>', "[u]" => '<u>', "[/u]" => '</u>', "[pre]" => '<pre>', "[/pre]" => '</pre>', "[green]" => '<font color="gren">', "[/green]" => '</font>',"[grey]" => '<font color="grey">', "[/grey]" => '</font>',"[blue]" => '<font color="blue">', "[/blue]" => '</font>'));    $text=stripslashes("$text");
    $text =  mysqli_real_escape_string($dbc, trim($text));
	$query_cr = "insert into topics (`id_subf`, `avtor`, `fix`, `text`, `time_cre`, `time_up`, `name`) values ('$subforum', '$user_id', '0', '$text', NOW(), NOW(), '$name')";
	$result_cr = mysqli_query($dbc, $query_cr) or die ('Ошибка передачи запроса к БД1');
	$query_cr = "select id_top from topics where id_subf='$subforum' and avtor='$user_id' and  fix=0 and text = '$text' and name = '$name'";
	$result_cr = mysqli_query($dbc, $query_cr) or die ('Ошибка передачи запроса к БД');
	$row_cr = mysqli_fetch_array($result_cr);
	$id_top = $row_cr['id_top'];
	?>
    <script type="text/javascript">
    document.location.href = "topic.php?topic=<?php echo "$id_top";?>";
    </script>
    <?php
    exit();
  }
}
$page_title = 'Создать новый топик';
require_once('conf/head.php');
require_once('conf/top.php')
?>
<?php
if ($err == 1) {?><p id="error">Название должно быть в пределах от 2 до 32 символов</p><?php }
elseif ($err == 2) {?><p id="error">Название должно быть в пределах от 1 до 1024 символов</p><?php }
?>
<div class="stats">
<p><?php if ($row['main'] == 1) {?> <img src="img/ico/forum_new.png" width="12" height="12"/> <a href="forum.php?type=main">Форум игры</a><?php } else {?><img src="img/ico/forum_new.png" width="12" height="12"/> <a href="forum.php?type=company&company=<?php echo $row['clan'];?>">Форум отряда</a><?php }?><span class="white"> / </span><a href="subforum.php?subforum=<?php echo "$subforum";?>"><?php echo $row['name_subf']?></a></p>
</div>
<p>Заголовок:</p>
<form enctype="multipart/form-data" method="post" action="<? $_SERVER['PHP_SELF']; ?>">
<input type="text" style="height:20px; width:230px;" class="input" name="name" /><br />
<p>Сообщение:</p>
<textarea rows="2" cols="35px" style="width:230px;" name="text"></textarea>
<div class="knopka">
<input type="submit" class="input" value="Создать" name="create"/>
</div>
</form>
<?php
require_once('conf/navig.php');
require_once('conf/foot.php'); 
mysqli_close($dbc);
?>