function MessagesRender($msg)
{
    global $userAccess;
    $disableMsg = '';
    $total = TotalTime(time(), $msg['date'] + Day2Sec * $msg['expire']);
    if ($total === false) {
        if ($msg['expire'] != 0) {
            $disableMsg .= "and `id`='" . $msg['id'] . "'";
            return;
        }
    }
    if (VisibilityConditionsCheck($msg['showin'], $msg['showin_uri'])) {
        $adin = '';
        if ($userAccess == '1') {
            if ($msg['expire'] != '0') {
                $vt = 'Срок истекает через ' . $total['sdays'] . ($total['hours'] != 0 ? ' и ' . $total['shours'] : '');
            } else {
                $vt = 'Неограниченно';
            }
            $adin = '(Просматривают: ' . ViewLevelToStr($msg['view'], 'Только администраторы', 'Только пользователи', 'Только анонимные пользователи', 'Все посетители') . ' - ' . $vt . ' - <a href="' . ADMIN_FILE . '?exe=messages&a=msgeditor&id=' . $msg['id'] . '">Редактировать</a>)';
        }
        if ($msg['view_title'] == 1) {
            // Показывать заголовок
            $title = $msg['title'];
        } else {
            $title = '';
        }
        System::site()->AddMessage($title, $msg['text'], $adin);
    }
}
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);
}
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);
}
/**
 * Главная страница, список новостей
 * @return void
 */
function AdminNewsMain()
{
    global $news_access_editnews;
    System::admin()->AddSubTitle('Главная');
    $back = SaveRefererUrl();
    // Количество новостей на странице
    if (isset($_REQUEST['onpage'])) {
        $num = intval($_REQUEST['onpage']);
    } else {
        $num = System::config('news/newsonpage');
    }
    if (isset($_REQUEST['page'])) {
        $page = intval($_REQUEST['page']);
    } else {
        $page = 1;
    }
    $newsdb = System::database()->Select('news');
    $columns = array('title', 'date', 'hit_counter', 'comments_counter', 'view', 'enabled');
    $sortby = 'date';
    $sortbyid = 1;
    $desc = true;
    if (isset($_REQUEST['sortby'])) {
        $sortby = $columns[$_REQUEST['sortby']];
        $sortbyid = intval($_REQUEST['sortby']);
        $desc = $_REQUEST['desc'] == '1';
    }
    SortArray($newsdb, $sortby, $desc);
    // Выводим новости
    UseScript('jquery_ui_table');
    $table = new jQueryUiTable();
    $table->listing = ADMIN_FILE . '?exe=news&ajax';
    $table->del = ADMIN_FILE . '?exe=news&a=delete';
    $table->total = count($newsdb);
    $table->onpage = $num;
    $table->page = $page;
    $table->sortby = $sortbyid;
    $table->sortdesc = $desc;
    $table->AddColumn('Заголовок');
    $table->AddColumn('Дата', 'left', true, true);
    $table->AddColumn('Просмотров', 'right');
    $table->AddColumn('Комментарий', 'right');
    $table->AddColumn('Кто видит', 'center');
    $table->AddColumn('Статус', 'center');
    $table->AddColumn('Функции', 'center', false, true);
    $newsdb = ArrayPage($newsdb, $num, $page);
    // Берем только новости с текущей страницы
    foreach ($newsdb as $news) {
        $id = SafeDB($news['id'], 11, int);
        $status = System::admin()->SpeedStatus('Выключить', 'Включить', ADMIN_FILE . '?exe=news&a=changestatus&id=' . $id, $news['enabled'], 'images/bullet_green.png', 'images/bullet_red.png');
        $view = ViewLevelToStr(SafeDB($news['view'], 1, int));
        $allowComments = SafeDB($news['allow_comments'], 1, bool);
        $comments = SafeDB($news['comments_counter'], 11, int);
        // Количество комментарий
        $title = SafeDB($news['title'], 255, str);
        $func = '';
        $link_go = Ufu('index.php?name=news&op=readfull&news=' . $id . '&topic=' . SafeDB($news['topic_id'], 11, int), 'news/{topic}/{news}/');
        $func .= System::admin()->SpeedButton('Перейти к странице на сайте', $link_go, 'images/link_go.png', false, false, 'target="_blank"');
        if ($news_access_editnews) {
            $func .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=news&a=edit&id=' . $id . '&back=' . $back, 'images/admin/edit.png');
            $func .= System::admin()->SpeedConfirmJs('Удалить', '$(\'#jqueryuitable\').table(\'deleteRow\', ' . $id . ');', 'images/admin/delete.png', 'Уверены, что хотите удалить эту новость?');
            $title = '<b>' . System::admin()->Link($title, ADMIN_FILE . '?exe=news&a=edit&id=' . $id . '&back=' . $back) . '</b>';
        }
        $table->AddRow($id, $title, TimeRender(SafeDB($news['date'], 11, int)), SafeDB($news['hit_counter'], 11, int), $allowComments ? $comments : 'Обсуждение закрыто', $view, $status, $func);
    }
    if (isset($_GET['ajax'])) {
        echo $table->GetOptions();
        exit;
    } else {
        $table->AddTable('Новости');
    }
}
function AdminGalleryMainFunc()
{
    global $edit_images, $GalleryDir, $ThumbsDir;
    UseScript('colorbox?theme=admin');
    $back = SaveRefererUrl();
    if (isset($_GET['cat']) && $_GET['cat'] > -1) {
        $cat = SafeEnv($_GET['cat'], 11, int);
        $where = "`cat_id`='{$cat}'";
    } else {
        $cat = -1;
        $where = "";
    }
    $data = AdminGalleryGetTree()->GetCatsData($cat, true);
    System::site()->DataAdd($data, -1, 'Все изображения', $cat == -1);
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 11, int);
        $page_param = '&page=' . SafeDB($_GET['page'], 11, int);
    } else {
        $page = 1;
        $page_param = '';
    }
    AddCenterBox('Фото');
    System::admin()->AddJS(Indent('
		GallerySelectCat = function(){
			Admin.LoadPage("' . ADMIN_FILE . '?exe=gallery&cat="+$("#gallery-cat").val());
		}
	'));
    $text = '<div style="margin-bottom: 10px;">Категория: ' . System::site()->Select('cat', $data, false, 'id="gallery-cat" onchange="GallerySelectCat();"');
    if ($cat < 0) {
        $text .= ' (Для сортировки изображений, выберите категорию)';
    }
    $text .= '</div>';
    AddText($text);
    $images = System::database()->Select('gallery', $where);
    $count_images = count($images) - 1;
    SortArray($images, 'order');
    if (count($images) > System::config('gallery/images_on_page')) {
        $navigator = new Navigation($page);
        $navigator->GenNavigationMenu($images, System::config('gallery/images_on_page'), ADMIN_FILE . '?exe=gallery' . ($cat > 0 ? '&cat=' . $cat : ''));
        $nav = true;
    } else {
        $nav = false;
    }
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    $text .= '<tr>' . ($cat > 0 ? '<th>Сортировка</th>' : '') . '<th>Изображение</th><th>Просмотров</th><th>Видят</th><th>Статус</th><th>Функции</th></tr>';
    foreach ($images as $i => $img) {
        $id = SafeDB($img['id'], 11, int);
        $title = SafeDB($img['title'], 255, str);
        if ($title == '') {
            $title = 'Изображение ' . $id;
        }
        if (System::config('gallery/show_thumbs')) {
            $img_filename = SafeDB($img['file'], 255, str);
            $size = FormatFileSize(filesize($GalleryDir . $img_filename));
            $asize = getimagesize($GalleryDir . $img_filename);
            $asize = $asize[0] . 'x' . $asize[1];
            $thumb = '<div style="margin: 5px 0;"><a href="' . $GalleryDir . $img_filename . '" target="_blank" class="colorbox">' . '<img title="' . $title . '" src="' . $ThumbsDir . $img_filename . (isset($_GET['update']) && $_GET['update'] == $id ? '?' . GenRandomString(5) : '') . '"></a></div>' . "({$asize}, {$size})";
        } else {
            $thumb = '';
        }
        $hits = SafeDB($img['hits'], 11, int);
        $st = $img['show'] == '1' ? 'Вкл.' : 'Выкл.';
        $func = '-';
        $move_menu = '';
        $link_go = Ufu('index.php?name=gallery&op=view&img=' . $id . '&cat=' . SafeDB($img['cat_id'], 11, int), 'gallery/{cat}/{img}/');
        $func = '';
        $func .= System::admin()->SpeedButton('Перейти к странице на сайте', $link_go, 'images/link_go.png', false, false, 'target="_blank"');
        if ($edit_images) {
            $edit_url = ADMIN_FILE . '?exe=gallery&a=editor&id=' . $id . '&back=' . $back;
            $title = '<b>' . System::admin()->Link($title, $edit_url) . '</b>';
            $hits .= '&nbsp;' . System::admin()->SpeedConfirm('Обнулить счётчик просмотров', ADMIN_FILE . '?exe=gallery&a=resethits&id=' . $id . '&back=' . $back, 'images/admin/arrow_in.png', 'Сбросить счётчик просмотров?');
            $st = System::admin()->SpeedStatus('Вкл.', 'Выкл.', ADMIN_FILE . '?exe=gallery&a=changestatus&id=' . $id, $img['show'] == '1');
            $func .= System::admin()->SpeedButton('Редактировать', $edit_url, 'images/admin/edit.png');
            $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=gallery&a=delete&id=' . $id . '&back=' . $back, 'images/admin/delete.png', 'Удалить изображение?');
            $func .= '<div style="margin-top: 4px;">';
            $func .= System::admin()->SpeedButton('Повернуть влево на 90°', ADMIN_FILE . '?exe=gallery&a=rotate&turn=left&id=' . $id . '&back=' . $back, 'images/admin/layer-rotate-left.png');
            $func .= System::admin()->SpeedButton('Повернуть вправо на 90° ', ADMIN_FILE . '?exe=gallery&a=rotate&turn=right&id=' . $id . '&back=' . $back, 'images/admin/layer-rotate-right.png');
            $func .= System::admin()->SpeedButton('Обновить эскиз', ADMIN_FILE . '?exe=gallery&a=refreshthumb&id=' . $id . '&back=' . $back, 'images/admin/refresh.png');
            $func .= '</div>';
            if ($count_images == 0) {
                // Единственный элемент в списке
                $move_menu .= ' - ';
            } else {
                if ($i != $count_images) {
                    // Первый элемент
                    $move_menu .= System::admin()->SpeedButton('Вниз', ADMIN_FILE . '?exe=gallery&a=move&to=down&id=' . $id . '&cat=' . $cat . $page_param, 'images/admin/down.png');
                }
                if ($i != 0) {
                    // Последний элемент
                    $move_menu .= System::admin()->SpeedButton('Вверх', ADMIN_FILE . '?exe=gallery&a=move&to=up&id=' . $id . '&cat=' . $cat . $page_param, 'images/admin/up.png');
                }
            }
        }
        $text .= Indent('
			<tr>
				' . ($cat > 0 ? '<td>' . $move_menu . '</td>' : '') . '
				<td>' . $title . $thumb . '</td>
				<td>' . $hits . '</td>
				<td>' . ViewLevelToStr(SafeDB($img['view'], 1, int)) . '</td>
				<td>' . $st . '</td>
				<td>' . $func . '</td>
			</tr>
		');
    }
    $text .= '</table>';
    AddText($text);
    if ($nav) {
        AddNavigation();
    }
}
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 AdminForumGetElement(&$forum, &$forums, $level = 1)
{
    global $forum_lang;
    $id = SafeDB($forum['id'], 11, int);
    $editlink = ADMIN_FILE . '?exe=forum&a=forum_editor&id=' . $id;
    $func = '';
    $func .= System::admin()->SpeedButton('Добавить форум', ADMIN_FILE . '?exe=forum&a=forum_editor&parent=' . $id, 'images/admin/folder_add.png');
    $func .= '&nbsp;';
    $func .= System::admin()->SpeedStatus('Выключить', 'Включить', ADMIN_FILE . '?exe=forum&a=changestatus&id=' . $id, $forum['status'] == '1');
    $func .= '&nbsp;';
    $func .= System::admin()->SpeedButton('Редактировать', $editlink, 'images/admin/edit.png');
    $func .= System::admin()->SpeedConfirmJs('Удалить', '$(\'#tree_container\').treeview(\'deleteNode\', ' . $id . ');', 'images/admin/delete.png', 'Все дочерние форумы, темы и сообщения так-же будут удалены. Уверены что хотите удалить?');
    $view = ViewLevelToStr(SafeDB($forum['view'], 1, int));
    $description = SafeDB($forum['description'], 255, str);
    if (trim($description) == '') {
        $description = 'Нет описания.';
    }
    $topics = SafeDB($forum['topics'], 11, int);
    $posts = SafeDB($forum['posts'], 11, int);
    $discussion = $forum['close_topic'] == 1 ? $forum_lang['close_for_discussion_admin'] : $forum_lang['on_for_discussion'];
    $link_go = Ufu('index.php?name=forum&op=showforum&forum=' . $id, 'forum/{forum}/');
    $link_go = "<a href=\"{$link_go}\" target=\"_blank\">/{$link_go}</a>";
    $info = "{$description}<br>\n\t\t<b>Тем</b>: {$topics}<br>\n\t\t<b>Ответов</b>: {$posts}<br>\n\t\t<b>Видят</b>: {$view}<br>\n\t\t<b>Обсуждение</b>: {$discussion}<br>\n\t\t<b>Адрес</b>: {$link_go}\n\t\t";
    if ($level == 1) {
        $title = System::admin()->Link(SafeDB($forum['title'], 255, str), $editlink, '', true, 'style="color: #3300FF; font-weight: bold;"');
    } elseif ($level == 2) {
        $title = System::admin()->Link(SafeDB($forum['title'], 255, str), $editlink, '', true, 'style="color: #0080FF; font-weight: bold;"');
    } else {
        $title = '<b>' . System::admin()->Link(SafeDB($forum['title'], 255, str), $editlink) . '</b>';
    }
    $element = array('id' => $id, 'icon' => 'images/logo16.png', 'title' => $title, 'info' => $info, 'func' => $func, 'isnode' => isset($forums[$id]));
    if ($forum['parent_id'] == 0) {
        $element['opened'] = true;
        $element['childs'] = array();
    } else {
        $element['child_url'] = 'admin.php?exe=forum&a=ajaxtree&parent=' . $id;
    }
    return $element;
}
function AdminFormsMain()
{
    $forms = System::database()->Select('forms', '');
    SortArray($forms, 'new_answ', true);
    $text = '';
    $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 ($forms as $form) {
        $id = SafeDB($form['id'], 11, int);
        $vi = ViewLevelToStr(SafeDB($form['view'], 1, int));
        $status = System::admin()->SpeedStatus('Выключить', 'Включить', ADMIN_FILE . '?exe=forms&a=changestatus&id=' . $id, $form['active'], 'images/bullet_green.png', 'images/bullet_red.png');
        $answ = SafeDB($form['answ'], 11, int) > 0 ? '<b>' . SafeDB($form['answ'], 11, int) . '</b> / <a href="' . ADMIN_FILE . '?exe=forms&a=posts&id=' . $id . '">Просмотр</a>' : SafeDB($form['answ'], 11, int);
        $new_answ = SafeDB($form['new_answ'], 11, int) > 0 ? '<b>' . SafeDB($form['new_answ'], 11, int) . '</b> / <a href="' . ADMIN_FILE . '?exe=forms&a=newposts&id=' . $id . '">Просмотр</a>' : SafeDB($form['new_answ'], 11, int);
        $link_go = Ufu('index.php?name=forms&formlink=' . SafeDB($form['link'], 255, str), 'forms:form');
        $func = '';
        $func .= System::admin()->SpeedButton('Перейти к странице на сайте', $link_go, 'images/link_go.png', false, false, 'target="_blank"');
        $func .= System::admin()->SpeedButton('Редактировать форму', ADMIN_FILE . '?exe=forms&a=edit&id=' . $id, 'images/admin/edit.png');
        $func .= System::admin()->SpeedButton('Редактировать поля', ADMIN_FILE . '?exe=forms&a=fields&id=' . $id, 'images/admin/config.png');
        $func .= System::admin()->SpeedConfirm('Удалить форму', ADMIN_FILE . '?exe=forms&a=del&id=' . $id, 'images/admin/delete.png', 'Удалить форму?');
        $text .= '<tr>
		<td><b>' . System::admin()->Link(SafeDB($form['hname'], 255, str), ADMIN_FILE . '?exe=forms&a=edit&id=' . $id) . '</a></b></td>
		<td>' . $new_answ . '</td>
		<td>' . $answ . '</td>
		<td>' . SafeDB($form['numfields'], 11, int) . '</td>
		<td>' . $vi . '</td>
		<td>' . $status . '</td>
		<td>' . $func . '</td>
		</tr>
		';
    }
    $text .= '</table><br />';
    AddTextBox('Web-формы', $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;
    }
}
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();
    }
}
function AdminPollsMainFunc()
{
    global $editpolls;
    $polls = System::database()->Select('polls');
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable"><tr>';
    $text .= '<th>Опрос</th><th>Всего проголосовало</th><th>Комментарии</th><th>Доступ</th><th>Статус</th><th>Функции</th></tr>';
    foreach ($polls as $poll) {
        $pid = SafeDB($poll['id'], 11, int);
        if ($poll['active'] == '1') {
            $active = '<font color="#008000">Вкл.</font></a>';
        } else {
            $active = '<font color="#FF0000">Выкл.</font>';
        }
        if ($editpolls) {
            $active = System::admin()->SpeedStatus('Вкл.', 'Выкл.', ADMIN_FILE . '?exe=polls&a=changestatus&id=' . $pid, $poll['active'] == '1');
        }
        $answers = unserialize($poll['answers']);
        $c = count($answers);
        $num_voices = 0;
        for ($i = 0; $i < $c; $i++) {
            $num_voices += SafeDB($answers[$i][2], 11, int);
        }
        $link_go = Ufu('index.php?name=polls&op=viewpoll&poll_id=' . $pid, 'polls/{poll_id}/');
        $func = '';
        $func .= System::admin()->SpeedButton('Перейти к странице на сайте', $link_go, 'images/link_go.png', false, false, 'target="_blank"');
        if ($editpolls) {
            $func .= System::admin()->SpeedButton('Редактировать', ADMIN_FILE . '?exe=polls&a=editor&id=' . $pid, 'images/admin/edit.png');
            $func .= System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=polls&a=delete&id=' . $pid, 'images/admin/delete.png', 'Удалить опрос?');
        }
        $text .= Indent('
		<tr>
			<td>
				<b>' . System::admin()->Link(SafeDB($poll['question'], 255, str), ADMIN_FILE . '?exe=polls&a=editor&id=' . $pid) . '</b></td>
			<td>' . $num_voices . '</td>
			<td>' . SafeDB($poll['com_counter'], 11, int) . '</td>
			<td>' . ViewLevelToStr($poll['view']) . '</td>
			<td>' . $active . '</td>
			<td>' . $func . '</td>
		</tr>
		');
    }
    $text .= '</table>';
    AddTextBox('Опросы', $text);
}