<?php
if( ! defined( 'DATALIFEENGINE' )) {die( "Hacking attempt!" );}

require_once SYSTEM_DIR . '/classes/parse.class.php';

$parse = new ParseFilter( );
$parse->safe_mode = true;
$parse->allow_url = $user_group[$member_id['user_group']]['allow_url'];
$parse->allow_image = $user_group[$member_id['user_group']]['allow_image'];

$_TIME = time() + ($config['date_adjust'] * 60);
$_IP = $db->safesql( $_SERVER['REMOTE_ADDR'] );

$post_id = intval( $_POST['post_id'] );
$stop = array ();

if( $is_logged ) {
    $name = $db->safesql($member_id['name']);
    $mail = $db->safesql($member_id['email']);
} else {
    $name = $db->safesql( $parse->process( trim( $_POST['name'] ) ) );
    $mail = $db->safesql( $parse->process( trim( $_POST['mail'] ) ) );
}

$comments = $parse->BB_Parse( $parse->process( trim($_POST['comments'] )), false );

if( $is_logged and ($member_id['restricted'] == 2 or $member_id['restricted'] == 3) ) {
	$stop[] = $lang['news_info_3'];
	$CN_HALT = TRUE;
}

if( ! $post_id ) {
	$stop[] = $lang['news_err_id'];
	$CN_HALT = TRUE;
}

//максимальное количество символов в комменте
if( strlen( $comments ) > $config['comments_maxlen'] ) {
	$stop[] = $lang['news_err_3'];
	$CN_HALT = TRUE;
}

//минимальное количество символов
$comments1 = preg_replace("/ /i", "", $comments); // режем пробелы, чтобы они не учитывались
if( strlen(trim(strip_tags($comments1))) < 3){ // режем теги картинок, смайлов, оставляем тока текст и если он меньше 10 символов, то ...
$stop[] = $lang['news_err_0']; // $lang['news_err_0'] - типа ругань всякая
$CN_HALT = TRUE;
}
//!

preg_match_all( '/<!--smile:(.*?)<!--\/smile-->/is' , $comments , $smilies_in_msg );
if( count($smilies_in_msg[0]) > 7 ){  // Максимум 7 смайлов
    $stop[] = "Ошибка! Сообщение содержит недопустимое количество смайлов.";
    $CN_HALT = TRUE;
}

if( $comments == '' ) {
	$stop[] = $lang['news_err_11'];
	$CN_HALT = TRUE;
}

if( $parse->not_allowed_tags ) {
	$stop[] = $lang['news_err_33'];
	$CN_HALT = TRUE;
}

if( $parse->not_allowed_text ) {
	$stop[] = $lang['news_err_37'];
	$CN_HALT = TRUE;
}

// Проверка на правильность новости
$row = $db->super_query( "SELECT id, date, allow_comm, approve, access from " . PREFIX . "_post WHERE id='$post_id'" );
$options = news_permission( $row['access'] );
if( (! $user_group[$member_id['user_group']]['allow_addc'] and $options[$member_id['user_group']] != 2) or $options[$member_id['user_group']] == 1 ) die( "Hacking attempt!" );

if( ! $row['id'] or ! $row['allow_comm'] or ! $row['approve'] ) {
	$stop[] = $lang['news_err_29'];
	$CN_HALT = TRUE;
}

//* Автоперенос длинных слов
if( intval( $config['auto_wrap'] ) ) {
	$comments = preg_split( '((>)|(<))', $comments, - 1, PREG_SPLIT_DELIM_CAPTURE );
	$n = count( $comments );
	for($i = 0; $i < $n; $i ++) {
		if( $comments[$i] == "<" ) {
			$i ++;
			continue;
		}$comments[$i] = preg_replace( "#([^\s\n\r]{" . intval( $config['auto_wrap'] ) . "})#i", "\\1<br />", $comments[$i] );
	}$comments = join( "", $comments );
}

$time = date( "Y-m-d H:i:s", $_TIME );

// Добавление комментария
if( $CN_HALT ) {
	msgbox( $lang['all_err_1'], implode( "<br />", $stop ) . "<br /><br /><a href=\"javascript:history.go(-1)\">" . $lang['all_prev'] . "</a>" );
} else {
	$update_comments = false;
	$row = $db->super_query( "SELECT id, post_id, user_id, date, text, ip, is_register FROM " . PREFIX . "_comments WHERE post_id = '$post_id' ORDER BY id DESC LIMIT 0,1" );
		if( $row['id'] ) {
			if( $row['user_id'] == $member_id['user_id'] and $row['is_register'] ) $update_comments = true;
			elseif( $row['ip'] == $_IP and ! $row['is_register'] and ! $is_logged ) $update_comments = true;
			
            /*$row['date'] = strtotime( $row['date'] );
   			if( date( "Y-m-d", $row['date'] ) != date( "Y-m-d", $_TIME ) ) $update_comments = false;*/
			
			if( ((strlen( $row['text'] ) + strlen( $comments )) > $config['comments_maxlen']) and $update_comments ) {
				$update_comments = false;
				$stop[] = $lang['news_err_3'];
				$CN_HALT = TRUE;
				msgbox( $lang['all_err_1'], implode( "<br />", $stop ) . "<br /><br /><a href=\"javascript:history.go(-1)\">" . $lang['all_prev'] . "</a>" );
			}
		}

	if( ! $CN_HALT ) {
		if( $update_comments ) {
			$comments = $db->safesql( $row['text'] ) . "<br /><br />" . $db->safesql( $comments );
			$db->query( "UPDATE " . PREFIX . "_comments set date='$time', text='{$comments}' WHERE id='{$row['id']}'" );
		} else {
            $comments =	$db->safesql( $comments );
			$db->query( "INSERT INTO " . PREFIX . "_comments (post_id, user_id, date, autor, email, text, ip, is_register) values ('$post_id', '$member_id[user_id]', '$time', '$name', '$mail', '$comments', '$_IP', '1')" );
			$db->query( "UPDATE " . PREFIX . "_post set comm_num=comm_num+1 where id='$post_id'" );
			$db->query( "UPDATE " . USERPREFIX . "_users set comm_num=comm_num+1 where user_id ='$member_id[user_id]'" );
		}
		

			include_once SYSTEM_DIR . '/classes/mail.class.php';
			$mail = new dle_mail( $config );
			
			$row = $db->super_query( "SELECT template FROM " . PREFIX . "_email WHERE name='comments' LIMIT 0,1" );

			$row['template'] = stripslashes( $row['template'] );
			$row['template'] = str_replace( "{%username%}", $name, $row['template'] );
			$row['template'] = str_replace( "{%date%}", langdate( "j F Y H:i", $_TIME ), $row['template'] );

            $row1 = $db->super_query( "SELECT id, alt_name FROM " . PREFIX . "_post WHERE id='$post_id' LIMIT 0,1" );
            $link = $config['http_home_url'] . $row1['id'] . '-' . $row1['alt_name'] . '.html#comment';
            $row['template'] = str_replace( "{%link%}", $link, $row['template'] );


			$body = str_replace( '\n', "", $comments );
			$body = str_replace( '\r', "", $body );
			
			$body = stripslashes( stripslashes( $body ) );
			$body = str_replace( "<br />", "\n", $body );
			$body = strip_tags( $body );
			
			$row['template'] = str_replace( "{%text%}", $body, $row['template'] );

			$row['template'] = str_replace( "{%ip%}", "--", $row['template'] );
			$found_subscribe = false;

			$db->query( "SELECT user_id, name, email, hash FROM " . PREFIX . "_subscribe WHERE news_id='{$post_id}'" );

			while($rec = $db->get_row())
			{
				if ($rec['user_id'] != $member_id['user_id'] ) {
					$body = str_replace( "{%username_to%}", $rec['name'], $row['template'] );
					$body = str_replace( "{%unsubscribe%}", $config['http_home_url'] . "index.php?do=unsubscribe&post_id=" . $post_id . "&user_id=" . $rec['user_id'] . "&hash=" . $rec['hash'], $body );
					$mail->send( $rec['email'], $lang['mail_comments'], $body );
				} else {
					$found_subscribe = true;
				}}
			$db->free();

			if ($_POST['allow_subscribe'] AND !$found_subscribe) {
				$salt = "abchefghjkmnpqrstuvwxyz0123456789";
				srand( ( double ) microtime() * 1000000 );
				$s_hash = "";
				for($i = 0; $i < 5; $i ++) {$s_hash .= $salt{rand( 0, 33 )};}
				$s_hash = md5($s_hash);

				$db->query( "INSERT INTO " . PREFIX . "_subscribe (user_id, name, email, news_id, hash) values ('{$member_id['user_id']}', '{$member_id['name']}', '{$member_id['email']}', '{$post_id}', '{$s_hash}')" );
			}
		
        $cache->clear( array( 'full_'.$post_id, 'news_', 'comm_'.$post_id, 'comments-last') );
		
		if( ! $ajax_adds AND ! $CN_HALT ) {
			header( "Location: {$_SERVER['REQUEST_URI']}" );
			die();
		}
	
	} else
		msgbox( $lang['all_err_1'], implode( "<br />", $stop ) . "<br /><br /><a href=\"javascript:history.go(-1)\">" . $lang['all_prev'] . "</a>" );

}
?>