function AdminCacheMain()
{
    AddCenterBox('Очистка кэша');
    if (!System::cache()->Enabled) {
        if (USE_CACHE) {
            System::admin()->HighlightError('<strong style="color: #FF0000;">Внимание!</strong> Папка "' . System::cache()->Path . '" не доступна для записи. Функция кэширования отключена.');
        } else {
            System::admin()->HighlightError('<strong style="color: #FF0000;">Внимание!</strong> Функция кэширования отключена в конфигурационном файле "config/config.php".');
        }
    }
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>Группа</th><th>Папка</th><th>Записей</th><th>Занимаемое место</th><th>Функции</th></tr>';
    $num_rows = 0;
    $total_size = 0;
    $groups = System::cache()->GetGroups();
    foreach ($groups as $g) {
        $file_size = 0;
        $num_files = 0;
        $folder = System::cache()->Path . $g;
        $files = scandir($folder);
        foreach ($files as $file) {
            if ($file != '.' && $file != '..') {
                $f = $folder . '/' . $file;
                if (!is_dir($f)) {
                    $file_size += filesize($f);
                }
                $num_files++;
            }
        }
        $func = SpeedButton('Очистить', ADMIN_FILE . '?exe=cache&a=clear&group=' . SafeDB($g, 255, str), 'images/admin/cleanup.png');
        $rows = floor($num_files / 2);
        $text .= '<tr>' . '<td>' . SafeDB($g, 255, str) . '</td>' . '<td>' . SafeDB($folder, 255, str) . '</td>' . '<td>' . $rows . '</td>' . '<td>' . FormatFileSize($file_size) . '</td>' . '<td>' . $func . '</td>' . '</tr>';
        $num_rows += $rows;
        $total_size += $file_size;
    }
    $text .= '</table><br />';
    $text .= 'Итого <b>' . count($groups) . '</b> групп(ы), <b>' . $num_rows . '</b> записей и <b>' . FormatFileSize($total_size) . '</b> занято.&nbsp;' . System::admin()->SpeedButton('Очистить все группы', ADMIN_FILE . '?exe=cache&a=cleanup', '', true, true);
    $text .= '<br /><br />';
    AddText($text);
}
function AdminSiteMessagesMain()
{
    System::database()->Select('messages', '');
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>Название</th><th>Осталось времени</th><th>Кто видит</th><th>Статус</th><th>Функции</th></tr>';
    while ($msg = System::database()->FetchRow()) {
        $mid = SafeDB($msg['id'], 11, int);
        $st = System::admin()->SpeedStatus('Вкл.', 'Выкл.', ADMIN_FILE . '?exe=messages&a=changestatus&id=' . $mid, $msg['active'] == '1');
        $resettime = '';
        if ($msg['expire'] != '0') {
            $total = TotalTime(time(), SafeDB($msg['date'], 11, int) + Day2Sec * SafeDB($msg['expire'], 11, int));
            if ($total['days'] > 0 || $total['hours'] > 0) {
                if ($total['days'] > 0) {
                    $resettime .= $total['sdays'];
                    if ($total['hours'] > 0) {
                        $resettime .= ' и ';
                    }
                }
                if ($total['hours'] > 0) {
                    $resettime .= $total['shours'];
                }
            } else {
                $resettime = 'Время вышло';
            }
        } else {
            $resettime = 'Неограниченно';
        }
        $func = '';
        $func .= SpeedButton('Редактировать', ADMIN_FILE . '?exe=messages&a=msgeditor&id=' . $mid, 'images/admin/edit.png');
        $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=messages&a=delete&id=' . $mid . '&ok=0', 'images/admin/delete.png', 'Удалить сообщение?');
        $text .= '<tr><td><b>' . System::admin()->Link(SafeDB($msg['title'], 250, str), ADMIN_FILE . '?exe=messages&a=msgeditor&id=' . $mid) . '</b></td>
		<td>' . $resettime . '</td>
		<td>' . ViewLevelToStr(SafeDB($msg['view'], 1, int)) . '</td>
		<td>' . $st . '</td>
		<td>' . $func . '</td>
		</tr>';
    }
    $text .= '</table>';
    AddTextBox('Все сообщения', $text);
}
$i = 0;
foreach ($info as $col) {
    if (!isset($col['notnull'])) {
        $col['notnull'] = false;
    }
    if (!isset($col['default'])) {
        $col['default'] = '';
    }
    if (!isset($col['attributes'])) {
        $col['attributes'] = '';
    }
    if (!isset($col['auto_increment'])) {
        $col['auto_increment'] = false;
    }
    $func = '';
    $func .= SpeedButton('Просмотреть информацию для установки', ADMIN_FILE . '?exe=dbadmin&a=viewcollinfo&name=' . $name . '&collid=' . $i, 'images/admin/info.png');
    $func .= System::admin()->SpeedConfirm('Удалить колонку', ADMIN_FILE . '?exe=dbadmin&a=deletecoll&name=' . $name . '&collid=' . $i, 'images/admin/delete.png', 'Удалить колонку?');
    $text .= '<tr>
	<td>' . $i . '</td>
	<td>' . SafeDB($col['name'], 255, str) . '</td>
	<td>' . SafeDB($col['type'], 255, str) . (isset($col['length']) ? '(' . SafeDB($col['length'], 11, int) . ')' : '') . '</td>
	<td>' . SafeDB($col['attributes'], 255, str) . '</td>
	<td>' . ($col['notnull'] ? '<font color="#0000FF">Нет</font>' : '<font color="#FF0000">Да</font>') . '</td>
	<td>' . SafeDB($col['default'], 255, str) . '</td>
	<td>' . ($col['auto_increment'] ? '<font color="#FF0000">Да</font>' : '<font color="0000FF">Нет</a>') . '</td>
	<td>' . $func . '</td>';
    System::site()->DataAdd($selcoldata, $i, SafeDB($col['name'], 255, str), $i == $colcount);
    $i++;
}
$text .= '</table><br />';
AddCenterBox('Структура таблицы "' . $name . '"');
function AdminsGroups()
{
    $accesses = System::database()->Select('access', '');
    foreach ($accesses as $ac) {
        $access[SafeDB($ac['group'], 255, str)][SafeDB($ac['name'], 255, str)] = SafeDB($ac['description'], 255, str);
    }
    unset($accesses);
    $atypes = System::database()->Select('usertypes', '');
    foreach ($atypes as $type) {
        $types[SafeDB($type['id'], 11, int)] = array('<font color="' . $type['color'] . '">' . SafeDB($type['name'], 255, str) . '</font>', SafeDB($type['access'], 0, str, false, false), SafeDB($type['id'], 11, int), SafeDB($type['system'], 1, bool));
    }
    unset($atypes);
    unset($type);
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable"><th>Группа</th><th>Доступ</th><th>Функции</th></tr>';
    foreach ($types as $type) {
        $funcs = '';
        $funcs .= SpeedButton('Редактировать', ADMIN_FILE . '?exe=admins&a=editgroup&id=' . $type[2], 'images/admin/edit.png');
        if ($type[3] == '0') {
            $funcs .= SpeedButton('Удалить', ADMIN_FILE . '?exe=admins&a=delgroup&id=' . $type[2], 'images/admin/delete.png');
        }
        $text .= '<tr>
		<td>' . $type[0] . '</td>
		<td>' . SafeDB(AdminsGenAccessStr($type[1], $access, $type[3]), 0, str) . '</td>
		<td>' . $funcs . '</td>
		</tr>';
    }
    $text .= '</table>';
    AddTextBox('Группы администраторов', $text);
}
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);
}
	<tr>
		<th>Действие</th>
		<th width="2">
	</th>';
$nc = count($info);
foreach ($info as $col) {
    $text .= '<th>' . $col['name'] . '</th>';
}
$text .= '</tr>';
$i = $rows_on_page * $page - $rows_on_page;
$back = SaveRefererUrl();
foreach ($rows as $col) {
    $func = '';
    $func .= SpeedButton('Редактировать', ADMIN_FILE . '?exe=dbadmin&a=editfield&name=' . $namedb . '&index=' . $i . $where_url . '&back=' . $back, 'images/admin/edit.png');
    $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=dbadmin&a=deleterow&name=' . $namedb . '&index=' . $i . $where_url . '&back=' . $back, 'images/admin/delete.png', 'Удалить запись?');
    $func .= SpeedButton('PHP код вставки', ADMIN_FILE . '?exe=dbadmin&a=viewcode&name=' . $namedb . '&index=' . $i . $where_url, 'images/admin/php.png');
    $text .= '<tr><td nowrap="nowrap">' . $func . '</td><td></td>';
    for ($j = 0; $j < $nc; $j++) {
        $col_name = $info[$j]['name'];
        strlen($col[$col_name]) > 255 ? $p = '... ...' : ($p = '');
        $text .= '<td>' . substr(HtmlChars($col[$col_name]), 0, 255) . $p . '</td>';
    }
    $text .= '</tr>';
    $i++;
}
$text .= '</table>';
AddText($text);
if ($nav) {
    AddNavigation();
}
AdminFdbAdminGenTableMenu($namedb);
$totalrows = 0;
$light = array();
$i = 0;
foreach ($tables as $r) {
    $i++;
    $name = SafeDb($r['name'], 255, str);
    $a = '';
    if ($sort == 'name') {
        $F = SafeDb($r['name'], 1, str);
        if (!isset($light[$F])) {
            $light[$F] = $F;
            $a = '<span style="float:right; font-size:18px; margin-right:10px;"><b>' . strtoupper($F) . '</b></span>';
        }
    }
    $func = SpeedButton('PHP код для создания', ADMIN_FILE . '?exe=dbadmin&a=viewtablecode&name=' . $name, 'images/admin/php.png');
    $func .= SpeedButton('Переименовать', ADMIN_FILE . '?exe=dbadmin&a=renametable&name=' . $name, 'images/admin/rename.png');
    if ($last_backup_name != '') {
        $func .= System::admin()->SpeedConfirm('Восстановить из последней резервной копии', ADMIN_FILE . '?exe=dbadmin&a=backup_restore&name=' . $last_backup_name . '&table=' . $name, 'images/admin/restore.png', 'Все текущие данные будут затёрты. Восстановить таблицу из последней резервной копии БД?');
    }
    $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=dbadmin&a=droptable&name=' . $name . '&ok=0', 'images/admin/delete.png', 'Удалить таблицу?');
    $text .= '<tr>' . '<td style="text-align:left; padding-left:10px;">' . $i . $a . '</td>' . '<td align="left" style="text-align:left; padding-left:10px;"><b>' . System::admin()->Link($name, ADMIN_FILE . '?exe=dbadmin&a=structure&name=' . $name) . '</b></td>' . '<td>' . $r['num_rows'] . '</td>' . '<td>' . FormatFileSize($r['size']) . '</td>' . '<td>' . (isset($r['type']) ? $r['type'] : 'По умолчанию') . '</td>' . '<td class="cfgtd">' . $func . '</td>' . '</tr>';
    $totalsize += $r['size'];
    $totalrows += $r['num_rows'];
    System::admin()->BreadCrumbMenuItem($name, 'exe=dbadmin&a=structure&name=' . $name);
}
$text .= '</table><br><br>';
$top_text .= '<strong>Таблиц</strong>: ' . System::database()->NumRows() . '<br>';
$top_text .= '<strong>Всего записей</strong>: ' . $totalrows . '<br>';
$top_text .= '<strong>Общий размер</strong>: ' . FormatFileSize($totalsize) . '<br>';
AddCenterBox('Обзор таблиц (' . System::database()->NumRows() . ')');
AddText($text);
/**
 * Генерирует Ajax дерево страниц
 * @return void
 */
function AdminPagesAjaxTree()
{
    UseScript('jquery_ui_treeview');
    if (CheckGet('parent')) {
        $parent = SafeEnv($_GET['parent'], 11, int);
    } else {
        $parent = 0;
    }
    $pages = System::database()->Select('pages');
    SortArray($pages, 'order');
    $pages_tree = new Tree($pages);
    $elements = array();
    if ($parent == 0) {
        $func = '';
        $func .= SpeedButton('Добавить дочернюю страницу', ADMIN_FILE . '?exe=pages&a=editor', 'images/admin/page_add.png');
        $func .= SpeedButton('Добавить дочернюю ссылку', ADMIN_FILE . '?exe=pages&a=link', 'images/admin/link_add.png');
        $func .= SpeedButton('Добавить дочернюю категорию', ADMIN_FILE . '?exe=pages&a=cat', 'images/admin/folder_add.png');
        $site_node = array('id' => '0', 'title' => System::config('general/site_name'), 'icon' => 'images/globe.png', 'func' => $func, 'isnode' => true, 'opened' => true, 'childs' => array());
    }
    foreach ($pages_tree->Cats[$parent] as $page) {
        $id = SafeDB($page['id'], 11, int);
        if ($page['type'] == 'page') {
            $link = Ufu('index.php?name=pages&file=' . SafeDB($page['link'], 255, str), 'pages:page');
            $icon = 'images/page.png';
            $type = 'Страница';
            $counter = SafeDB($page['hits'], 11, int);
            $edit_link = ADMIN_FILE . '?exe=pages&a=editor&id=' . $id;
        } elseif ($page['type'] == 'link') {
            $link = SafeDB($page['text'], 255, str);
            if (substr($link, 0, 6) == 'mod://') {
                $link = Ufu('index.php?name=' . substr($link, 6), '{name}/');
            }
            $icon = 'images/link.png';
            $type = 'Ссылка';
            $counter = '-&nbsp;';
            $edit_link = ADMIN_FILE . '?exe=pages&a=link&id=' . $id;
        } else {
            $link = Ufu('index.php?name=pages&file=' . SafeDB($page['link'], 255, str), 'pages:page');
            $icon = 'images/folder.png';
            $type = 'Категория';
            $counter = '-&nbsp;';
            $edit_link = ADMIN_FILE . '?exe=pages&a=cat&id=' . $id;
        }
        $func = '';
        $func .= System::admin()->SpeedButton('Добавить дочернюю страницу', ADMIN_FILE . '?exe=pages&a=editor&parent=' . $id, 'images/admin/page_add.png');
        $func .= System::admin()->SpeedButton('Добавить дочернюю ссылку', ADMIN_FILE . '?exe=pages&a=link&parent=' . $id, 'images/admin/link_add.png');
        $func .= System::admin()->SpeedButton('Добавить дочернюю категорию', ADMIN_FILE . '?exe=pages&a=cat&parent=' . $id, 'images/admin/folder_add.png');
        $func .= '&nbsp;';
        $func .= System::admin()->SpeedStatus('Скрыть из меню', 'Показать в меню', ADMIN_FILE . '?exe=pages&a=changemenu&id=' . $id, $page['showinmenu'] == '1', 'images/menu_enabled.png', 'images/menu_disabled.png');
        $func .= System::admin()->SpeedStatus('Выключить', 'Включить', ADMIN_FILE . '?exe=pages&a=changestatus&id=' . $id, $page['enabled'] == '1', 'images/bullet_green.png', 'images/bullet_red.png');
        $func .= '&nbsp;';
        $func .= System::admin()->SpeedButton('Редактировать', $edit_link, 'images/admin/edit.png');
        $func .= System::admin()->SpeedConfirmJs('Удалить', '$(\'#tree_container\').treeview(\'deleteNode\', ' . $id . ');', 'images/admin/delete.png', 'Уверены что хотите удалить? Все дочерние страницы и ссылки так-же будут удалены.');
        $view = ViewLevelToStr(SafeDB($page['view'], 1, int));
        $info = Indent("\n\t\t\t<b>Тип</b>: {$type}<br />\n\t\t\t" . ($page['type'] == 'page' ? "<b>Просмотров</b>: {$counter}<br />" : '') . "\n\t\t\t<b>Видят</b>: {$view}<br />\n\t\t\t<b>Адрес</b>: <a href=\"{$link}\" target=\"_blank\">/" . Utf8ToCp1251(rawurldecode($link)) . "</a>\n\t\t");
        $elements[] = array('id' => $id, 'icon' => $icon, 'title' => '<b>' . System::admin()->Link(SafeDB($page['title'], 255, str), $edit_link) . '</a></b>', 'info' => $info, 'func' => $func, 'isnode' => isset($pages_tree->Cats[$id]), 'child_url' => 'admin.php?exe=pages&a=ajaxtree&parent=' . $id);
    }
    if ($parent == 0) {
        $site_node['childs'] =& $elements;
        $tree = array(&$site_node);
    } else {
        $tree =& $elements;
    }
    if ($parent == 0) {
        System::admin()->AddOnLoadJS('$("#tree_container").treeview({move: \'' . ADMIN_FILE . '?exe=pages&a=ajaxmove\', del: \'' . ADMIN_FILE . '?exe=pages&a=delete\', tree: ' . JsonEncode($tree) . '});');
        AddTextBox('Страницы', '<div id="tree_container"></div>');
    } else {
        echo JsonEncode($tree);
        exit;
    }
}