<?php

/**
* @package     JohnCMS
* @link        http://johncms.com
* @copyright   Copyright (C) 2008-2011 JohnCMS Community
* @license     LICENSE.txt (see attached file)
* @version     VERSION.txt (see attached file)
* @author      http://johncms.com/about
*/

/*
 by Str@nnik
 http://johncms.com/users/profile.php?user=21326
 ICQ: 609745227
*/
defined('_IN_JOHNADM') or die('Error: restricted access');

// Проверяем права доступа
if ($rights < 9) {
    header('Location: http://johncms.com/?err');
    exit;
}
// Нашел в интернете функцию скругления размера файла
function formatSize($size) {
	$filesizename = array("Bytes", "Kb", "Mb", "Gb", "Tb");
	return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i]: '0' . $filesizename[0];
}
// Функция подсветки результатов запроса
function ReplaceKeywords($search, $text)
{
    $search = str_replace('*', '', $search);
    return mb_strlen($search) < 3 ? $text : preg_replace('|(' . preg_quote($search, '/') . ')|siu', '<span style="background-color: #FFFF33">$1</span>', $text);
}

echo '<div class="phdr"><a href="index.php"><b>' . $lng['admin_panel'] . '</b></a> | Шпион почты</div>';

if (isset($_GET['delete'])) {
	mysql_query('delete from `cms_mail` where `id` = '.$id.'');
	echo '<div class="gmenu">Сообщение удалено!</div>';
}

switch ($mod) {
	case 'track':
	$total = mysql_result(mysql_query('select count(*) from `cms_mail` where `sys` = 0 and `user_id` = '.$id.';'), 0);
	if ($total) {
		$req = mysql_query('select * from `cms_mail` where `sys` = 0 and `user_id` = '.$id.' order by `time` desc;');
		$i = 0;
	    while ($res = mysql_fetch_assoc($req)) {
		    $User = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$res['user_id'].''));
		    $from = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$res['from_id'].''));
		    echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
		    echo '<b>Кто:</b> <a href="' . $home . '/users/profile.php?user=' . $User['id'] . '">' . $User['name'] . '</a><br />
		        <b>Кому:</b> <a href="' . $home . '/users/profile.php?user=' . $from['id'] . '">' . $from['name'] . '</a><br />
				<b>Время:</b> ' . functions::display_date($res['time']) . '<br />';
		    $message = functions::checkout($res['text'], 1, 1);
            if ($set_user['smileys'])
                $message = functions::smileys($message, $user['rights'] >= 1 ? 1 : 0);
		    echo '<b>Сообщение:</b> ' . $message . '<br />';
			if ($res['file_name']) {
				$size = $res['size'];
                echo '<div class="func">Файл: <a href="../mail/index.php?act=load&amp;id=' . $res['id'] . '">' . $res['file_name'] . '</a> (' . formatSize($size) . ')(' . $res['count'] . ')</div>';
			}	
		    echo '<a href="?act=spy_mail&amp;delete&amp;id='.$res['id'].'">Удалить</a>';
		    echo '</div>';
		    $i++;
		}
		if ($total > $kmess) {
            echo '<div class="topmenu">' . functions::display_pagination('index.php?act=spy_mail&amp;mod=track&amp;id='.$id.'&amp;', $start, $total, $kmess) . '</div>';
            echo '<p><form action="index.php?act=spy_mail&amp;mod=track&amp;id='.$id.'" method="post"><input type="text" name="page" size="2"/><input type="submit" value="' . $lng['to_page'] . ' &gt;&gt;"/></form></p>';
        }
	} else {
		echo '<div class="menu">Пусто</div>';
	}
	if ($total)
	echo '<div class="rmenu"><a href="?act=spy_mail&amp;mod=clean_usr&amp;id='.$id.'">Очистить почту юзера</a></div>';
	echo '<div class="menu"><a href="?act=spy_mail">К основному</a></div>';
	break;
	
	case 'search':
	if (isset($_POST['submit'])) {
	    $search = htmlspecialchars(mysql_real_escape_string(trim($_POST['search'])));
		$array = explode(' ', $search);
		
		$error = array();
		if (mb_strlen($search) < 3)
			$error[] = 'Слишком короткий запрос!';
		if (mb_strlen($search) > 40)
			$error[] = 'Слишком длинный запрос!';
		if (mb_strlen($search) == 0)
			$error[] = 'Пустой запрос!';
		if (!$error) {
			$req = mysql_query("select * from `cms_mail` where `text` like '%$search%' order by `time` desc");
			//$a = mysql_fetch_assoc($req);
			//print_r($a);
			$total = mysql_num_rows($req);
			if (mysql_num_rows($req) > 0) {
				echo '<div class="gmenu">Результаты поиска по запросу <b>'.$search.'</b></div>';
				$i = 0;
				while ($res = mysql_fetch_assoc($req)) {
					$User = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$res['user_id'].''));
					$from = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$res['from_id'].''));
					echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
					echo '<b>Кто:</b> <a href="' . $home . '/users/profile.php?user=' . $User['id'] . '">' . $User['name'] . '</a> <a href="?act=spy_mail&amp;mod=track&amp;id=' . $User['id'] . '">[#]</a><br />
						<b>Кому:</b> <a href="' . $home . '/users/profile.php?user=' . $from['id'] . '">' . $from['name'] . '</a> <a href="?act=spy_mail&amp;mod=track&amp;id=' . $from['id'] . '">[#]</a><br />
						<b>Время:</b> ' . functions::display_date($res['time']) . '<br />';
					$message = functions::checkout($res['text'], 1, 1);
					if ($set_user['smileys'])
						$message = functions::smileys($message, $user['rights'] >= 1 ? 1 : 0);
					foreach ($array as $val) {
                        $message = ReplaceKeywords($val, $message);
                    }
					echo '<b>Сообщение:</b> ' . $message . '<br />';
					if ($res['file_name']) {
						$size = $res['size'];
						echo '<div class="func">Файл: <a href="../mail/index.php?act=load&amp;id=' . $res['id'] . '">' . $res['file_name'] . '</a> (' . formatSize($size) . ')(' . $res['count'] . ')</div>';
					}	
					echo '<a href="?act=spy_mail&amp;delete&amp;id='.$res['id'].'">Удалить</a>';
					echo '</div>';
					$i++;
				}
				echo '<div class="phdr">Всего: '.$total.'</div>';
			} else {
				echo '<div class="menu">По вашему запросу ничего не найдено</div>';
			}
		} else {
			echo functions::display_error($error, '<a href="?act=spy_mail&amp;mod=search">Назад</a>');
		}
	} else {
		echo '<div class="gmenu"><form name="search" method="post" action="?act=spy_mail&amp;mod=search">
            <input type="search" name="search" placeholder="Поиск">
            <input type="submit" name="submit" value="Поиск" />
            </form></div>';
	}
	
	echo '<div class="menu"><a href="?act=spy_mail">В шпион</a></div>';
	break;
	
	case 'clean':
	if (isset($_GET['yes'])) {
		mysql_query('truncate table `cms_mail`');
		header('location: ?act=spy_mail');
	} else {
		echo '<div class="rmenu">Вы действительно желаете очистить всю почту??<br />
		        <a href="?act=spy_mail&amp;mod=clean&amp;yes">Да</a> | <a href="?act=spy_mail">Отмена</a></div>';
	}
	break;
	
	case 'clean_usr':
	$usr = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$id.';'));
	if (isset($_GET['yes'])) {
		mysql_query('delete from `cms_mail` where `sys` = 0 and `user_id` = '.$id.';');
		header('location: ?act=spy_mail');
	} else {
		echo '<div class="rmenu">Вы действительно желаете очистить всю почту '.$usr['name'].'??<br />
		        <a href="?act=spy_mail&amp;mod=clean_usr&amp;id='.$id.'&amp;yes">Да</a> | <a href="?act=spy_mail">Отмена</a></div>';
	}
	break;
	
	default:
	echo '<div class="gmenu"><a href="?act=spy_mail&amp;mod=search"><small>Поиск</small></a></div>';
	$total = mysql_result(mysql_query('select count(*) from `cms_mail` where `sys` = 0'), 0);
    if ($total){
		$req = mysql_query('select * from `cms_mail` where `sys` = 0 order by `time` desc limit ' . $start . ', ' . $kmess . ';');
	    $i = 0;
	    while ($res = mysql_fetch_assoc($req)) {
		    $User = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$res['user_id'].''));
		    $from = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$res['from_id'].''));
		    echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
		    echo '<b>Кто:</b> <a href="' . $home . '/users/profile.php?user=' . $User['id'] . '">' . $User['name'] . '</a> <a href="?act=spy_mail&amp;mod=track&amp;id=' . $User['id'] . '">[#]</a><br />
		        <b>Кому:</b> <a href="' . $home . '/users/profile.php?user=' . $from['id'] . '">' . $from['name'] . '</a> <a href="?act=spy_mail&amp;mod=track&amp;id=' . $from['id'] . '">[#]</a><br />
				<b>Время:</b> ' . functions::display_date($res['time']) . '<br />';
		    $message = functions::checkout($res['text'], 1, 1);
            if ($set_user['smileys'])
                $message = functions::smileys($message, $user['rights'] >= 1 ? 1 : 0);
		    echo '<b>Сообщение:</b> ' . $message . '<br />';
			if ($res['file_name']) {
				$size = $res['size'];
                echo '<div class="func">Файл: <a href="../mail/index.php?act=load&amp;id=' . $res['id'] . '">' . $res['file_name'] . '</a> (' . formatSize($size) . ')(' . $res['count'] . ')</div>';
			}	
		    echo '<a href="?act=spy_mail&amp;delete&amp;id='.$res['id'].'">Удалить</a>';
		    echo '</div>';
		    $i++;
	    }
		echo '<div class="rmenu"><a href="?act=spy_mail&amp;mod=clean">Очистить почту</a></div>';
    } else {
	    echo '<div class="menu">Пусто</div>';
    }
	if ($total > $kmess) {
        echo '<div class="topmenu">' . functions::display_pagination('index.php?act=spy_mail&amp;', $start, $total, $kmess) . '</div>';
        echo '<p><form action="index.php?act=spy_mail" method="post"><input type="text" name="page" size="2"/><input type="submit" value="' . $lng['to_page'] . ' &gt;&gt;"/></form></p>';
    }
	break;
}
echo '<div class="phdr"><a href="index.php">' . $lng['admin_panel'] . '</a></div>';