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);
}
            continue;
        }
        // Not wearable
    }
    LoadRawGump($gumpindex, $gumpfile, intval($gumpid), $hue, $hues, $gumprawdata);
}
// Separate name and skill title
$nametitle = striphtmlchars($nametitle);
if (($i = strpos($nametitle, ",")) !== FALSE) {
    $name = substr($nametitle, 0, $i);
    $title = substr($nametitle, $i + 2);
} else {
    $name = $nametitle;
    $title = "";
}
AddText($gumprawdata, $name, $title);
CreateGump($gumprawdata);
fclose($hues);
fclose($tiledata);
fclose($gumpfile);
fclose($gumpindex);
exit;
function LoadRawGump($gumpindex, $gumpfile, $index, $hue, $hues, &$gumprawdata)
{
    $send_data = '';
    $color32 = array();
    fseek($gumpindex, $index * 12, SEEK_SET);
    if (feof($gumpindex)) {
        return;
    }
    // Invalid gumpid, reached end of gumpindex.
function AdminBlocksMain()
{
    System::database()->Select('block_types', '');
    while ($type = System::database()->FetchRow()) {
        $types[SafeDB($type['folder'], 255, str)] = SafeDB($type['name'], 255, str);
    }
    unset($type);
    $b_pos = array('L' => 'Левые блоки', 'R' => 'Правые блоки', 'T' => 'Верхние блоки', 'B' => 'Нижние блоки', 'A' => 'A Нижние блоки');
    $text = '';
    $text .= '<table cellspacing="0" cellpadding="0" class="cfgtable">' . '<tr>
		<th>Заголовок</th>
		<th>Положение</th>
		<th>Тип</th>
		<th>Кто видит</th>
		<th>Статус</th>
		<th>Функции</th>
	</tr>';
    foreach ($b_pos as $pos => $pos_title) {
        System::database()->Select('blocks', "`position`='" . SafeEnv($pos, 255, str) . "'");
        $maxplace = System::database()->NumRows() - 1;
        if ($maxplace + 1 > 0) {
            $text .= '<tr><th colspan="6">' . SafeDB($pos_title, 255, str) . '</th></tr>';
        }
        usort(System::database()->QueryResult, 'AdminBlocksSort');
        while ($block = System::database()->FetchRow()) {
            $block_id = SafeDB($block['id'], 11, int);
            $st = System::admin()->SpeedStatus('Вкл.', 'Выкл.', ADMIN_FILE . '?exe=blocks&a=changestatus&id=' . $block_id, $block['enabled'] == '1');
            $vi = ViewLevelToStr(SafeDB($block['view'], 1, int));
            $move_menu = '';
            if ($maxplace == 0) {
                // Единственный элемент в списке
                $move_menu .= ' - ';
            } else {
                if ($block['place'] >= 0 && $block['place'] < $maxplace) {
                    // Первый элемент
                    $move_menu .= System::admin()->SpeedButton('Вниз', ADMIN_FILE . '?exe=blocks&a=move&to=down&id=' . $block_id, 'images/admin/down.png');
                }
                if ($block['place'] <= $maxplace && $block['place'] > 0) {
                    $move_menu .= System::admin()->SpeedButton('Вверх', ADMIN_FILE . '?exe=blocks&a=move&to=up&id=' . $block_id, 'images/admin/up.png');
                }
            }
            $func = '';
            $func .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=blocks&a=edit&id=' . $block_id, 'images/admin/edit.png');
            $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=blocks&a=del&id=' . $block_id, 'images/admin/delete.png', 'Удалить блок?');
            $text .= '<tr>
			<td><b>' . System::admin()->Link(SafeDB($block['title'], 255, str), ADMIN_FILE . '?exe=blocks&a=edit&id=' . $block_id) . '</b></td>
			<td>' . $move_menu . '</td>
			<td>' . $types[SafeDB($block['type'], 255, str)] . '</td>
			<td>' . $vi . '</td>
			<td>' . $st . '</td>
			<td>' . $func . '</td>
			</tr>';
        }
    }
    $text .= '</table><br />';
    AddCenterBox('Блоки');
    AddText($text);
}
		}
	});
};
');
$backup_files = GetFiles($backup_dir, false, true, '.zip');
rsort($backup_files, SORT_STRING);
$backup_files2 = array();
foreach ($backup_files as $file) {
    if (GetSecondFileExt($file, true) == System::database()->Name) {
        $backup_files2[] = $file;
    }
}
$text = '';
$text .= '<table cellspacing="0" cellpadding="0" class="cfgtable">';
$text .= '<tr><th>Имя файла (дата-время...)</th><th>Функции</th></tr>';
foreach ($backup_files2 as $file) {
    $file = SafeDB($file, 255, str);
    $func = System::admin()->SpeedConfirm('Восстановить', ADMIN_FILE . '?exe=dbadmin&a=backup_restore&name=' . $file, 'images/admin/restore.png', 'Все текущие данные будут затёрты. Восстановить БД из резервной копии?');
    $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=dbadmin&a=backup_delete&name=' . $file, 'images/admin/delete.png', 'Удалить?');
    $text .= '<tr>
	<td><a href="' . $backup_dir . $file . '">' . $file . '</a></td>
	<td>' . $func . '</td>
	</tr>';
}
if (count($backup_files2) == 0) {
    $text .= '<tr><td colspan="2" style="text-align: left;">Нет резервных копий.</td></tr>';
}
$text .= '</table>';
$text .= '<a href="#" id="backup_button" class="button" onclick="CreateBackup(); return false;">Создать резервную копию</a>';
AddText($text);
function AdminConfigViewGroups()
{
    System::database()->Select(AdminConfigGroupTable());
    AddCenterBox('Группы настроек');
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr>
	<th>Имя группы</th>
	<th>Заголовок</th>
	<th>Описание</th>' . '<th>Видимая</th>
	<th>Функции</th>' . '</tr>';
    while ($group = System::database()->FetchRow()) {
        $groupid = SafeDB($group['id'], 11, int);
        $func = '';
        $func .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=config_admin&a=editgroup&id=' . $groupid . (AdminConfigPlugins() ? '&plugins=1' : ''), 'images/admin/edit.png');
        $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=config_admin&a=deletegroup&id=' . $groupid . '&ok=0' . (AdminConfigPlugins() ? '&plugins=1' : ''), 'images/admin/delete.png', 'Это может повлиять на работу системы. Нажмите отмена, если не уверены. Удалить группу настроек?');
        if ($group['visible'] == '1') {
            $visible = '<font color="#008000">Да</font>';
        } else {
            $visible = '<font color="#FF0000">Нет</font>';
        }
        //$install_vals = Values('', $group['name'], $group['hname'], $group['description'], $group['visible']);
        //$install = 'System::database()->Insert("'.AdminConfigGroupTable().'","'.$install_vals.'");';
        $text .= '<tr>
		<td>' . SafeDB($group['name'], 255, str) . '</td>
		<td>' . SafeDB($group['hname'], 255, str) . '</td>
		<td>' . SafeDB($group['description'], 255, str) . '</td>' . '<td>' . $visible . '</td>
		<td>' . $func . '</td>
		</tr>';
    }
    $text .= '</table><br />';
    if (isset($_GET['saveok'])) {
        System::admin()->Highlight('Изменения сохранены.');
    } elseif (isset($_GET['addok'])) {
        System::admin()->Highlight('Группа добавлена.');
    } elseif (isset($_GET['delok'])) {
        System::admin()->Highlight('Группа удалена.');
    }
    AddText($text);
    //AddText('.:Добавить группу:.');
    System::admin()->FormTitleRow('Добавить группу');
    FormRow('Имя', System::site()->Edit('name', '', false, 'style="width:400px;"'));
    FormRow('Заголовок', System::site()->Edit('hname', '', false, 'style="width:400px;"'));
    FormRow('Описание', System::site()->TextArea('description', '', 'style="width:400px;height:100px;"'));
    FormRow('Видимая', System::site()->Check('visible', '1', false));
    AddForm('<form action="' . ADMIN_FILE . '?exe=config_admin&a=savegroup' . (AdminConfigPlugins() ? '&plugins=1' : '') . '" method="post">', System::site()->Submit('Добавить'));
}
function AdminNewsTopics()
{
    global $news_access_edittopics;
    UseScript('jquery_ui', 'colorbox?theme=admin');
    if (!$news_access_edittopics) {
        System::admin()->AccessDenied();
    }
    $cntr = 0;
    AddCenterBox('Текущие новостные разделы');
    $topics = System::database()->Select('news_topics');
    $text = '<table style="width: 100%; border: 1px #ABC5D8 solid; background-color: #fff; padding: 10px;">';
    foreach ($topics as $topic) {
        $topic_id = SafeDB($topic['id'], 11, int);
        $edit_url = ADMIN_FILE . '?exe=news&a=edittopic&id=' . $topic_id;
        $link_go = Ufu('index.php?name=news&topic=' . $topic_id, 'news/{topic}/');
        $title = SafeDB($topic['title'], 255, str);
        $desc = SafeDB($topic['description'], 255, str);
        $counter = SafeDB($topic['counter'], 11, int);
        $image = SafeDB($topic['image'], 255, str);
        if ($image != '') {
            list($width, $height) = SafeDB(explode(':', System::config('news/topics_tmb_size')), 11, int);
            $image = GetThumb($image, $width, $height);
            $image = '<tr><td align="center"><a href="' . $edit_url . '"><img src="' . $image . '" height="80" title="' . $desc . '"></a></td></tr>';
        }
        $func = '';
        $func .= System::admin()->SpeedButton('Перейти к странице на сайте', $link_go, 'images/link_go.png', false, false, 'target="_blank"');
        $func .= System::admin()->SpeedButton('Редактировать', $edit_url, 'images/admin/edit.png');
        $func .= System::admin()->SpeedAjax('Удалить', ADMIN_FILE . '?exe=news&a=deltopic&id=' . $topic_id, 'images/admin/delete.png', 'Удалить раздел? Все новости в этом разделе так-же будут удалены.', '', "\$('#topic_{$topic_id}').children('table').fadeOut('slow');");
        if ($cntr % 4 == 0) {
            $text .= '<tr>';
        }
        $text .= Indent('
			<td id="topic_$topic_id" valign="top" align="center" style="padding: 10px;">
				<table align="center" cellspacing="5" cellpadding="0">
					<tr>
						<td align="center">
							<b><a href="' . $edit_url . '">' . $title . '</a> (' . $counter . ')</b>
						</td>
					</tr>
					' . $image . '
					<tr>
						<td align="center">' . $func . '</td>
					</tr>
				</table>
			</td>
		');
        if (++$cntr % 4 == 0) {
            $text .= '</tr>';
        }
    }
    if ($cntr % 4 != 0) {
        $text .= '</tr>';
    }
    $text .= '</table>';
    AddText($text);
    System::admin()->FormTitleRow('Создать новый раздел новостей');
    System::admin()->FormRow('Название раздела', System::admin()->Edit('topic_name', '', false, 'maxlength="255" style="width:400px;"'));
    System::admin()->FormTextRow('Описание (HTML)', System::admin()->HtmlEditor('topic_description', '', 600, 200));
    FormRow('Изображение', System::admin()->FileManager('topic_image', '') . '<br>
		<a href="images/no_image.png" class="filemanager_topic_image colorbox" data-content="href:path" target="_blank">
			<img src="images/no_image.png" class="filemanager_topic_image" data-content="src:tmb" style="margin-top: 5px; max-width: 250px;">
		</a>');
    System::admin()->AddForm('<form name="topicsform" action="' . ADMIN_FILE . '?exe=news&a=addtopic" method="post" name="topicsform">', System::admin()->Submit('Создать'));
}
function AdminGalleryUpload()
{
    // TODO: неправильный порядок изображений при мультизагрузке
    if (!isset($_POST['action']) || !isset($_GET['formid']) || !isset($_SESSION['uploadforms'][$_GET['formid']])) {
        AdminGalleryUploadForm();
        return;
    }
    global $GalleryDir, $ThumbsDir;
    $formid = $_GET['formid'];
    // Загрузка фотографий
    if ($_POST['action'] == 'upload') {
        // SwfUpload кодирует имена файлов в UTF-8
        $_FILES['up_image']['name'] = Utf8ToCp1251($_FILES['up_image']['name']);
        $Error = false;
        $_SESSION['uploadforms'][$formid]['photos'][] = LoadImage('up_image', $GalleryDir, $ThumbsDir, System::config('gallery/thumb_max_width'), System::config('gallery/thumb_max_height'), '', $Error, true, System::config('gallery/optimize_originals'), System::config('gallery/original_width'), System::config('gallery/original_height'));
        if ($Error) {
            exit('ERROR 2');
        }
        exit('OK');
    }
    // Предпросмотр добавляемых фотографий
    $_SESSION['uploadforms'][$formid]['category'] = $_POST['category'];
    $_SESSION['uploadforms'][$formid]['allow_comments'] = EnToInt($_POST['allow_comments']);
    $_SESSION['uploadforms'][$formid]['allow_votes'] = EnToInt($_POST['allow_votes']);
    $_SESSION['uploadforms'][$formid]['show'] = EnToInt($_POST['show']);
    $_SESSION['uploadforms'][$formid]['view'] = ViewLevelToInt($_POST['view']);
    AddCenterBox('Мультизагрузка - предпросмотр');
    $count_photos = count($_SESSION['uploadforms'][$formid]['photos']);
    $text = '<form action="' . ADMIN_FILE . '?exe=gallery&a=saveuploaded&formid=' . $formid . '" method="post">';
    $submits = System::admin()->Submit('Отмена', 'name="submit_cancel" value="cancel"') . System::admin()->Submit('Сохранить', 'name="submit_save" value="save"');
    $text .= '<div class="cfgboxsubmit"><div style="float: left;">Загружено ' . $count_photos . ' изображений.</div>' . $submits . '</div>';
    foreach ($_SESSION['uploadforms'][$formid]['photos'] as $id => $photo) {
        $func = System::admin()->SpeedAjax('Удалить', ADMIN_FILE . '?exe=gallery&a=deleteuploaded&id=' . $id . '&formid=' . $formid, 'images/admin/delete.png', '', '', "jQuery('#photo_box_{$id}').fadeOut();");
        $text .= Indent('
			<div class="cfgbox" id="photo_box_' . $id . '">
				<table cellspacing="0" cellpadding="0" border="0" style="width: 100%;">
					<tr>
						<td style="vertical-align: top; width: 160px;">
							<a href="' . $GalleryDir . $photo . '" target="_blank"><img src="' . $ThumbsDir . $photo . '" /></a>
							' . $photo . '
						</td>
						<td style="vertical-align: top;">
							<table cellspacing="2" cellpadding="4" style="width: 100%;" class="cfgtable">
								<tr>
									<td>Заголовок</td>
									<td colspan="3" style="text-align: left;">' . System::admin()->Edit('title_' . $id, '', false, 'maxlength="250" style="width:400px;"') . '</td>
								</tr>
								<tr>
									<td>Описание (HTML)</td>
									<td colspan="3" style="text-align: left;">' . System::admin()->TextArea('description_' . $id, '', 'style="width: 400px; height: 120px;"') . '</td>
								</tr>
								<tr>
									<td>Автор</td>
									<td style="text-align: left;">' . System::admin()->Edit('author_' . $id, '', false, 'maxlength="250" style="width:200px;"') . '</td>
									<td>Email автора</td>
									<td style="text-align: left;">' . System::admin()->Edit('email_' . $id, '', false, 'maxlength="250" style="width:200px;"') . '</td>
								</tr>
								<tr>
									<td>Сайт автора</td>
									<td colspan="3" style="text-align: left;">' . System::admin()->Edit('www_' . $id, '', false, 'maxlength="250" style="width:200px;"') . '</td>
								</tr>
							</table>
						</td>
						<td style="vertical-align: top; text-align: right; width: 50px;">' . $func . '</td>
					</tr>
				</table>
			</div>
		');
    }
    $text .= '<div class="cfgboxsubmit">' . $submits . '</div>';
    $text .= '</form>';
    AddText($text);
}
function AdminArticlesMain()
{
    global $editarticles;
    // Фильтр, дает возможность показывать статьи определенной категории.
    if (isset($_GET['cat']) && $_GET['cat'] > -1) {
        $cat = SafeEnv($_GET['cat'], 11, int);
        $where = "`cat_id`='{$cat}'";
    } else {
        $cat = -1;
        $where = "";
    }
    $data = array();
    $data = AdminArticlesGetTree()->GetCatsData($cat, true);
    System::site()->DataAdd($data, -1, 'Все статьи', $cat == -1);
    // Получаем номер страницы
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 10, int);
    } else {
        $page = 1;
    }
    AddCenterBox('Статьи');
    // Форма фильтра по категориям
    System::admin()->AddJS('
	ArticlesSelectCat = function(){
		Admin.LoadPage("' . ADMIN_FILE . '?exe=articles&cat="+$("#article-cat").val());
	}
	');
    $text = '<div style="text-align: center; margin-bottom: 10px;">Категория: ' . System::site()->Select('cat', $data, false, 'id="article-cat" onchange="ArticlesSelectCat();"') . '</div>';
    AddText($text);
    // Берем статьи из БД и включаем постраничную навигацию если нужно.
    $r = System::database()->Select('articles', $where);
    SortArray($r, 'public', true);
    // Сортируем по дате добавления
    if (count($r) > System::config('articles/articles_on_page')) {
        $navigator = new Navigation($page);
        $navigator->GenNavigationMenu($r, System::config('articles/articles_on_page'), ADMIN_FILE . '?exe=articles' . ($cat > 0 ? '&cat=' . $cat : ''));
        $nav = true;
    } else {
        $nav = false;
    }
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>Название</th><th>Прочитано</th><th>Оценки</th><th>Видят</th><th>Статус</th><th>Функции</th></tr>';
    $back = SaveRefererUrl();
    foreach ($r as $art) {
        $id = SafeDB($art['id'], 11, int);
        $cat_id = SafeDB($art['cat_id'], 11, int);
        $title = SafeDB($art['title'], 255, str);
        $hits = SafeDB($art['hits'], 11, int);
        $rating = '<img src="' . GetRatingImage(SafeDB($art['num_votes'], 11, int), SafeDB($art['all_votes'], 11, int)) . '" border="0" />';
        $st = $art['active'] == '1' ? 'Вкл.' : 'Выкл.';
        $link_go = Ufu("index.php?name=articles&op=read&art={$id}&cat={$cat_id}", 'articles/{cat}/{art}/');
        $func = '';
        $func .= System::admin()->SpeedButton('Перейти к странице на сайте', $link_go, 'images/link_go.png', false, false, 'target="_blank"');
        if ($editarticles) {
            $title = '<b>' . System::admin()->Link($title, ADMIN_FILE . '?exe=articles&a=editor&id=' . $id . '&back=' . $back) . '</b>';
            $hits .= '&nbsp;' . System::admin()->SpeedConfirm('Обнулить счётчик просмотров', ADMIN_FILE . '?exe=articles&a=resethits&id=' . $id . '&back=' . $back, 'images/admin/arrow_in.png', 'Сбросить счётчик просмотров?');
            $rating .= '&nbsp;' . System::admin()->SpeedConfirm('Обнулить счётчик оценок (' . SafeDB($art['num_votes'], 11, int) . ' голосов)', ADMIN_FILE . '?exe=articles&a=resetrating&id=' . $id . '&back=' . $back, 'images/admin/arrow_in.png', 'Сбросить оценки?');
            $st = System::admin()->SpeedStatus('Включена', 'Отключена', ADMIN_FILE . '?exe=articles&a=changestatus&id=' . $id, $art['active'] == '1');
            $func .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=articles&a=editor&id=' . $id . '&back=' . $back, 'images/admin/edit.png');
            $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=articles&a=delete&id=' . $id . '&ok=1&back=' . $back, 'images/admin/delete.png', 'Удалить статью?');
        }
        $text .= '<tr>
		<td>' . $title . '</td>
		<td>' . $hits . '</td>
		<td>' . ($art['allow_votes'] == '1' ? $rating : 'Запрещены') . '</td>
		<td>' . ViewLevelToStr(SafeDB($art['view'], 1, int)) . '</td>
		<td>' . $st . '</td>
		<td>' . $func . '</td>
		</tr>';
    }
    $text .= '</table>';
    AddText($text);
    if ($nav) {
        AddNavigation();
    }
}
function AdminUserAvatarsGallery()
{
    global $galeryedit;
    TAddSubTitle('Галерея аватар');
    if (isset($_GET['user']) && $_GET['user'] == '1') {
        $personal = true;
        $dir = System::config('general/personal_avatars_dir');
        $dirlink = System::admin()->Link('Показать аватары из галереи', ADMIN_FILE . '?exe=user&a=avatars');
        $users = System::database()->Select('users', "`type`='2'");
        $c = sizeof($users);
        for ($i = 0; $i < $c; $i++) {
            $users[$users[$i]['avatar']] = $i;
        }
    } else {
        $personal = false;
        $dir = System::config('general/avatars_dir');
        $dirlink = System::admin()->Link('Показать аватары пользователей', ADMIN_FILE . '?exe=user&a=avatars&user=1');
    }
    $avatars2 = GetFiles($dir, false, true, '.gif.jpg.jpeg.png');
    $avatars = array();
    foreach ($avatars2 as $av) {
        $name = GetFileName($av, true);
        $sub = substr($name, -3);
        if ($sub != 'x24' && $sub != 'x64') {
            $avatars[] = $av;
        }
    }
    $c = count($avatars);
    $allsize = 0;
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    if ($c > 0) {
        $col = 0;
        for ($i = 0; $i < $c; $i++) {
            if ($col == 0) {
                $text .= '<tr>';
            }
            $col++;
            $imagfn = $dir . $avatars[$i];
            $size = getimagesize($imagfn);
            $fsize = filesize($imagfn);
            $allsize = $allsize + $fsize;
            if ($galeryedit) {
                $funcs = System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=user&a=delavatar&filename=' . $avatars[$i] . ($personal ? '&personal' : ''), 'images/admin/delete.png', 'Удалить аватар?');
            } else {
                $funcs = '&nbsp;';
            }
            $text .= '<td align="center">
				<table cellspacing="0" cellpadding="0" align="center" style="border:none; background: none;">
				<tr style="border:none; background: none;">
					<td style="border:none; background: none;"><a href="' . $imagfn . '" target="_blank"><img src="' . $imagfn . '" border="0" width="64" title="(' . $size[0] . ' x ' . $size[1] . ', ' . FormatFileSize($fsize) . ') ' . $avatars[$i] . '" /></a></td>
					<td valign="top" style="border:none; background: none;">' . $funcs . '</td>
				</tr>
				';
            if ($personal && isset($users[$avatars[$i]])) {
                $text .= '<tr><td colspan="2" align="left" style="border:none; background: none;"><a href="' . ADMIN_FILE . '?exe=user&a=edituser&id=' . SafeDB($users[$users[$avatars[$i]]]['id'], 11, int) . '">' . SafeDB($users[$users[$avatars[$i]]]['name'], 255, str) . '</a></td></tr>';
            }
            $text .= '</table></td>';
            if ($col == 5) {
                $text .= '</tr>';
                $col = 0;
            }
        }
        if ($col < 5) {
            $text .= '<td colspan="' . (5 - $col) . '"></td>';
            $text .= '</tr>';
        }
    } else {
        $text .= '<tr><td>В галерее нет ни одного аватара.</td></tr>';
    }
    $text .= '</table>';
    $info = '<table cellspacing="0" cellpadding="0" border="0" class="cfgtable">
		<tr>
		<td width="34%">Аватар в галерее: ' . $c . '</td>
		<td width="33%">Общий размер: ' . FormatFileSize($allsize) . '</td>
		<td>' . $dirlink . '</td>
		</tr>
	</table>';
    $text = $info . $text;
    AddCenterBox('Галерея аватар', $text);
    AddText($text);
    if (!$personal && $galeryedit) {
        System::admin()->FormTitleRow('Загрузить аватар');
        FormRow('Выберите файл', System::site()->FFile('avatar'));
        AddForm(System::site()->FormOpen(ADMIN_FILE . '?exe=user&a=saveavatar', 'post', true), System::site()->Submit('Загрузить'));
    }
    AddText('<br />');
}
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>');
}
function AdminSmiliesAutoAdd()
{
    global $mod, $smilies_dir;
    AddCenterBox('Авто-добавление смайликов');
    $smilies = System::database()->Select('smilies');
    $xor_smilies = array();
    foreach ($smilies as $smile) {
        $xor_smilies[] = $smile['file'];
    }
    $find_smilies = AdminSmiliesFind($smilies_dir, $xor_smilies);
    if (count($find_smilies) == 0) {
        System::admin()->Highlight('Новых файлов не найдено. Загрузите изображения смайликов в папку: <b>' . $smilies_dir . '</b>.');
        return;
    }
    $text = '';
    $text .= System::site()->FormOpen(ADMIN_FILE . '?exe=smilies&a=autosave');
    $text .= '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr>
		<th>Добавить</th>
		<th>Изображение</th>
		<th>Код</th>
		<th>Описание</th>
		<th>Имя файла</th>
		<th>Показать</th>
		<th>Удалить</th>
	</tr>';
    foreach ($find_smilies as $sm) {
        $file = SafeDB($sm['file'], 255, str);
        $func = System::admin()->SpeedConfirm('Удалить файл', $mod . '&a=deletefile&name=' . $file, 'images/admin/delete.png', 'Удалить файл с сервера?');
        $text .= '<tr>' . '<td>' . System::site()->Check('smilies[]', $file, true) . '</td>' . '<td><img src="' . $smilies_dir . $file . '"></td>' . '<td>' . System::site()->Edit('code[' . $file . ']', SafeDB($sm['code'], 255, str), false, 'style="width:160px;"') . '</td>' . '<td>' . System::site()->Edit('desc[' . $file . ']', SafeDB($sm['desc'], 255, str), false, 'style="width:160px;"') . '</td>' . '<td>' . $file . '</td>' . '<td>' . System::site()->Check('en[' . $file . ']', '1', true) . '</td>' . '<td>' . $func . '</td>' . '</tr>';
    }
    $text .= '</table>';
    $text .= System::site()->Submit('Добавить') . '<br /><br />';
    $text .= System::site()->FormClose();
    AddText($text);
}
function AdminAuditReferers()
{
    System::admin()->AddCenterBox('Переходы с сайтов (Рефералы)');
    $query = System::database()->Select('referers', '');
    SortArray($query, 'count', true);
    $allcount = 0;
    $count = count($query);
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 10, int);
    } else {
        $page = 1;
    }
    $num = 50;
    if ($count > $num) {
        $navigator = new Navigation($page);
        $navigator->GenNavigationMenu($query, $num, ADMIN_FILE . '?exe=audit&a=referers');
        $nav = true;
    } else {
        $nav = false;
    }
    if ($count == 0) {
        System::admin()->Highlight('Рефералов не было обнаружено.');
    } elseif ($count >= 1) {
        $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
        $text .= Indent('<tr>
			<th>Реферал</th>
			<th>Переходов</th>
		</tr>');
        foreach ($query as $q) {
            $referer = 'http://' . $q['referer'];
            $title = AdminAuditDecodeUrl($referer);
            $count = SafeDB($q['count'], 11, int);
            $allcount += $count;
            $text .= '<tr>
			<td><a href="' . $referer . '" target="_blank">' . $title . '</a></td>
			<td>' . $count . '</td>
			</tr>';
        }
        $text .= '</table>';
        $text .= 'Всего переходов на этой странице: <b>' . $allcount . '</b>.&nbsp;' . System::admin()->SpeedConfirm('Очистить  лог', ADMIN_FILE . '?exe=audit&a=clear_referers', '', 'Очистить лог рефералов?', true, true);
        AddText($text);
        if ($nav) {
            AddNavigation();
        }
    }
}
function AdminFormsFields()
{
    if (!isset($_GET['id'])) {
        GO(ADMIN_FILE . '?exe=forms');
    }
    $id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select('forms', "`id`='{$id}'");
    $form = System::database()->FetchRow();
    $fields = unserialize($form['form_data']);
    $cnt = count($fields);
    AddCenterBox('Поля формы "' . $form['hname'] . '"');
    $text = '';
    $text .= '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>Название</th><th>Имя HTML</th><th>Предпросмотр</th><th>Тип</th><th>Максимальная длина</th><th>Вид</th><th>Функции</th></tr>';
    if ($cnt > 0) {
        for ($i = 0; $i < $cnt; $i++) {
            $func = '';
            $func .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=forms&a=editfield&id=' . SafeDB($form['id'], 11, int) . '&index=' . $i, 'images/admin/edit.png');
            $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=forms&a=delfield&id=' . SafeDB($form['id'], 11, int) . '&index=' . $i, 'images/admin/delete.png', 'Удалить?');
            $type = explode(',', $fields[$i]['type']);
            $text .= '<tr><td>' . SafeDB($fields[$i]['hname'], 255, str) . '</td><td>' . SafeDB($fields[$i]['name'], 255, str) . '</td><td>' . FormsGetControl($fields[$i]['name'], '', $fields[$i]['kind'], $fields[$i]['type'], $fields[$i]['values']) . '</td><td>' . SafeDB($type[1], 50, str) . '</td><td>' . SafeDB($type[0], 11, int) . '</td><td>' . $fields[$i]['kind'] . '</td><td>' . $func . '</td></tr>';
        }
    } else {
        $text .= '<tr><td colspan="7" style="text-align: left;">В этой форме нет полей.</td></tr>';
    }
    $text .= '</table>';
    AddText($text);
    AdminFormsFieldEditor('add');
}
function AdminDownloadsMain()
{
    $editfiles = System::user()->CheckAccess2('downloads', 'edit_files');
    $back = SaveRefererUrl();
    if (isset($_GET['cat']) && $_GET['cat'] > -1) {
        $cat = SafeEnv($_GET['cat'], 11, int);
        $where = "`category`='{$cat}'";
    } else {
        $cat = -1;
        $where = "";
    }
    $data = array();
    $data = AdminDownloadsGetTree()->GetCatsData($cat, true);
    System::site()->DataAdd($data, -1, 'Все файлы', $cat == -1);
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 10, int);
    } else {
        $page = 1;
    }
    AddCenterBox('Файлы');
    System::admin()->AddJS(Indent('
		DownloadsSelectCat = function(){
			Admin.LoadPage("' . ADMIN_FILE . '?exe=downloads&cat="+$("#download-cat").val());
		}
	'));
    $text = '<div style="text-align: center; margin-bottom: 10px;">Категория: ' . System::site()->Select('cat', $data, false, 'id="download-cat" onchange="DownloadsSelectCat();"') . '</div>';
    AddText($text);
    System::database()->Select('downloads', $where);
    SortArray(System::database()->QueryResult, 'public', true);
    if (count(System::database()->QueryResult) > System::config('downloads/filesonpage')) {
        $navigator = new Navigation($page);
        $navigator->GenNavigationMenu(System::database()->QueryResult, System::config('downloads/filesonpage'), ADMIN_FILE . '?exe=downloads' . ($cat > 0 ? '&cat=' . $cat : ''));
        $nav = true;
    } else {
        $nav = false;
    }
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr><th>Заголовок</th><th>Скачиваний</th><th>Оценки</th><th>Видят</th><th>Статус</th><th>Функции</th></tr>';
    while ($row = System::database()->FetchRow()) {
        $id = SafeDB($row['id'], 11, int);
        $title = SafeDB($row['title'], 255, str);
        $hits = SafeDB($row['hits'], 11, int);
        $rating = '<img src="' . GetRatingImage(SafeDB($row['votes_amount'], 11, int), SafeDB($row['votes'], 11, int)) . '" border="0" />';
        $st = $row['active'] == '1' ? 'Вкл.' : 'Выкл.';
        $func = '-';
        if ($editfiles) {
            $title = '<b>' . System::admin()->Link($title, ADMIN_FILE . '?exe=downloads&a=editor&id=' . $id . '&back=' . $back) . '</b>';
            $hits .= '&nbsp;' . System::admin()->SpeedConfirm('Обнулить счётчик скачиваний', ADMIN_FILE . '?exe=downloads&a=resetcounter&id=' . $id . '&back=' . $back, 'images/admin/arrow_in.png', 'Сбросить счётчик скачиваний?');
            $rating .= '&nbsp;' . System::admin()->SpeedConfirm('Обнулить счётчик оценок (' . SafeDB($row['votes_amount'], 11, int) . ' голосов)', ADMIN_FILE . '?exe=downloads&a=resetrating&id=' . $id . '&back=' . $back, 'images/admin/arrow_in.png', 'Сбросить оценки?');
            $st = System::admin()->SpeedStatus('Вкл.', 'Выкл.', ADMIN_FILE . '?exe=downloads&a=changestatus&id=' . $id, $row['active'] == '1');
            $func = System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=downloads&a=editor&id=' . $id . '&back=' . $back, 'images/admin/edit.png');
            $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=downloads&a=deletefile&id=' . $id . '&ok=0&back=' . $back, 'images/admin/delete.png', 'Удалить файл?');
        }
        $text .= '<tr><td>' . $title . '</td>
		<td>' . $hits . '</td>
		<td>' . ($row['allow_votes'] == '1' ? $rating : 'Запрещены') . '</td>
		<td>' . ViewLevelToStr(SafeDB($row['view'], 1, int)) . '</td>
		<td>' . $st . '</td>
		<td>' . $func . '</td>
		</tr>';
    }
    $text .= '</table>';
    AddText($text);
    if ($nav) {
        AddNavigation();
    }
}