<?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'];


$stop_pm = FALSE;
if( isset( $_REQUEST['doaction'] ) ) $doaction = $_REQUEST['doaction'];
else $doaction = "";

if( ! $is_logged or ! $user_group[$member_id['user_group']]['allow_pm'] ) {
	msgbox( $lang['all_err_1'], $lang['pm_err_1'] );
	$stop_pm = TRUE;
}

$tpl->load_template( 'pm.tpl' );

$tpl->set( '[inbox]', "<a href=\"$PHP_SELF?do=pm&amp;doaction=inbox\">" );
$tpl->set( '[/inbox]', "</a>" );
$tpl->set( '[outbox]', "<a href=\"$PHP_SELF?do=pm&amp;doaction=outbox\">" );
$tpl->set( '[/outbox]', "</a>" );
$tpl->set( '[new_pm]', "<a href=\"$PHP_SELF?do=pm&amp;doaction=newpm\">" );
$tpl->set( '[/new_pm]', "</a>" );

$tpl->copy_template = "
    <SCRIPT LANGUAGE=\"JavaScript\">
    function confirmDelete(url){
    var agree=confirm(\"" . $lang['pm_confirm'] . "\");
    if (agree)
    document.location=url;
    }
    </SCRIPT>" . $tpl->copy_template;

if( isset( $_POST['send'] ) and ! $stop_pm ) {

	$name = $db->safesql( $parse->process( trim( $_POST['name'] ) ) );
	$subj = $db->safesql( $parse->process( trim( $_POST['subj'] ) ) );

	$stop = "";

    if( $user_group[$member_id['user_group']]['allow_url'] ) $parse->ParseFilter( Array ('div', 'a', 'span', 'p', 'br', 'strong', 'em', 'ul', 'li', 'ol' ), Array (), 0, 1 );
    else $parse->ParseFilter( Array ('div', 'span', 'p', 'br', 'strong', 'em', 'ul', 'li', 'ol' ), Array (), 0, 1 );

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

	if( empty( $name ) or $comments == "" ) $stop .= $lang['pm_err_2'];
	if ($subj == ""){$subj = "Без темы";}
	if( strlen( $subj ) > 250 ) {$stop .= $lang['pm_err_3'];}
	if( $parse->not_allowed_tags ) {$stop .= "<li>" .$lang['news_err_33']. "</li>";}
	if( $parse->not_allowed_text ) {$stop .= "<li>" . $lang['news_err_37']. "</li>";}
	
	$db->query( "SELECT email, name, user_id, pm_all, user_group, mail_lc FROM " . USERPREFIX . "_users where name = '$name'" );
	if( ! $db->num_rows() ) $stop .= $lang['pm_err_4'];
	if($name == $member_id['name']){$stop .= $lang['pm_err_10'];}
	
	$row = $db->get_row();
	$db->free();
	
	if( ! $stop ) {
		$_SESSION['sec_code_session'] = 0;
		$time = time() + ($config['date_adjust'] * 60);
        $member_id['name'] = $db->safesql($member_id['name']);
		$db->query( "INSERT INTO " . USERPREFIX . "_pm (subj, text, user, user_from, date, pm_read, folder) values ('$subj', '$comments', '{$row['user_id']}', '{$member_id['name']}', '$time', 'no', 'inbox')" );
		$db->query( "UPDATE " . USERPREFIX . "_users set pm_all=pm_all+1, pm_unread=pm_unread+1  where user_id='{$row['user_id']}'" );
		if( intval( $_REQUEST['outboxcopy'] ) ) {
			$db->query( "INSERT INTO " . USERPREFIX . "_pm (subj, text, user, user_from, date, pm_read, folder) values ('$subj', '$comments', '{$row['user_id']}', '{$member_id['name']}', '$time', 'yes', 'outbox')" );
			$db->query( "UPDATE " . USERPREFIX . "_users set pm_all=pm_all+1 where user_id='$member_id[user_id]'" );
		}
		
		$replyid = intval( $_GET['replyid'] );
		if( $replyid ) {$db->query( "UPDATE " . USERPREFIX . "_pm SET reply=1 WHERE id= '$replyid'" );}
		
		if($config['mail_pm'] AND $row['mail_lc'] != 0) {
			include_once SYSTEM_DIR . '/classes/mail.class.php';
			$mail = new dle_mail( $config );
			$mail_template = $db->super_query( "SELECT template FROM " . PREFIX . "_email WHERE name='pm' LIMIT 0,1" );
			$mail_template['template'] = stripslashes( $mail_template['template'] );
			$mail_template['template'] = str_replace( "{%username%}", $row['name'], $mail_template['template'] );
			$mail_template['template'] = str_replace( "{%date%}", langdate( "j F Y H:i", $_TIME ), $mail_template['template'] );
			$mail_template['template'] = str_replace( "{%fromusername%}", $member_id['name'], $mail_template['template'] );
			$mail_template['template'] = str_replace( "{%title%}", strip_tags( stripslashes( $subj ) ), $mail_template['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 );
			$mail_template['template'] = str_replace( "{%text%}", $body, $mail_template['template'] );
			$mail->send( $row['email'], $lang['mail_pm'], $mail_template['template'] );
		}
		msgbox( $lang['all_info'], $lang['pm_sendok'] . " <a href=\"$PHP_SELF?do=pm&amp;doaction=newpm\">" . $lang['pm_noch'] . "</a> " . $lang['pm_or'] . " <a href=\"$PHP_SELF\">" . $lang['pm_main'] . "</a><meta http-equiv=\"Refresh\" content=\"3;url=/index.php\">" );
		$stop_pm = TRUE;
	} else
		msgbox( $lang['all_err_1'], "<ul>".$stop."</ul>" );
}

if( $doaction == "del" and ! $stop_pm ) {
	$delete_count = 0;
	if( $_REQUEST['dle_allow_hash'] == "" or $_REQUEST['dle_allow_hash'] != $dle_login_hash ) {die( "Hacking attempt! User ID not valid" );	}
	if( $_GET['pmid'] ) {
		
		$pmid = intval( $_GET['pmid'] );
		$row = $db->super_query( "SELECT id, user, user_from, pm_read, folder FROM " . USERPREFIX . "_pm where id= '{$pmid}'" );
		if( ($row['user'] == $member_id['user_id'] and $row['folder'] == "inbox") or ($row['user_from'] == $member_id['name'] and $row['folder'] == "outbox") ) {
			$db->query( "DELETE FROM " . USERPREFIX . "_pm WHERE id='{$row['id']}'" );
			$delete_count ++;
			if( $row['pm_read'] != "yes" ) {$db->query( "UPDATE " . USERPREFIX . "_users set pm_unread=pm_unread-1 where user_id='{$member_id['user_id']}'" );}
			$db->query( "UPDATE " . USERPREFIX . "_users set pm_all=pm_all-1 where user_id='{$member_id['user_id']}'" );
		}
	} elseif( count( $_REQUEST['selected_pm'] ) ) {
		foreach ( $_REQUEST['selected_pm'] as $pmid ) {
			$pmid = intval( $pmid );
			$row = $db->super_query( "SELECT id, user, user_from, pm_read, folder FROM " . USERPREFIX . "_pm where id= '{$pmid}'" );
			if( ($row['user'] == $member_id['user_id'] and $row['folder'] == "inbox") or ($row['user_from'] == $member_id['name'] and $row['folder'] == "outbox") ) {
				$db->query( "DELETE FROM " . USERPREFIX . "_pm WHERE id='{$row['id']}'" );
				$delete_count ++;
				if( $row['pm_read'] != "yes" ) {$db->query( "UPDATE " . USERPREFIX . "_users set pm_unread=pm_unread-1 where user_id='{$member_id['user_id']}'" );}
				$db->query( "UPDATE " . USERPREFIX . "_users set pm_all=pm_all-1 where user_id='{$member_id['user_id']}'" );
	}}}
	if( $delete_count ) msgbox( $lang['all_info'], $lang['pm_delok'] . " <a href=\"$PHP_SELF?do=pm\">" . $lang['all_prev'] . "</a>." );
	else msgbox( $lang['all_err_1'], $lang['pm_err_5'] );
}

elseif( $doaction == "readpm" and ! $stop_pm ) {
	$pmid = intval( $_GET['pmid'] );
	$tpl->set( '[readpm]', "" );
	$tpl->set( '[/readpm]', "" );
	$tpl->set_block( "'\\[pmlist\\].*?\\[/pmlist\\]'si", "" );
	$tpl->set_block( "'\\[newpm\\].*?\\[/newpm\\]'si", "" );
	$db->query( "SELECT * FROM " . USERPREFIX . "_pm where id= '$pmid'" );
	$row = $db->get_row();
	if( $db->num_rows() < 1 ) {
		msgbox( $lang['all_err_1'], $lang['pm_err_6'] );
		$stop_pm = TRUE;
	} elseif( $row['user'] != $member_id['user_id'] and $row['user_from'] != $member_id['name'] ) {
		msgbox( $lang['all_err_1'], $lang['pm_err_7'] );
		$stop_pm = TRUE;
	} else {
		if( $row['user'] == $member_id['user_id'] and $row['pm_read'] != "yes" ) {
			$db->query( "UPDATE " . USERPREFIX . "_users set pm_unread=pm_unread-1  where user_id='{$member_id['user_id']}'" );
			$db->query( "UPDATE " . USERPREFIX . "_pm set pm_read='yes'  where id='{$row['id']}'" );
		}
		$tpl->set( '{subj}', stripslashes( $row['subj'] ) );
		$tpl->set( '{text}', stripslashes( $row['text'] ) );
		$tpl->set( '{author}', "<a href=\"" . $config['http_home_url'] . "user/" . urlencode( $row['user_from'] ) . "/\">" . $row['user_from'] . "</a>" );
		
		$tpl->set( '[reply]', "<a href=\"" . $config['http_home_url'] . "index.php?do=pm&amp;doaction=newpm&amp;replyid=" . $row['id'] . "\">" );
		$tpl->set( '[/reply]', "</a>" );
		
		$tpl->set( '[del]', "<a href=\"javascript:confirmDelete('" . $config['http_home_url'] . "index.php?do=pm&amp;doaction=del&amp;pmid=" . $row['id'] . "&amp;dle_allow_hash=" . $dle_login_hash . "')\">" );
		$tpl->set( '[/del]', "</a>" );

        $tpl->set( '[complaint]', "<a href=\"javascript:AddComplaint('" . $row['id'] . "', 'pm')\">" );
        $tpl->set( '[/complaint]', "</a>" );
		
		$tpl->compile( 'content' );
		$tpl->clear();
	}

} 
elseif( $doaction == "newpm" and ! $stop_pm ) {
	$tpl->set( '[newpm]', "" );
	$tpl->set( '[/newpm]', "" );
	$tpl->set_block( "'\\[pmlist\\].*?\\[/pmlist\\]'si", "" );
	$tpl->set_block( "'\\[readpm\\].*?\\[/readpm\\]'si", "" );
	
	$replyid = intval( $_GET['replyid'] );
	$user = intval( $_GET['user'] );
	if( isset( $_REQUEST['username'] ) ) $username = $db->safesql( strip_tags( urldecode( $_GET['username'] ) ) ); else $username = '';
	$text = "";
	if( $replyid ) {
		$row = $db->super_query( "SELECT * FROM " . USERPREFIX . "_pm where id= '$replyid'" );
		if( ($row['user'] != $member_id['user_id']) and ($row['user_from'] != $member_id['name']) ) {
			msgbox( $lang['all_err_1'], $lang['pm_err_7'] );
			$stop_pm = TRUE;
		}
		
		$text = $parse->decodeBBCodes( $row['text'], false );
		$text = "[quote]" . $text . "[/quote]\n";
		$tpl->set( '{author}', $row['user_from'] );

		if (strpos ( $row['subj'], "RE:" ) === false)
			$tpl->set( '{subj}', "RE: " . stripslashes( $row['subj'] ) );
		else
			$tpl->set( '{subj}', stripslashes( $row['subj'] ) );

		$row = $db->super_query( "SELECT pm_all, user_group FROM " . USERPREFIX . "_users WHERE name = '" . $db->safesql( $row['user_from'] ) . "'" );
	} elseif( $user or $username != "" ) {
		if( $user ) $row = $db->super_query( "SELECT name, pm_all, user_group FROM " . USERPREFIX . "_users where user_id = '$user'" );
		elseif( $username != "" ) $row = $db->super_query( "SELECT name, pm_all, user_group FROM " . USERPREFIX . "_users where name='$username'" );
		$tpl->set( '{author}', $row['name'] );
		$tpl->set( '{subj}', "" );
	} else {
		$tpl->set( '{author}', "" );
		$tpl->set( '{subj}', "" );
	}

		include_once SYSTEM_DIR . '/modules/bbcode.php';
		$tpl->set( '{editor}', $bb_code );

	$tpl->set( '{text}', $text );		

	$tpl->copy_template = "<form  method=\"post\" name=\"dle-comments-form\" id=\"dle-comments-form\" onsubmit=\"if(document.getElementById('dle-comments-form').name.value == '' || document.getElementById('dle-comments-form').comments.value == ''){alert('{$lang['comm_req_f']}');return false}\" action=\"\">\n" . $tpl->copy_template . "<input name=\"send\" type=\"hidden\" value=\"send\" /></form>";

	if( ! $stop_pm ) {
		$tpl->compile( 'content' );
		$tpl->clear();
	} else {
		$tpl->clear();
	}

} elseif( ! $stop_pm ) {
	$tpl->set( '[pmlist]', "" );
	$tpl->set( '[/pmlist]', "" );
	$tpl->set_block( "'\\[newpm\\].*?\\[/newpm\\]'si", "" );
	$tpl->set_block( "'\\[readpm\\].*?\\[/readpm\\]'si", "" );
	if( $member_id['pm_unread'] < 0 ) {$db->query( "UPDATE " . USERPREFIX . "_users SET pm_unread='0' WHERE user_id='{$member_id['user_id']}'" );	}
	$pmlist = <<<HTML
<form action="$PHP_SELF?do=pm&doaction=del" method="post" name="pmlist">
<input type="hidden" name="dle_allow_hash" value="{$dle_login_hash}" />
HTML;

// добавлено
if (isset($_REQUEST['cstart'])){$cstart = intval($_GET['cstart']);}
else{$cstart = 0;}
$config['news_number'] = '25';
if ($cstart){$cstart = $cstart - 1;$cstart = $cstart * $config['news_number'];}
// добавлено

	if ($doaction == "outbox"){
		    $lang['pm_from'] = $lang['pm_to'];
		    $sql = "SELECT id, subj, name as user_from, date, pm_read FROM " . USERPREFIX . "_pm LEFT JOIN " . USERPREFIX . "_users ON " . USERPREFIX . "_pm.user=" . USERPREFIX . "_users.user_id WHERE user_from = '{$member_id['name']}' AND folder = 'outbox' order by date desc LIMIT " . $cstart . "," . $config['news_number'];;
		    $sql_count = "SELECT COUNT(*) as count FROM " . PREFIX . "_pm WHERE user = '{$member_id['user_id']}' AND folder = 'outbox'";
		}else{
		    $sql = "SELECT id, subj, user_from, date, pm_read, reply FROM " . USERPREFIX . "_pm where user = '{$member_id['user_id']}' AND folder = 'inbox' ORDER BY date DESC LIMIT " . $cstart . "," . $config['news_number'];
		    $sql_count = "SELECT COUNT(*) as count FROM " . PREFIX . "_pm WHERE user = '{$member_id['user_id']}' AND folder = 'inbox'";
		}
	$pmlist .= "<table class=\"userstop\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td width=\"20\">&nbsp;</td><td class=\"pm_head\">" . $lang['pm_subj'] . "</td><td width=\"150\" class=\"pm_head\">" . $lang['pm_from'] . "</td><td width=\"150\" class=\"pm_head\" align=\"center\">" . $lang['pm_date'] . "</td><td width=\"50\" class=\"pm_head\" align=\"center\"><input type=\"checkbox\" name=\"master_box\" title=\"{$lang['pm_selall']}\" onclick=\"javascript:ckeck_uncheck_all()\" /></td>";
	$db->query($sql);
	$i = 0;
	while ( $row = $db->get_row() ) {
		$i ++;

        if ($user_group[$user_color[$row['user_from']]['user_group']]['colour']){
   			$group_span = $user_group[$user_color[$row['user_from']]['user_group']]['colour'];
            $user =  "<font color={$group_span}>".$row['user_from']."</font>";
   		}else{
            $user = $row['user_from'];
   		}

$user_from = "<a class=\"pm_list\" href=\"" . $config['http_home_url'] . "user/" . urlencode( $row['user_from'] ) . "/\">" . $user . "</a>";

		if( $row['pm_read'] == "yes" ) {
			$subj = "<a class=\"pm_list\" href=\"$PHP_SELF?do=pm&amp;doaction=readpm&amp;pmid=" . $row['id'] . "\">" . stripslashes( $row['subj'] ) . "</a>";
			$icon = "{THEME}/images/read.gif";
		} else {
			$subj = "<a class=\"pm_list\" href=\"$PHP_SELF?do=pm&amp;doaction=readpm&amp;pmid=" . $row['id'] . "\"><b>" . stripslashes( $row['subj'] ) . "</b></a>";
			$icon = "{THEME}/images/unread.gif";
		}
		if( $row['reply'] ) $icon = "{THEME}/images/send.gif";
		$pmlist .= "<tr><td><img src=\"{$icon}\" border=\"0\" alt=\"\" /></td><td class=\"pm_list\">{$subj}</td><td class=\"pm_list\">{$user_from}</td><td class=\"pm_list\" align=\"center\">" . langdate( "j.m.Y H:i", $row['date'] ) . "</td><td class=\"pm_list\" align=\"center\"><input name=\"selected_pm[]\" value=\"{$row['id']}\" type=\"checkbox\" /></td></tr>";
	}
	$db->free();
	
	$pmlist .= "<tr><td colspan=\"4\" align=\"right\"><input class=\"bbcodes\" type=\"submit\" value=\"{$lang['b_del']}\" /></td></tr></table></form>";
	if ($i) $tpl->set( '{pmlist}', $pmlist );
	else $tpl->set( '{pmlist}', $lang['no_message'] );
	
	$tpl->compile( 'content' );
	$tpl->clear();

// добавлено
if (!isset($view_template)){
	    $count_all = $db->super_query($sql_count);
	    $count_all = $count_all['count'];
	}else{$count_all = 0;}

	$url_page = $PHP_SELF. "?do=pm&doaction=".$doaction;

if( ! isset( $view_template ) and $count_all ) {
	$tpl->load_template('navigation.tpl');
	$no_prev = false;
	$no_next = false;

	if (isset($cstart) and $cstart != "" and $cstart > 0) // ссылка "назад"
		{
		$prev = $cstart / $config['news_number'];
		$prev_page = $url_page . "&cstart=" . $prev;
		$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<a href=\"" . $prev_page . "\" title=\"Перейти на предыдущую страницу\">\\1</a>" );
		}
	else
		{
		$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<b>\\1</b>" );
		$no_prev = TRUE;
		}

	if ($config['news_number'] > 0) // ссылка на страницы
		{
		if ($count_all > $config['news_number'])
			{
			$enpages_count = @ceil($count_all / $config['news_number']);
			$pages = "";
			$cstart = ($cstart / $config['news_number']) + 1;
			if ($enpages_count <= 8)
				{
				for ($j = 1; $j <= $enpages_count; $j ++)
					{
					if ($j != $cstart)
						{
						$pages .= "<a href=\"" . $url_page . "&cstart=" . $j . "\" title=\"Перейти на " . $j . "-ю страницу\">$j $pge</a> ";
						}
					else
						{
						$pages .= "<span>$j $pge</span> ";
						}
					}
				}
			else
				{
				$start = 1;
				$end = 8;
				$nav_prefix = "<b>---</b> ";
				if ($cstart > 0)
					{
					if ($cstart > 6)
						{
						$start = $cstart - 2;
						$end = $start + 5;
						if ($end >= $enpages_count)
							{
							$start = $enpages_count - 7;
							$end = $enpages_count - 1;
							$nav_prefix = "";
							}
						else
							{
							$nav_prefix = "<b>---</b> ";
							}
						}
					}

				if ($start >= 2)
					{
					$pages .= "<a href=\"" . $url_page . "\" title=\"Перейти на 1-ю страницу\">1 $pge</a> <b>---</b> ";
					}

				for ($j = $start; $j <= $end; $j ++)
					{
					if ($j != $cstart)
						{
						$pages .= "<a href=\"" . $url_page . "&cstart=" . $j . "\" title=\"Перейти на " . $j . "-ю страницу\">$j $pge</a> ";
						}
					else
						{
						$pages .= "<span>$j $pge</span> ";
						}
					}

				if ($cstart != $enpages_count)
					{
					$pages .= $nav_prefix . "<a href=\"" . $url_page . "&cstart={$enpages_count}\" title=\"Перейти на {$enpages_count}-ю страницу\">{$enpages_count} $pge</a>";
					}
				else
					{
					$pages .= "<span>{$enpages_count} $pge</span> ";
					}
				}
			}
		$tpl->set('{pages}', $pages);
		}

	if ($config['news_number'] < $count_all and $i < $count_all) // ссылка "вперёд"
		{
		$next_page = $i / $config['news_number'] + 1;
		$next = $url_page . '&cstart=' . $next_page;
		$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<a href=\"" . $next . "\" title=\"Перейти на следующую страницу\">\\1</a>" );
		}
	else
		{
		$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<b>\\1</b>" );
		$no_next = TRUE;
		}

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

	}}
?>