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

class Comments {
	var $db = false;
    var $query = false;
    var $nid = false;
    var $cstart = 0;
    var $CountCom = 0;
    var $LimitCom = 0;
    var $AllowCom = false;
    private $Row = array();    

    public function EchoInfo($title, $info){
        global $tpl;
        $tpl->Load_Template( 'comments/info.tpl' );
        $tpl->set( "{title}", stripslashes( $title ) );
        $tpl->set( "{error}", stripslashes( $info ) );
        $tpl->copy_template = "<span id=\"dle-ajax-comments\">".$tpl->copy_template."</span>";
        $tpl->compile( "content" );
        $tpl->clear();
    }

    function Comments( $db, $total_comments, $comments_per_pages ) {
        global $allow_comments;

        $this->db = $db;
        $this->CountCom = $total_comments;
        $this->LimitCom = $comments_per_pages;
        $this->AllowCom = $allow_comments;

        if ( isset( $_GET['cstart'] ) ) $this->cstart = intval( $_GET['cstart'] ); else $this->cstart = 0;
        if( $this->cstart > 0) {
            $this->cstart = $this->cstart - 1;
            $this->cstart = $this->cstart * $comments_per_pages;
        } else $this->cstart = 0;
    }

    //Отображение комментариев
	function build_comments($area, $allow_cache = false ) {
		global $config, $tpl, $cache, $user_group, $member_id;

        if($this->CountCom > 0){
            $rows = false;
            if($allow_cache) $rows = $cache->open( "comm_".$allow_cache, $this->query . " LIMIT " . $this->cstart . "," . $this->LimitCom );

            if($rows){ $rows = unserialize($rows);
            } else {
                $rows = $this->db->super_query(  $this->query . " LIMIT " . $this->cstart . "," . $this->LimitCom, true );
                if($allow_cache) $cache->save( "comm_".$allow_cache, serialize($rows), $this->query . " LIMIT " . $this->cstart . "," . $this->LimitCom );
            }

            if(count ($rows)) foreach ($rows as $row){
                $this->Row[ $row['id'] ] = $row;
                $this->Echo_Comm($row['id']);
            }

        } elseif ($user_group[$member_id['user_group']]['allow_addc'] && $this->AllowCom){
            $this->EchoInfo("Комментарии отсутствуют", "Но вы можете добавить первый....");
        }

		if ($area != 'ajax' AND $config['comm_msort'] == "ASC") $tpl->result['content'] .= "\n<div id=\"dle-ajax-comments\"></div>\n";
	}

    private function Echo_Comm($id){
        global $config, $tpl, $is_logged, $member_id, $user_group, $lang, $dle_login_hash, $_TIME;

        $row = $this->Row[ $id ];
        $id = $row['id'];

        $tpl->Load_Template( 'comments/comments.tpl' );
        $tpl->copy_template = "<div id='comment-id-$id'>" . $tpl->copy_template . "</div>";
        $tpl->template = "<div id='comment-id-$id'>" . $tpl->template . "</div>";

        $UserName = stripslashes( $row['name'] );
        $date = strtotime( $row['date'] );
        $ComAutor = htmlspecialchars( stripslashes( $row['gast_name'] ) );
        $text = stripslashes( $row['text'] );
        $is_register = intval( $row['is_register'] );
        $UserFoto = stripslashes( $row['foto'] );

        //Цвет пользовательской группы (пользователя)
        if ($user_group[$row['user_group']]['colour']){
            $group_span = $user_group[$row['user_group']]['colour'];
            $user =  "<font color={$group_span}>".$UserName."</font>";
        }else{
            $user = $UserName;
        }

        //Ссылка на автора комментария
        if( !$is_register || $UserName == '' ) {
            $tpl->set( '{author}', $ComAutor );
        } else {
            $tpl->set( '{author}', "<a href=\"" . $config['http_home_url'] . "user/" . urlencode( $row['name'] ) . "/\">{$user}</a>" );
        }

        //Дата добавления комментария
        if( date( Ymd, $date ) == date( Ymd, $_TIME ) )
            $tpl->set( "{date}", $lang['time_heute'].langdate( ", H:i", $date ) );
        elseif( date( Ymd, $date ) == date( Ymd, ($_TIME - 86400) ) )
            $tpl->set( "{date}", $lang['time_gestern'].langdate( ", H:i", $date ));
        else
            $tpl->set( "{date}", langdate( $config['timestamp_comment'], $date ) );

        //Ссылка на новость
        if(!$this->nid){
            $link = $config['http_home_url'] . $row['post_id'] . "-" . $row['alt_name'] . ".html";
            $tpl->set_block( "'\[news](.*?)\[/news\]'si", "<a href=\"$link\">".$row['title']."</a>" );
        } else {            
            $tpl->set( "[news]", "" );
            $tpl->set( "[/news]", "" );
        }

        //Ссылка на комментарий
        $tpl->set( '[com-href]', "<a class=\"comm-link\" href=\"#comment\">");
        $tpl->set( '[/com-href]', "</a>");

        // Аватар пользователя
        if( $UserFoto ) $tpl->set( '{foto}', "<img class=\"avatar\" src=\"" . $config['http_home_url'] . "uploads/fotos/" . $row['foto'] . "\"/>" );
        else $tpl->set( '{foto}', "<img class=\"avatar\" src=\"" . $config['http_home_url'] . 'templates/' . $config['skin'] . "/images/noavatar.png\"/>" );

        if ( ($row['lastdate'] + $config['user_online']*60) > $_TIME ) $tpl->set('{status}', "<font color=\"green\">Online</font>");
        else $tpl->set('{status}', "<font color=\"red\">Offline</font>");

        if( $is_logged and ($member_id['name'] == $ComAutor) )$tpl->set('{rate}',CommRating ($row['id'], $row['rating'], 0));
        else $tpl->set('{rate}',CommRating ($row['id'], $row['rating'], $user_group[$member_id['user_group']]['allow_rating']));

        @include (SYSTEM_DIR.'/modules/reputation.php');

        if( $is_logged && ( ( $member_id['name'] == $UserName && $is_register && $user_group[$member_id['user_group']]['allow_editc']) or $user_group[$member_id['user_group']]['edit_allc']) ) {
            $tpl->set( '[com-edit]', "<a onclick=\"return ajax_comm_edit('" . $row['id'] . "', '" . $area . "')\" return false; href=\"#\">" );
            $tpl->set( '[/com-edit]', "</a>" );
        } else $tpl->set_block( "'\\[com-edit\\](.*?)\\[/com-edit\\]'si", "" );

        if( $is_logged && (($member_id['name'] == $UserName && $is_register && $user_group[$member_id['user_group']]['allow_delc']) or $member_id['user_group'] == '1' or $user_group[$member_id['user_group']]['del_allc']) ) {
            $tpl->set('[com-del]',"<a href=\"javascript:commentdelete('{$row['id']}', '{$dle_login_hash}');\">");
            $tpl->set('[/com-del]',"</a>");
        }else $tpl->set_block("'\\[com-del\\](.*?)\\[/com-del\\]'si","");

        if( ($user_group[$member_id['user_group']]['allow_addc'])) {
            if( !$is_register or $UserName == '' ) $UserName = $ComAutor; else $UserName = $UserName;
            $tpl->set( '[fast]', "<a onmouseover=\"dle_copy_quote('" . str_replace( array (" ", "&#039;" ), array ("&nbsp;", "&amp;#039;" ), $UserName ) . "');\" href=\"#\" onclick=\"dle_ins('" . str_replace( array (" ", "&#039;" ), array ("&nbsp;", "&amp;#039;" ), $UserName ) . "'); return false;\">" );
            $tpl->set( '[/fast]', "</a>" );
        } else $tpl->set_block( "'\\[fast\\](.*?)\\[/fast\\]'si", "" );

        if( $user_group[$member_id['user_group']]['allow_hide'] ) $text = str_ireplace( "[hide]", "", str_ireplace( "[/hide]", "", $text) );
        else $text = preg_replace ( "#\[hide\](.+?)\[/hide\]#is", "<div class=\"quote\">" . $lang['news_regus'] . "</div>", $text );

        $tpl->set( "{comment-id}", $id );
        $tpl->set( "{comment}", "<div id=\"comm-id-{$id}\">{$text}</div>" );

        $tpl->compile( "content" );
        $tpl->clear();
    }

    //Навигация
	function build_navigation( $template, $alternative_link, $link ) {
		global $tpl, $config, $lang;

		if( $this->CountCom < $this->LimitCom ) return;

		if( isset( $_GET['cstart'] ) ) $this->cstart = intval( $_GET['cstart'] );
		if( !$this->cstart OR $this->cstart < 0 ) $this->cstart = 1;

		$tpl->load_template( $template );

		if( $this->cstart > 1 ) {
			$prev = $this->cstart - 1;

			if( $alternative_link ) {
				$url = str_replace ("{page}", $prev, $alternative_link );
				$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<a href=\"" . $url . "\">\\1</a>" );
			} else $tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<a href=\"$PHP_SELF?cstart=" . $prev . "&amp;{$link}#comment\">\\1</a>" );
		
		} else {
			$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<span>\\1</span>" );
			$no_prev = TRUE;
		}

		if( $this->LimitCom ) {
			$enpages_count = @ceil( $this->CountCom / $this->LimitCom );
			$pages = "";
			if( $enpages_count <= 10 ) {
				for($j = 1; $j <= $enpages_count; $j ++) {
					if( $j != $this->cstart  ) {
						if( $alternative_link ) {
							$url = str_replace ("{page}", $j, $alternative_link );
							$pages .= "<a href=\"" . $url . "\">$j</a> ";
						} else $pages .= "<a href=\"$PHP_SELF?cstart=$j&amp;{$link}#comment\">$j</a> ";
					} else {$pages .= "<span>$j</span> ";}
			}} else {
				$start = 1;
				$end = 10;
				$nav_prefix = "<span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
				if( $this->cstart  > 0 ) {
					if( $this->cstart  > 6 ) {
						$start = $this->cstart  - 4;
						$end = $start + 8;
						if( $end >= $enpages_count ) {
							$start = $enpages_count - 9;
							$end = $enpages_count - 1;
							$nav_prefix = "";
						} else $nav_prefix = "<span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
				}}
				if( $start >= 2 ) {
					if($alternative_link) {
						$url = str_replace ("{page}", "1", $alternative_link );
						$pages .= "<a href=\"" . $url . "\">1</a> <span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
					} else $pages .= "<a href=\"$PHP_SELF?cstart=1&amp;{$link}#comment\">1</a> <span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
				}

				for($j = $start; $j <= $end; $j ++) {
					if( $j != $this->cstart ) {
						if( $alternative_link) {
							$url = str_replace ("{page}", $j, $alternative_link );
							$pages .= "<a href=\"" . $url . "\">$j</a> ";
						} else $pages .= "<a href=\"$PHP_SELF?cstart=$j&amp;{$link}#comment\">$j</a> ";
					} else {$pages .= "<span>$j</span> ";
				}}

				if( $this->cstart != $enpages_count ) {
					if($alternative_link) {
						$url = str_replace ("{page}", $enpages_count, $alternative_link );
						$pages .= $nav_prefix . "<a href=\"" . $url . "\">{$enpages_count}</a>";
					} else $pages .= $nav_prefix . "<a href=\"$PHP_SELF?cstart={$enpages_count}&amp;{$link}#comment\">{$enpages_count}</a>";
				} else $pages .= "<span>{$enpages_count}</span> ";
			}$tpl->set( '{pages}', $pages );
		}

		if( $this->cstart < $enpages_count ) {
			$next_page = $this->cstart + 1;
			if( $alternative_link ) {
				$url = str_replace ("{page}", $next_page, $alternative_link );
				$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<a href=\"" . $url . "\">\\1</a>" );
			} else $tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<a href=\"$PHP_SELF?cstart=$next_page&amp;{$link}#comment\">\\1</a>" );
		} else {
			$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<span>\\1</span>" );
			$no_next = TRUE;
		}

		if( ! $no_prev or ! $no_next ) {$tpl->compile( 'content' );}

		$tpl->clear();
}

    //Показываем форму добавления коомента
    function build_comm_form(){
        global $allow_add, $tpl, $is_logged, $user_group, $member_id, $lang, $bb_code, $news_id;
        if($this->AllowCom){
            if($user_group[$member_id['user_group']]['allow_addc'] && $allow_add){
                if(!$this->CountCom) $tpl->result['content'] .= "\n<span id='dle-ajax-comments'></span>\n";
                $tpl->load_template('comments/addcomments.tpl');
                include_once SYSTEM_DIR . '/modules/bbcode.php';

                $tpl->set( '{editor}', $bb_code );
                $tpl->set( '{text}', '' );
                $tpl->set( '{title}', $lang['news_addcom'] );

                if( ! $is_logged ) {
                    $tpl->set( '[not-logged]', '' );
                    $tpl->set( '[/not-logged]', '' );
                } else $tpl->set_block( "'\\[not-logged\\](.*?)\\[/not-logged\\]'si", "" );

                if( $is_logged ) $hidden = "<input type=\"hidden\" name=\"name\" id=\"name\" value=\"{$member_id['name']}\" /><input type=\"hidden\" name=\"mail\" id=\"mail\" value=\"\" />";
                else $hidden = "";

                $tpl->copy_template = "<form  method=\"post\" name=\"dle-comments-form\" id=\"dle-comments-form\" action=\"{$_SESSION['referrer']}\">" . $tpl->copy_template . "
		        <input type=\"hidden\" name=\"subaction\" value=\"addcomment\" />{$hidden}
		        <input type=\"hidden\" name=\"post_id\" id=\"post_id\" value=\"$news_id\" /></form>";

                $tpl->compile( 'content' );
                $tpl->clear();
            } else $this->EchoInfo($lang['all_info'], "Только <b>Зарегистрированные</b> пользователи могут оставлять комментарии.");
        } else $this->EchoInfo($lang['all_info'], "Комментирвание новости отключено.");
    }
}
?>