function AdminFeedBackDepartments()
{
    System::database()->Select('feedback', '');
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>Название</th><th>E-mail</th><th>Статус</th><th>Функции</th></tr>';
    while ($row = System::database()->FetchRow()) {
        $fid = SafeDB($row['id'], 11, int);
        $st = System::admin()->SpeedStatus('Вкл.', 'Выкл.', ADMIN_FILE . '?exe=feedback&a=changestatus&id=' . $fid, $row['active'] == '1');
        $func = System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=feedback&a=edit&id=' . $fid, 'images/admin/edit.png') . System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=feedback&a=delete&id=' . $fid, 'images/admin/delete.png', 'Удалить департамент?');
        $text .= '<tr>
		<td><b>' . System::admin()->Link(SafeEnv($row['name'], 255, str), ADMIN_FILE . '?exe=feedback&a=edit&id=' . $fid, 'Редактировать') . '</b></td>
		<td>' . PrintEmail($row['email']) . '</td>
		<td>' . $st . '</td>
		<td>' . $func . '</td>
		</tr>';
    }
    $text .= '</table>';
    AddTextBox('Департаменты', $text);
}
function AdminsMain()
{
    $atypes = System::database()->Select('usertypes', '');
    foreach ($atypes as $type) {
        $types[SafeDB($type['id'], 11, int)] = array('<span style="color: ' . SafeDB($type['color'], 9, str) . ';">' . SafeDB($type['name'], 255, str) . '</span>', SafeDB($type['system'], 1, bool), $type['image'] != '' ? '<img src="' . System::config('general/ranks_dir') . SafeDB($type['image'], 255, str) . '"><br>' : '');
    }
    $admins = System::database()->Select('users', "`type`='1'");
    //Подсчитываем количество главных администраторов
    $system = 0;
    for ($i = 0, $c = count($admins); $i < $c; $i++) {
        if ($types[$admins[$i]['access']][1]) {
            $system++;
        }
    }
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable"><tr><th>&nbsp;</th><th>Имя</th><th>E-mail</th><th>Группа</th><th>Посл. посещение</th><th>Посещений</th><th>Функции</th></tr>';
    foreach ($admins as $adm) {
        $id = SafeDB($adm['id'], 11, int);
        $funcs = '';
        $funcs .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=admins&a=editadmin&id=' . $id, 'images/admin/edit.png');
        if ($system > 1 || !$types[$adm['access']][1]) {
            $funcs .= System::admin()->SpeedButton('Удалить или перевести в пользователи', ADMIN_FILE . '?exe=admins&a=deladmin&id=' . $id, 'images/admin/delete.png');
        }
        $text .= '<tr>
			<td><img src="' . GetSmallestUserAvatar($id) . '"></td>
			<td><b>' . System::admin()->Link(SafeDB($adm['name'], 50, str), ADMIN_FILE . '?exe=admins&a=editadmin&id=' . $id) . '</b></td>
			<td>' . PrintEmail($adm['email']) . '</td>
			<td>' . $types[$adm['access']][2] . $types[$adm['access']][0] . '</td>
			<td>' . TimeRender($adm['lastvisit']) . '</td>
			<td>' . SafeDB($adm['visits'], 11, int) . '</td>
			<td>' . $funcs . '</td>
			</tr>';
    }
    $text .= '</table>';
    AddTextBox('Администраторы сайта (' . count($admins) . ')', $text);
}
function AdminUserMain()
{
    global $user, $editing;
    $searchm = false;
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 10, int);
    } else {
        $page = 1;
    }
    if (isset($_GET['show'])) {
        $show = $_GET['show'];
    } else {
        $show = '';
    }
    //Пользователи online
    $sonline = false;
    $onlwhere = '';
    $where = '`type`=\'2\'';
    if ($show == 'online') {
        $donline = $user->Online();
        $donline = $donline['members'];
        $onlwhere = '';
        foreach ($donline as $memb) {
            $onlwhere .= "or `id`='" . SafeDB($memb['u_id'], 11, int) . "'";
        }
        $onlwhere = substr($onlwhere, 3);
        $sonline = true;
        if (count($donline) > 0) {
            $where = "`type`='2' and ({$onlwhere})";
            $users = AdminUserGetUsers($where);
        } else {
            $users = array();
        }
        $searchm = true;
    } else {
        $users = AdminUserGetUsers();
    }
    //Поиск
    $criterion = '';
    $sstr = '';
    if (isset($_GET['criterion']) && isset($_GET['stext']) && $_GET['stext'] != '') {
        $searchm = true;
        $criterion = $_GET['criterion'];
        $sstr = SafeEnv($_GET['stext'], 255, str);
        switch ($criterion) {
            case 'nikname':
                AdminUserQueryStristrFilter($users, $sstr, 'name');
                break;
            case 'email':
                AdminUserQueryStristrFilter($users, $sstr, 'email');
                break;
            case 'rname':
                AdminUserQueryStristrFilter($users, $sstr, 'truename');
                break;
            case 'age':
                AdminUserQueryStristrFilter($users, $sstr, 'age');
                break;
            case 'city':
                AdminUserQueryStristrFilter($users, $sstr, 'city');
                break;
            case 'site':
                AdminUserQueryStristrFilter($users, $sstr, 'url');
                break;
            case 'icq':
                AdminUserQueryStristrFilter($users, $sstr, 'icq');
                break;
            case 'gmt':
                AdminUserQueryStristrFilter($users, $sstr, 'timezone');
                break;
            case 'active':
                AdminUserQueryStristrFilter($users, $sstr, 'active');
                break;
            case 'points':
                AdminUserQueryStristrFilter2($users, $sstr, 'points');
                break;
            case 'ip':
                AdminUserQueryStristrFilter($users, $sstr, 'lastip');
                break;
        }
        Audit('Пользователи: Поиск пользователей, критерий: "' . $criterion . '", запрос: "' . $sstr . '"');
    }
    $sstr = strval($sstr);
    $showd = array();
    System::site()->DataAdd($showd, 'all', 'Все пользователи', $show == '');
    System::site()->DataAdd($showd, 'online', 'Пользователи OnLine', $show == 'online');
    $searchd = array();
    System::site()->DataAdd($searchd, 'nikname', 'Ник', $criterion == 'nikname');
    System::site()->DataAdd($searchd, 'email', 'E-mail', $criterion == 'email');
    System::site()->DataAdd($searchd, 'rname', 'Настоящее имя', $criterion == 'rname');
    System::site()->DataAdd($searchd, 'age', 'Возраст', $criterion == 'age');
    System::site()->DataAdd($searchd, 'city', 'Город', $criterion == 'city');
    System::site()->DataAdd($searchd, 'site', 'Сайт', $criterion == 'site');
    System::site()->DataAdd($searchd, 'icq', 'ICQ', $criterion == 'icq');
    System::site()->DataAdd($searchd, 'gmt', 'Часовой пояс', $criterion == 'gmt');
    System::site()->DataAdd($searchd, 'active', 'Активен', $criterion == 'active');
    System::site()->DataAdd($searchd, 'points', 'Пунктов более', $criterion == 'points');
    System::site()->DataAdd($searchd, 'ip', 'IP', $criterion == 'ip');
    System::admin()->AddJS('
	SearchUsers = function(){
		var cri = "&criterion="+$("#criterion").val();
		var stext = "&stext="+$("#stext").val();
		var online = "&show="+$("#online").val();
		Admin.LoadPage("' . ADMIN_FILE . '?exe=user"+cri+stext+online, undefined, "Идёт поиск");
	}
	');
    TAddSubTitle('Главная');
    AddCenterBox('Зарегистрированные пользователи (' . count($users) . ')');
    $searchtool = '<style>.ustd td{ border: none; padding: 0; }</style>';
    $searchtool .= '<table cellspacing="0" cellpadding="0" border="0" class="cfgtable"><tr><td>' . "\n";
    $searchtool .= '<table cellspacing="0" cellpadding="0" border="0" width="100%" class="ustd">
	<tr>
	<td>Поиск: </td>
	<td>' . System::site()->Select('criterion', $searchd, false, 'id="criterion"') . '&nbsp;' . System::site()->Edit('stext', $sstr, false, 'id="stext"') . '&nbsp;' . System::site()->Select('show', $showd, false, 'id="online"') . '</td>
	<td>' . System::admin()->SpeedConfirmJs('Поиск', 'SearchUsers();', 'images/search.png', '', true) . '</td>
	</tr>
	</table>' . "\n";
    $searchtool .= '</td></tr></table>' . "\n";
    AddText($searchtool);
    SortArray($users, 'regdate', true);
    // Сортируем по дате регистрации
    if (count($users) > System::config('user/users_on_page')) {
        $navigator = new Navigation($page);
        $navigator->GenNavigationMenu($users, System::config('user/users_on_page'), ADMIN_FILE . '?exe=user' . ($searchm ? '&criterion=' . $criterion . '&stext=' . $sstr . '&show=' . $show : ''));
        $nav = true;
    } else {
        $nav = false;
        AddText('<br />');
    }
    $text = '';
    $text .= '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>Ник</th><th>E-mail</th><th>Дата региcтрации</th><th>Посл. посещение</th><th>Посещений</th><th>Пунктов</th><th>Активация</th><th>IP</th><th>Функции</th></tr>';
    foreach ($users as $row) {
        $uid = SafeDB($row['id'], 11, int);
        if ($row['active'] == '1') {
            $active = 'Да';
        } elseif ($row['active'] == '0' && $row['activate'] == '') {
            $active = 'Нет';
        } elseif ($row['active'] == '0' && $row['activate'] != '') {
            $active = 'Ожидается';
        }
        $funcs = '';
        if ($editing) {
            $funcs .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=user&a=edituser&id=' . $uid, 'images/admin/edit.png');
            $funcs .= System::admin()->SpeedButton('Удалить', ADMIN_FILE . '?exe=user&a=deluser&id=' . $uid, 'images/admin/delete.png');
            // Всё верно
        }
        $text .= '<tr>
		<td>' . ($editing ? '<b>' . System::admin()->Link(SafeDB($row['name'], 50, str), ADMIN_FILE . '?exe=user&a=edituser&id=' . $uid) . '</b>' : SafeDB($row['name'], 50, str)) . '</td>
		<td>' . PrintEmail($row['email']) . '</td>
		<td>' . TimeRender($row['regdate']) . '</td>
		<td>' . TimeRender($row['lastvisit']) . '</td>
		<td>' . SafeDB($row['visits'], 11, int) . '</td>
		<td>' . SafeDB($row['points'], 11, int) . '</td>
		<td>' . $active . '</td>
		<td>' . SafeDB($row['lastip'], 20, str) . '</td>
		<td>' . $funcs . '</td>
		</tr>';
    }
    $text .= '</table>';
    AddText($text);
    if ($nav) {
        AddNavigation();
    }
}
function AdminCommentsMain()
{
    System::admin()->AddCenterBox('Глобальная модерация комментариев');
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 10, int);
    } else {
        $page = 1;
    }
    System::admin()->AddJS('
		UpdateSelectComment = function(){
			$(".comment_check").each(function(){
				$("#comment"+$(this).val()).removeClass("commtable_selected");
			});
			$(".comment_check:checked").each(function(){
				$("#comment"+$(this).val()).addClass("commtable_selected");
			});
		};
		SelectAllComments = function(){
			$(".comment_check").each(function(){
				$(this).attr("checked", true);
			});
			UpdateSelectComment();
		};
		DeleteComments = function(){
			var del = "";
			$(".comment_check:checked").each(function(){
				del += "#"+$(this).val();
			});
			Admin.LoadPagePost("' . ADMIN_FILE . '?exe=comments&a=delete&page=' . $page . '", {delcomments: del}, "Удаление...");
		};
	');
    $commentsOnPage = 50;
    // Выбираем комментарии из всех таблиц
    $where = '';
    $posts = array();
    $comments_tables = System::database()->Select('comments');
    foreach ($comments_tables as $table) {
        $temp_posts = System::database()->Select($table['table'], $where);
        AdminConfigMarkPosts($temp_posts, $table);
        $posts = array_merge($posts, $temp_posts);
    }
    // Сортируем комментарии по дате(Новые сверху)
    SortArray($posts, 'post_date', true);
    // Добавляем постраничную навигацию
    if (count($posts) > $commentsOnPage) {
        $navigator = new Navigation($page);
        $navigator->GenNavigationMenu($posts, $commentsOnPage, ADMIN_FILE . '?exe=comments');
        $nav = true;
    } else {
        $nav = false;
        AddText('<br />');
    }
    // Шапка
    if (count($posts) == 0) {
        System::admin()->Highlight('На сайте нет комментариев.');
        return;
    } else {
        $text = '';
    }
    $text .= '<table cellspacing="0" cellpadding="0" width="90%" align="center" class="commtable_header">
	<tr>
	<th style="width: 160px;">Пользователь</th>
	<th style="width: 260px;">E-mail</th>
	<th style="width: 260px;">Сайт</th>
	<th style="width: 260px;">Дата и время</th>
	<th style="width: 70px;">IP</th>
	<th>Функции</th>
	</tr></table>';
    // Выводим комментарии
    foreach ($posts as $post) {
        $post_id = SafeDB($post['id'], 11, int);
        $object_id = SafeDB($post['object_id'], 11, int);
        $user_id = SafeDB($post['user_id'], 11, int);
        $user_name = SafeDB($post['user_name'], 255, str);
        $user_homepage = SafeDB($post['user_homepage'], 255, str);
        $user_email = SafeDB($post['user_email'], 255, str);
        $user_ip = SafeDB($post['user_ip'], 19, str);
        $post_date = TimeRender($post['post_date']);
        $post_message = SafeDB($post['post_message'], 0, str, false);
        $post_message = nl2br($post_message);
        $edit = ADMIN_FILE . '?exe=comments&a=edit&id=' . $post_id . '&table=' . $post['_table'] . '&page=' . $page;
        if ($user_id != 0) {
            $userinfo = GetUserInfo($user_id);
            $user_name = $userinfo['name'];
            $user_homepage = $userinfo['url'];
            $user_email = PrintEmail($userinfo['email']);
            if ($userinfo['online']) {
                $online = '<b>Сейчас на сайте.</b>';
            } else {
                $online = '';
            }
            $avatar = '<img src="' . $userinfo['avatar_file'] . '" />';
            $rank_image = '<img src="' . $userinfo['rank_image'] . '" />';
            $rank_name = $userinfo['rank_name'];
            $regdate = 'Зарегистрирован: ' . TimeRender($userinfo['regdate'], false);
            $ruser = true;
        } else {
            $user_email = PrintEmail($user_email);
            $online = '';
            $avatar = '<img src="' . GetPersonalAvatar(0) . '" />';
            $rank_image = '';
            $rank_name = '';
            $regdate = '';
            $ruser = false;
        }
        if ($user_homepage != '') {
            $user_homepage = '<a href="http://' . $user_homepage . '" target="_blank">' . $user_homepage . '</a>';
        } else {
            $user_homepage = '&nbsp;';
        }
        if ($ruser) {
            $user_name = '<a href="' . Ufu("index.php?name=user&op=userinfo&user={$user_id}", 'user/{user}/info/') . '" target="_blank">' . $user_name . '</a>';
        }
        $link_go = ADMIN_FILE . '?exe=comments&a=find&table=' . SafeDB($post['_id'], 11, int) . '&post_id=' . $post_id;
        $func = '';
        if ($post['_url'] != '') {
            $func .= System::admin()->SpeedButton('Найти комментарий', $link_go, 'images/search.png', false, false, 'target="_blank"');
        }
        $func .= SpeedButton('Редактировать', $edit, 'images/admin/edit.png');
        $text .= Indent('
			<table cellspacing="0" cellpadding="0" width="90%" align="center" class="commtable" id="comment' . $post_id . '--' . $post['_table'] . '--' . $object_id . '">
				<tr>
					<th style="width: 160px;"><b>' . $user_name . '</b></th>
					<th style="width: 260px;">' . $user_email . '</th>
					<th style="width: 260px;">' . $user_homepage . '</th>
					<th style="width: 260px;">' . $post_date . '</th>
					<th style="width: 70px;">' . $user_ip . '</th>
					<th>' . $func . '</th>
					<th>' . System::admin()->Check('delcomments[]', $post_id . '--' . $post['_table'] . '--' . $object_id, false, 'class="comment_check" onchange="UpdateSelectComment();"') . '</th>
				</tr>
				<tr>
					<td valign="top" width="140">' . $avatar . '<br>' . $rank_image . '<br>' . $rank_name . '</td>
					<td colspan="6" class="commtable_text">' . $post_message . '</td>
				</tr>
			</table>
		');
    }
    // Подвал
    AddText($text);
    if ($nav) {
        AddNavigation();
    }
    $text = '';
    if (count($posts) > 0) {
        $text .= '<div style="text-align: right;">' . System::admin()->SpeedConfirmJs('Выделить все', 'SelectAllComments();', '', '', true) . '&nbsp;' . System::admin()->SpeedConfirmJs('Удалить выделенные', 'DeleteComments();', 'images/admin/delete.png', 'Удалить выделенные комментарии?', true) . '</div>';
    }
    AddText($text);
}
function AdminMailList()
{
    if (!isset($_GET['topic_id'])) {
        GO(ADMIN_FILE . '?exe=mail');
    }
    $topic_id = SafeEnv($_GET['topic_id'], 11, int);
    System::database()->Select('mail_topics', "`id`='{$topic_id}'");
    if (System::database()->NumRows() == 0) {
        AddTextBox("Внимание!", 'Тема не найдена.');
        return;
    }
    $topic = System::database()->FetchRow();
    System::database()->Select('mail_list', "`topic_id`='{$topic_id}'");
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>E-mail</th><th>Пользователь</th><th>Формат</th><th>Функции</th></tr>';
    $c_all = 0;
    $c_users = 0;
    $c_html = 0;
    while ($row = System::database()->FetchRow()) {
        $c_all++;
        if ($row['user_id'] == '0') {
            $isuser = 'Нет';
        } else {
            $isuser = 'Да';
            $c_users++;
        }
        if ($row['html'] == '0') {
            $html = 'Текст';
        } else {
            $html = 'HTML';
            $c_html++;
        }
        $func = '';
        $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=mail&a=delete_email&topic_id=' . SafeDB($row['topic_id'], 11, int) . '&email=' . SafeDB($row['email'], 50, str) . '&ok=0', 'images/admin/delete.png', 'Удалить подписчика?');
        $text .= '<tr><td>' . PrintEmail($row['email']) . '</a></td><td>' . $isuser . '</td><td>' . $html . '</td><td>' . $func . '</td></tr>';
    }
    $text .= '<tr><td>' . $c_all . '</a></td><td>' . $c_users . '</td><td>' . $c_html . '</td><td>&nbsp;</td></tr>';
    $text .= '</table>';
    AddCenterBox('Список подписчиков на рассылку "' . SafeDB($topic['title'], 250, str) . '"');
    AddText($text);
    $format = array();
    System::admin()->DataAdd($format, '1', 'HTML');
    System::admin()->DataAdd($format, '0', 'Текст');
    System::admin()->FormTitleRow('Добавить E-mail');
    System::admin()->FormRow('E-mail', System::admin()->Edit('email', '', false, 'style="width: 260px;"'));
    System::admin()->FormRow('Формат рассылки', System::admin()->Select('html', $format));
    System::admin()->AddForm('<form action="' . ADMIN_FILE . '?exe=mail&a=add_email&topic_id=' . $topic_id . '" method="post">', System::admin()->Submit('Добавить'));
}
function AdminGuestBookPremoderationMain()
{
    System::admin()->AddCenterBox('Премодерация');
    $premoderation = System::user()->CheckAccess2('guestbook', 'premoderation');
    $premoderate = System::database()->Select('guestbook', "`premoderate`='0'");
    if (System::database()->NumRows() == 0) {
        System::admin()->Highlight('В премодерации нет сообщений.');
        return;
    }
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 10, int);
    } else {
        $page = 1;
    }
    SortArray($premoderate, 'date', true);
    $num = System::config('gb/msgonpage');
    if (count($premoderate) > $num) {
        $navigator = new Navigation($page);
        $navigator->GenNavigationMenu($premoderate, $num, ADMIN_FILE . '?exe=guestbook&a=premoderation');
        $nav = true;
    } else {
        $nav = false;
    }
    $text = '';
    $back = SaveRefererUrl();
    foreach ($premoderate as $pre) {
        if ($pre['url'] == '') {
            $url = 'Нет';
        } else {
            $url = '<a href="http://' . SafeDB($pre['url'], 250, str) . '" target="_blank">' . SafeDB($pre['url'], 250, str) . '</a>';
        }
        if ($pre['email'] == '') {
            $name = SafeDB($pre['name'], 50, str);
        } else {
            $name = PrintEmail($pre['email'], $pre['name']);
        }
        $mid = SafeDB($pre['id'], 11, int);
        $del = System::admin()->SpeedConfirm('Удалить сообщение', ADMIN_FILE . '?exe=guestbook&a=delete&id=' . $mid . '&back=' . $back, 'images/admin/delete.png', 'Удалить сообщение?');
        $func2 = '';
        $func2 = System::admin()->Link('Разрешить', ADMIN_FILE . '?exe=guestbook&a=prem_yes&id=' . $mid . '&back=' . $back);
        $text .= '<table cellspacing="0" cellpadding="0" class="commtable" style="width:75%;">';
        $text .= '<tr>
			<th style="text-align: left; width: 180px;">' . $name . '</th>
			<th style="width: 160px;">Сайт: ' . $url . '</th>
			<th style="width: 120px;">ICQ: ' . SafeDB($pre['icq'], 15, str) . '</th>
			<th style="width: 120px;">IP: ' . SafeDB($pre['user_ip'], 20, str) . '</th>
			<th> ' . $del . ' </th>
		</tr>';
        $text .= '<tr><td colspan="5" style="text-align:left;padding:10px;" class="commtable_text">' . SafeDB($pre['message'], 0, str) . '</td></tr>';
        $text .= '<tr><th>Дата: ' . TimeRender($pre['date']) . '</th><th colspan="4" style="text-align:right;">' . $func2 . '</th></tr>';
        $text .= '</table>';
    }
    AddText($text);
    if ($nav) {
        AddNavigation();
    }
    AddText('<div style="text-align: center;">' . System::admin()->SpeedConfirm('Разрешить все', ADMIN_FILE . '?exe=guestbook&a=prem_yes_all&back=' . $back, 'images/admin/accept.png', 'Разрешить все сообщения?', true, true) . '&nbsp;' . System::admin()->SpeedConfirm('Удалить все', ADMIN_FILE . '?exe=guestbook&a=prem_del_all&back=' . $back, 'images/admin/delete.png', 'Удалить все сообщения?', true, true) . '</div>');
}