<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (session_id()=='') session_start();
$time=time();
$db=mysqli_connect("localhost","*******","******","*******") or die();
$res=mysqli_query($db,"set names utf8");
$mess_url=mysqli_real_escape_string($db,basename($_SERVER['SCRIPT_FILENAME']));
//получаем id текущей темы
if (isset ($_GET['id'])) {$id = $_GET['id'];}
if (!isset($id)) {$id = 1;}
$theme_id=$id;
if (isset($_POST["contr_cod"])){ //отправлен комментарий
$mess_login=htmlspecialchars($_POST["mess_login"]);
$user_text=htmlspecialchars($_POST["user_text"]);
if (md5($_POST["contr_cod"])==$_POST["prov_summa"]){ //код правильный
if ($mess_login!='' and $user_text!=''){
if (is_numeric($_POST["parent_id"]) and is_numeric($_POST["f_parent"]))
$res=mysqli_query($db,"insert into comment
(parent_id, first_parent, date, theme_id, login, message)
values ('".$_POST["parent_id"]."','".$_POST["f_parent"]."',
'".$time."','".$theme_id."','".$mess_login."','".$user_text."')");
else $res=mysqli_query($db,"insert into comment (date, theme_id, login, message)
values ('".$time."','".$theme_id."','".$mess_login."','".$user_text."')");
$_SESSION["send"]="Комментарий принят!";
header("Location: $mess_url#last"); exit;
}
else {
$_SESSION["send"]="Не все поля заполнены!";
header("Location: $mess_url#last"); exit;
}
}
else {
$_SESSION["send"]="Неверный проверочный код!";
header("Location: $mess_url#last"); exit;
}
}
if (isset($_SESSION["send"]) and $_SESSION["send"]!="") { //вывод сообщения
echo '<script type="text/javascript">alert("'.$_SESSION["send"].'");</script>';
$_SESSION["send"]="";
}
?>
<?php
// Защита сайта от частых обращений к страничке
// объявляем работу с сессиями
session_start();
// указываем папку, куда будет сохраняться информация сессий
session_save_path($_SERVER["DOCUMENT_ROOT"]."/log/session");
// устанавливаем защиту по IP (сессии) не чаще, чем раз в две секунды.
if (isset($_SESSION["telecod_ip"])) {
$t = ((int)(time()-$_SESSION["telecod_ip"]));
if ($t < 2) die("Нельзя обращаться к сайту чаще, чем 1 раз в две секунды!");
}
$_SESSION["telecod_ip"]=time();
?>
<?php
// Защита сайта от частых обращений к сайту в течении 10 раз за 10 секунд
$bot='';
$ip=$_SERVER['REMOTE_ADDR'];
if (strstr($_SERVER['HTTP_USER_AGENT'], 'Yandex')) $bot='Yandex';
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'Google')) $bot='Google';
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'Yahoo')) $bot='Yahoo';
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'Mail')) $bot='Mail';
if ($bot=='') {
$db=mysqli_connect("localhost","carthage","2104metalist1986","raschet");
$res=mysqli_query($db,"INSERT INTO all_visits (ip,date) VALUES
(INET_ATON('".$ip."'),'".time()."')");
$res=mysqli_query($db,"SELECT count(id) FROM all_visits WHERE
(ip=INET_ATON('".$ip."') and date>'".(time()-10)."') LIMIT 1");
$count_visit=mysqli_fetch_array($res);
if ($count_visit[0]>10) {
$res=mysqli_query($db,"INSERT INTO black_list_ip (ip,date) VALUES
(INET_ATON('".$ip."'),'".time()."')");
$start_line=0;
$lines='';
$ln_hta='';
$fh=fopen(".htaccess", "a+");
flock($fh, LOCK_EX);
fseek($fh, 0);
while (!feof($fh)) $lines.=fread($fh,2048);
$lines=explode("\n", $lines);
for ($n=0; $n<=count($lines); $n++) {
if (strstr($lines[$n],"Order Allow,Deny")) $start_line=$n;
}
if ($start_line!=0) for ($n=0; $n<$start_line; $n++) $ln_hta[]=$lines[$n];
else $ln_hta=$lines;
$ln_hta[]="Order Allow,Deny";
$ln_hta[]="Allow from all";
$res=mysqli_query($db,"SELECT INET_NTOA(ip) AS ip,date FROM black_list_ip
ORDER BY INET_ATON(ip)");
while ($bad_ip=mysqli_fetch_array($res)) {
if (time()<($bad_ip[date]+900))$ln_hta[]=" deny from ".$bad_ip[ip];
}
$ln_hta=implode("\n",$ln_hta);
ftruncate($fh, 0);
fwrite($fh, $ln_hta);
flock($fh, LOCK_UN);
fclose($fh);
}
}
?>
<? include ("blocks/bd.php");
/*вывод статей из БД*/
$result = mysqli_query($db,"SELECT * FROM data WHERE id='$id'");
if (!$result)/*Если в переменную результат попала ложь, то...*/
{
echo "<p>Запрос на выборку данных из базы не прошел. Напишите об этом администратору admin@raschet.info<br> <strong>Код ошибки:</strong></p>";
exit(mysqli_error());/*Останавливает выполнение всех программ и выводит код ошибки*/
}
/*проверяем кол-во переменных в БД для данной таблицы*/
if (mysqli_num_rows($result) > 0)
{
$myrow = mysqli_fetch_array($result);
$new_view = $myrow["view"] + 1;
$update = mysqli_query ($db,"UPDATE data SET view='$new_view' WHERE id='$id'");/*Cчетчик обновлении поля: Просмотров*/
}
else
{
echo "<p>Информация по запросу не может быть извлечена в таблице нет записей.</p>";
exit();/*Останавливает выполнение всех программ*/
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="img/favicon.ico" rel="SHORTCUT ICON" type="image/x-icon">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title><? echo $myrow["title"]; ?></title>
<meta name="keywords" content="<? echo $myrow["meta_k"]; ?>" />
<meta name="description" content="<? echo $myrow["meta_d"]; ?>" />
<link rel="stylesheet" href="style.css" type="text/css" />
<style type="text/css">
.add_comment {
display: table;
width: 580px;
border: 1px solid #000;
background-color: #6AF;
}
.close_hint, .open_hint {
float: right;
border: 1px solid #77A;
background: #6e6;
width: 100px;
text-align: center;
cursor: pointer;
}
.close_hint { margin: 5px; color: #F00; }
.comm_body { padding: 0 5px; background-color:#EEE; text-align:left; }
.comm_head { padding: 3px; border: 1px solid #77A; background-color: #DFD; }
.comm_minus { background: url('image/minus.png') no-repeat; }
.comm_plus { background: url('image/plus.png') no-repeat; }
.comm_minus, .comm_plus {
float: right;
width: 19px;
height: 18px;
cursor: pointer;
}
.comm_text { display:none; }
.sp_link { color: #F33; cursor: pointer; }
.strelka {
background: url(image/strelka.png) no-repeat;
border-left: 2px solid #000;
}
.strelka_2 { background: url(image/strelka_2.png) no-repeat; }
#hint { position: absolute; display: none; z-index: 100; }
</style>
</head>
<body>
<div class="wrapper">
<!-- .header-->
<!--Подключаем шапку сайта-->
<?php include ("blocks/header.php");?>
<div class="middle">
<div class="container">
<div class="content">
<!--Подключаем центральную часть сайта-->
<div class='post'>
<?php
printf ("<h1 class='post_h1'>%s</h1>
<p class='post_add1'>Раздел: %s</p>
<p>%s</p>
<p class='post_view_left1'>Просмотров: %s</p> <p class='post_view_right1'>Статья создана: %s</p>
",$myrow["title"],$myrow["author"],$myrow["text"],$myrow["view"],date("d.m.Y", strtotime($myrow['date'])));
echo "<p class='post_comment'>Поделиться:</p>
<script type='text/javascript'>(function() {
if (window.pluso)if (typeof window.pluso.start == 'function') return;
if (window.ifpluso==undefined) { window.ifpluso = 1;
var d = document, s = d.createElement('script'), g = 'getElementsByTagName';
s.type = 'text/javascript'; s.charset='UTF-8'; s.async = true;
s.src = ('https:' == window.location.protocol ? 'https' : 'http') + '://share.pluso.ru/pluso-like.js';
var h=d[g]('body')[0];
h.appendChild(s);
}})();</script>
<div class='pluso' data-background='transparent' data-options='medium,square,line,horizontal,counter,theme=08' data-services='vkontakte,odnoklassniki,facebook,twitter,google,moimir,email,print,googlebookmark'></div><hr>";
/*Вывод похожих 5 записей - Начало*/
$result5 = mysqli_query($db,"SELECT id, title FROM data WHERE cat={$myrow['cat']} AND art={$myrow['art']} AND id!={$myrow['id']} ORDER BY RAND ()LIMIT 5");
echo "<p class='post_comment'>Читать еще:</p>";
while ($myrow5 = mysqli_fetch_array($result5))
{
printf ("<div class='article_random'><li><h3><a href='view_post.php?id=%s'>%s</a></h3></li></div>",$myrow5["id"],$myrow5["title"]);
}
/*Вывод похожих 5 записей - Конец*/
echo "<hr><p class='post_comment'>Комментарии к этой заметке:</p> ";
?>
<?php
function parents($up=0, $left=0) { //Строим иерархическое дерево комментариев
global $tag,$mess_url;
for ($i=0; $i<=count($tag[$up])-1; $i++) {
//Можно выделять цветом указанные логины
if ($tag[$up][$i][2]=='Admin') $tag[$up][$i][2]='<font color="#C00">Admin</font>';
if ($tag[$up][$i][6]==0) $tag[$up][$i][6]=$tag[$up][$i][0];
//Высчитываем рейтинг комментария
$sum=$tag[$up][$i][4]-$tag[$up][$i][5];
if ($up==0) echo '<div style="padding:5px 0 0 0;">';
else {
if (count($tag[$up])-1!=$i)
echo '<div class="strelka" style="padding:5px 0 0 '.($left-2).'px;">';
else echo '<div class="strelka_2" style="padding:5px 0 0 '.$left.'px;">';
}
echo '<div class="comm_head" id="m'.$tag[$up][$i][0].'">';
echo '<div style="float:left;"><b>'.$tag[$up][$i][2].'</b></div>';
echo '<div class="comm_minus"></div>';
echo '<div style="float:right; width:30px;" id="rating_comm'.$tag[$up][$i][0].'">';
echo '<b>'.$sum.'</b></div><div class="comm_plus"></div>';
echo '<a style="float:right; width:70px;" href="'.$mess_url.'#m';
echo $tag[$up][$i][0].'"># '.$tag[$up][$i][0].'</a>';
echo '<div style="float:right; width:170px;">';
echo '('.date("H:i:s d.m.Y", $tag[$up][$i][3]).' г.)</div>';
echo '<div style="clear:both;"></div></div>';
echo '<div class="comm_body">';
if ($sum<0) echo '<u class="sp_link">Показать/скрыть</u><div class="comm_text">';
else echo '<div style="word-wrap:break-word;">';
echo str_replace("<br />","<br>",nl2br($tag[$up][$i][1])).'</div>';
echo '<div class="open_hint" onClick="comm_on('.$tag[$up][$i][0].',
'.$tag[$up][$i][6].')">Ответить</div><div style="clear:both;"></div></div>';
if (isset($tag[ $tag[$up][$i][0] ])) parents($tag[$up][$i][0],20);
echo '</div>';
}
}
$res=mysqli_query($db,"SELECT * FROM comment
WHERE theme_id='".$theme_id."' and moderation=1 ORDER BY id");
$number=mysqli_num_rows($res);
if ($number>0) {
echo '<div style="border:1px solid #000000;padding:5px;text-align:center;">';
echo '<b>Последние комментарии:</b><br>';
while ($com=mysqli_fetch_assoc($res))
$tag[(int)$com["parent_id"]][] = array((int)$com["id"], $com["message"],
$com["login"], $com["date"], $com["plus"], $com["minus"], $com["first_parent"]);
echo parents().'</div><br>';
}
?>
<?php
$cod=rand(100,900); $cod2=rand(1,99);
echo '<div id="last" align="center">';
echo '<form method="POST" action="'.$mess_url.'#last" class="add_comment"';
echo 'name="add_comment" id="hint"><div class="close_hint">Закрыть</div>';
echo '<textarea cols="68" rows="5" name="user_text"></textarea>';
echo '<div style="margin:5px; float:left;">';
echo 'Имя: <input type="text" name="mess_login" maxlength="20" value=""></div>';
echo '<div style="margin:5px; float:right;">'.$cod.' + '.$cod2.' = ';
echo '<input type="hidden" name="prov_summa" value="'.md5($cod+$cod2).'">';
echo '<input type="hidden" name="parent_id" value="0">';
echo '<input type="hidden" name="f_parent" value="0">';
echo '<input type="text" name="contr_cod" maxlength="4" size="4"> ';
echo '<input type="submit" value="Отправить"></div>';
echo '</form>';
echo '<form method="POST" action="'.$mess_url.'#last" class="add_comment">';
echo 'Добавить комментарий:';
echo '<textarea cols="68" rows="5" name="user_text"></textarea>';
echo '<div style="margin:5px; float:left;">';
echo 'Имя: <input type="text" name="mess_login" maxlength="20" value=""></div>';
echo '<div style="margin:5px; float:right;">'.$cod.' + '.$cod2.' = ';
echo '<input type="hidden" name="prov_summa" value="'.md5($cod+$cod2).'">';
echo '<input type="text" name="contr_cod" maxlength="4" size="4"> ';
echo '<input type="submit" value="Отправить"></div>';
echo '</form></div>';
?>
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
//Добавление в форму отправки комментария значений id родительских комментариев
function comm_on(p_id,first_p){
document.add_comment.parent_id.value=p_id;
document.add_comment.f_parent.value=first_p;
}
$(document).ready(function(){
//Показать скрытое под спойлером сообщение
$(".sp_link").click(function(){
$(this).parent().children(".comm_text").toggle("normal");
});
//Показать форму ответа на имеющийся комментарий
$(".open_hint").click(function(){
$("#hint").animate({
top: $(this).offset().top + 25, left: $(document).width()/2 -
$("#hint").width()/2
}, 400).fadeIn(800);
});
//Скрыть форму ответа на имеющийся комментарий
$(".close_hint").click(function(){ $("#hint").fadeOut(1200); });
//Получение id оцененного комментария
$(".comm_plus,.comm_minus").click(function(){
id_comm=$(this).parents(".comm_head").attr("id").substr(1);
});
//Отправление оценки комментария в файл rating_comm.php
$(".comm_plus").click(function(){
jQuery.post("rating_comm.php",{comm_id:id_comm,ocenka:1},rating_comm);
});
$(".comm_minus").click(function(){
jQuery.post("rating_comm.php",{comm_id:id_comm,ocenka:0},rating_comm);
});
//Возврат рейтинга комментария и его обновление
function rating_comm(data){
$("#rating_comm"+id_comm).fadeOut(800,function(){
$(this).html(data).fadeIn(800);
});
}
});
</script>
</div><!-- конец .post-->
</div><!-- .content-->
</div><!-- .container-->
<!-- .left-sidebar -->
<!--Подключаем меню навигации сайта-->
<?php include ("blocks/leftmenu.php");?>
</div>
<!-- .middle-->
<!-- .footer -->
<!--Подключаем подвал сайта-->
<?php include ("blocks/footer.php");?>
</div><!-- .wrapper -->
</body>
</html>