function AdminBlocksSave($a)
{
    $block_config = '';
    $editsave = System::config('blocks_dir') . SafeEnv($_POST['type'], 255, str) . '/editsave.php';
    if (file_exists($editsave)) {
        include_once $editsave;
        // Что-то записывает в $block_config
    }
    VisibilityConditionsAdminSave($showin, $extra_uri);
    $b_v = ViewLevelToInt($_POST['view']);
    $b_en = EnToInt($_POST['enabled']);
    if (isset($_GET['id'])) {
        $id = SafeEnv($_GET['id'], 11, int);
    } else {
        $id = 0;
    }
    $place = GetPlace(SafeEnv($_POST['position'][0], 1, str), $id);
    // FIXME: Ниже блок вытаскивается, тогда можно узнать его place без лишнего запроса
    if ($id != 0) {
        $block = System::database()->Select('blocks', "`id`='{$id}'");
        $block_pos = SafeEnv($block[0]['position'], 1, str);
    }
    $vals = Values('', SafeEnv($_POST['title'], 255, str), SafeEnv($_POST['type'], 255, str), $place, '', '1', $block_config, SafeEnv($_POST['template'], 255, str), SafeEnv($_POST['position'][0], 1, str), $b_v, $b_en, $showin, $extra_uri);
    if ($a == 'newsave') {
        System::database()->Insert('blocks', $vals);
        Audit('Блока: Добавление блока "' . $_POST['title'] . '"');
    } elseif ($a == 'update') {
        System::database()->Update('blocks', $vals, "`id`='" . $id . "'", true);
        Audit('Блока: Изменение блока "' . $_POST['title'] . '"');
        if ($block_pos != $_POST['position'][0]) {
            // Пересчитываем все place в предыдущем position
            $blocks = System::database()->Select('blocks', "`position`='" . $block_pos . "'");
            if (count($blocks) > 0) {
                usort($blocks, 'AdminBlocksSort');
                foreach ($blocks as $i => $b) {
                    System::database()->Update('blocks', "`place`='{$i}'", "`id`='" . SafeEnv($b['id'], 11, int) . "'");
                }
            }
        }
    }
    GO(ADMIN_FILE . '?exe=blocks');
}
function AdminExtensionsConfigSave()
{
    $post = SafeR('view', 255, str) + SafeR('name, theme', 255, str) + SafeR('enabled', 3, onoff);
    $post['view'] = ViewLevelToInt($post['view']);
    System::database()->Update('modules', MakeSet($post), "`folder`='" . SafeEnv($_GET['name'], 255, str) . "'");
    Audit('Расширения: Изменение настроек модуля "' . $_GET['name'] . '"');
    GO(ADMIN_FILE . '?exe=extensions');
}
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 AdminNewsSave()
{
    global $news_access_editnews;
    if (!$news_access_editnews) {
        System::admin()->AccessDenied();
    }
    $author = SafeEnv(System::user()->Get('u_name'), 255, str);
    // Получаем параметры
    $topic_id = SafeEnv($_POST['topic_id'], 11, int);
    $title = SafeEnv($_POST['title'], 255, str);
    // Модуль SEO
    $seo_title = SafeEnv($_POST['seo_title'], 255, str);
    $seo_keywords = SafeEnv($_POST['seo_keywords'], 255, str);
    $seo_description = SafeEnv($_POST['seo_description'], 255, str);
    //
    $allow_comments = EnToInt($_POST['acomments']);
    $icon = SafeEnv($_POST['icon'], 255, str);
    $start_text = SafeEnv($_POST['shorttext'], 0, str, false);
    $end_text = SafeEnv($_POST['continuation'], 0, str, false);
    $auto_br = EnToInt($_POST['auto_br']);
    $view = ViewLevelToInt(SafeEnv($_POST['view'], 15, str));
    $enabled = EnToInt($_POST['enabled']);
    $img_view = SafeEnv($_POST['img_view'], 1, int);
    $public_date = $_POST['public_date'];
    $public_time = $_POST['public_time'];
    $public = strtotime(str_replace('.', '-', $public_date) . ' ' . $public_time);
    $comments_counter = 0;
    $hit_counter = 0;
    if (isset($_GET['id'])) {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('news', "`id`='{$id}'");
        $news = System::database()->FetchRow();
        $author = SafeEnv($news['author'], 255, str);
        $comments_counter = SafeEnv($news['comments_counter'], 11, int);
        $hit_counter = SafeEnv($news['hit_counter'], 11, int);
        if ($topic_id != $news['topic_id'] && $news['enabled'] == 1) {
            CalcNewsCounter($news['topic_id'], false);
            CalcNewsCounter($topic_id, true);
        }
        if ($enabled != $news['enabled']) {
            CalcNewsCounter($topic_id, $enabled);
        }
    }
    $vals = Values('', $title, $public, $author, $topic_id, $allow_comments, $icon, $start_text, $end_text, $auto_br, $comments_counter, $hit_counter, $view, $enabled, $img_view, $seo_title, $seo_keywords, $seo_description);
    if (isset($id)) {
        System::database()->Update('news', $vals, "`id`='{$id}'", true);
        Audit('Редактирование новости "' . $title . '" (id: ' . $id . ')');
    } else {
        System::database()->Insert('news', $vals);
        CalcNewsCounter($topic_id, true);
        Audit('Новости: Добавление новости "' . $title . '"');
    }
    AdminNewsClearBlockCache();
    if (isset($_REQUEST['back'])) {
        GoRefererUrl($_REQUEST['back']);
    } else {
        GO(ADMIN_FILE . '?exe=news');
    }
}
function AdminForumSave()
{
    $f_title = SafeDB($_POST['title'], 255, str);
    $f_view = ViewLevelToInt($_POST['view']);
    $f_status = EnToInt($_POST['status']);
    $f_admin_theme_add = 0;
    $f_new_message_email = 0;
    $f_no_link_guest = 0;
    $rang_access = 0;
    $rang_message = 0;
    $close_topic = 0;
    $rang_add_theme = 0;
    if (isset($_POST['admin_theme_add'])) {
        $f_admin_theme_add = SafeEnv($_POST['admin_theme_add'], 1, int);
    }
    if (isset($_POST['new_message_email'])) {
        $f_new_message_email = SafeEnv($_POST['new_message_email'], 1, int);
    }
    if (isset($_POST['no_link_guest'])) {
        $f_no_link_guest = SafeEnv($_POST['no_link_guest'], 1, int);
    }
    if (isset($_POST['rang_access'])) {
        $rang_access = SafeEnv($_POST['rang_access'], 11, int);
    }
    if (isset($_POST['rang_message'])) {
        $rang_message = SafeEnv($_POST['rang_message'], 11, int);
    }
    if (isset($_POST['rang_add_theme'])) {
        $rang_add_theme = SafeEnv($_POST['rang_add_theme'], 11, int);
    }
    if (isset($_POST['close_topic'])) {
        $close_topic = SafeEnv($_POST['close_topic'], 1, int);
    }
    if (isset($_POST['desc'])) {
        $f_desc = SafeEnv($_POST['desc'], 0, str);
    } else {
        $f_desc = '';
    }
    if (isset($_POST['parent_id'])) {
        $f_parent = SafeEnv($_POST['parent_id'], 11, int);
    } else {
        $f_parent = '0';
    }
    if (isset($_POST['sub_id'])) {
        $f_parent2 = SafeEnv($_POST['sub_id'], 11, int);
        $f_parent = $f_parent2;
    } else {
        $f_parent2 = '0';
    }
    if (isset($_GET['id'])) {
        // Редактирование
        $id = SafeEnv($_GET['id'], 11, int);
        $set = "`parent_id`='{$f_parent}',`title`='{$f_title}',`description`='{$f_desc}',`view`='{$f_view}',`status`='{$f_status}',`admin_theme_add`='{$f_admin_theme_add}',`no_link_guest`='{$f_no_link_guest}',`new_message_email`='{$f_new_message_email}',`rang_access`='{$rang_access}',`rang_message`='{$rang_message}',`rang_add_theme`='{$rang_add_theme}',`close_topic`='{$close_topic}'";
        System::database()->Update('forums', $set, "`id`='{$id}'");
        Audit('Форум: Редактирование форума "' . $f_title . '"');
    } else {
        // Добавление
        $order = AdminForumGetOrder('0');
        $values = "'','{$f_parent}','{$f_title}','{$f_desc}','0','0','0','0','','','0','{$order}','{$f_status}','{$f_view}','{$f_admin_theme_add}','{$f_no_link_guest}','{$f_new_message_email}', '{$rang_access}', '{$rang_message}', '{$rang_add_theme}','{$close_topic}'";
        System::database()->Insert('forums', $values);
        Audit('Форум: Добавление форума "' . $f_title . '"');
    }
    ForumCacheClear();
    GO(ADMIN_FILE . '?exe=forum');
}
function AdminArticlesSaveArticle($action)
{
    global $editarticles;
    if (!$editarticles) {
        System::admin()->AccessDenied();
    }
    $cat_id = SafeEnv($_POST['category'], 11, int);
    if (in_array($cat_id, AdminArticlesGetTree()->GetAllChildId(0)) === false || $cat_id == 0) {
        GO(ADMIN_FILE . '?exe=articles');
    }
    $author = SafeEnv($_POST['author'], 200, str, true);
    $email = SafeEnv($_POST['email'], 50, str, true);
    $www = SafeEnv(Url($_POST['www']), 250, str, true);
    $title = SafeEnv($_POST['title'], 255, str);
    $description = SafeEnv($_POST['description'], 0, str, false, true, false);
    $article = SafeEnv($_POST['article'], 0, str, false, true, false);
    // Загружаем изображение
    $Error = false;
    $image = LoadImage('up_image', System::config('articles/images_dir'), System::config('articles/images_dir') . 'thumbs', System::config('articles/thumb_max_width'), System::config('articles/thumb_max_height'), $_POST['image'], $Error);
    $auto_br_desc = EnToInt($_POST['auto_br_desc']);
    $auto_br_article = EnToInt($_POST['auto_br_article']);
    $allow_comments = EnToInt($_POST['allow_comments']);
    $allow_votes = EnToInt($_POST['allow_votes']);
    $view = ViewLevelToInt($_POST['view']);
    $active = EnToInt($_POST['active']);
    //Модуль SEO
    $seo_title = SafeEnv($_POST['seo_title'], 255, str);
    $seo_keywords = SafeEnv($_POST['seo_keywords'], 255, str);
    $seo_description = SafeEnv($_POST['seo_description'], 255, str);
    //
    $form = SafeEnv($_POST['form'], 11, int);
    $product_id = SafeEnv($_POST['product_id'], 255, str);
    if ('add' == $action) {
        $values = Values('', $cat_id, time(), $author, $email, $www, $title, $description, $article, $image, 0, $allow_comments, 0, $allow_votes, 0, 0, $active, $view, $auto_br_desc, $auto_br_article, $seo_title, $seo_keywords, $seo_description, $form, $product_id);
        System::database()->Insert('articles', $values);
        if ($active) {
            AdminArticlesGetTree()->CalcFileCounter($cat_id, true);
        }
        Audit('Статьи: Добавление статьи "' . $title . '"');
    } elseif ('save' == $action) {
        $set = "`cat_id`='{$cat_id}',`author`='{$author}',`email`='{$email}',`www`='{$www}',`title`='{$title}',`description`='{$description}',`article`='{$article}',`image`='{$image}',`allow_comments`='{$allow_comments}',`allow_votes`='{$allow_votes}',`view`='{$view}',`active`='{$active}',`auto_br_desc`='{$auto_br_desc}',`auto_br_article`='{$auto_br_article}',`seo_title`='{$seo_title}',`seo_keywords`='{$seo_keywords}',`seo_description`='{$seo_description}',`form`='{$form}',`product_id`='{$product_id}'";
        $id = SafeEnv($_GET['id'], 11, int);
        $r = System::database()->Select('articles', "`id`='{$id}'");
        if ($r[0]['cat_id'] != $cat_id && $r[0]['active'] == '1') {
            // Если переместили в другой раздел
            AdminArticlesGetTree()->CalcFileCounter($r[0]['cat_id'], false);
            AdminArticlesGetTree()->CalcFileCounter($cat_id, true);
        }
        if ($r[0]['active'] != $active) {
            // Выключили / Включили
            if ($active == 0) {
                AdminArticlesGetTree()->CalcFileCounter($cat_id, false);
            } else {
                AdminArticlesGetTree()->CalcFileCounter($cat_id, true);
            }
        }
        System::database()->Update('articles', $set, "`id`='{$id}'");
        Audit('Статьи: Изменение статьи "' . $title . '"');
    }
    if ($Error) {
        AddTextBox('Ошибка', '<p align="center">Неправильный формат файла. Можно загружать только изображения формата GIF, JPEG или PNG. Остальные изменения сохранены.</p><br><a href="' . GetRefererUrl($_REQUEST['back']) . '" class="button">Далее</a>');
        return;
    }
    GoRefererUrl($_REQUEST['back']);
}
function AdminFormsSave()
{
    $hname = SafeEnv($_POST['hname'], 255, str);
    $link = SafeEnv($_POST['link'], 255, str);
    if ($link == '') {
        $link = SafeEnv(UfuLink($_POST['hname']), 255, str);
    }
    $name = SafeEnv($_POST['name'], 255, str);
    $desc = SafeEnv($_POST['desc'], 0, str);
    $form_action = SafeEnv($_POST['action'], 250, str);
    $email = SafeEnv($_POST['email'], 50, str);
    $msg_ok = SafeEnv($_POST['send_ok_msg'], 0, str);
    $view = ViewLevelToInt($_POST['view']);
    $active = EnToInt($_POST['active']);
    if (isset($_GET['id'])) {
        $set = "`hname`='{$hname}',`link`='{$link}',`name`='{$name}',`desc`='{$desc}',`view`='{$view}',`active`='{$active}',`action`='{$form_action}',`email`='{$email}',`send_ok_msg`='{$msg_ok}'";
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Update('forms', $set, "`id`='{$id}'");
        Audit('Web-формы: Изменение формы "' . $name . '"');
        GO(ADMIN_FILE . '?exe=forms');
    } else {
        $form_data = serialize(array());
        $values = Values('', $hname, $name, $link, $desc, 0, 0, 0, $form_data, $active, $view, $form_action, $email, $msg_ok);
        System::database()->Insert('forms', $values);
        Audit('Web-формы: Добавление формы "' . $name . '"');
        GO(ADMIN_FILE . '?exe=forms');
    }
}
function AdminSiteMessagesSave()
{
    $title = SafeEnv($_POST['title'], 250, str);
    $view_title = EnToInt($_POST['vtitle']);
    $text = SafeEnv($_POST['text'], 0, str);
    $time = SafeEnv($_POST['time'], 3, int);
    $date = time();
    $view = ViewLevelToInt($_POST['view']);
    $active = EnToInt($_POST['enabled']);
    switch ($_POST['position']) {
        case 'top':
            $pos = '1';
            break;
        case 'bottom':
            $pos = '0';
            break;
        default:
            $pos = '1';
    }
    VisibilityConditionsAdminSave($showin, $extra_uri);
    //Записываем или обновляем данные в базе данных
    if (!isset($_GET['id'])) {
        $vals = "'','{$title}','{$text}','{$date}','{$time}','{$showin}','{$extra_uri}','{$pos}','{$view_title}','{$view}','{$active}'";
        System::database()->Insert('messages', $vals);
        Audit('Сообщения: Добавление нового сообщения "' . $title . '"');
    } else {
        $id = SafeEnv($_GET['id'], 11, int);
        if (!isset($_POST['resettime'])) {
            System::database()->Select('messages', "`id`='{$id}'");
            if (System::database()->NumRows() > 0) {
                $msg = System::database()->FetchRow();
                $date = $msg['date'];
            } else {
                $date = time();
            }
        }
        $vals = "'','{$title}','{$text}','{$date}','{$time}','{$showin}','{$extra_uri}','{$pos}','{$view_title}','{$view}','{$active}'";
        System::database()->Update('messages', $vals, "`id`='{$id}'", true);
        Audit('Сообщения: Изменение сообщения "' . $title . '"');
    }
    GO(ADMIN_FILE . '?exe=messages');
}
/**
 * Сохранение изменений категории
 * @return void
 */
function AdminPagesCatSave()
{
    $parent_id = SafeEnv($_POST['parent_id'], 11, int);
    $title = SafeEnv($_POST['title'], 255, str);
    $link = SafeEnv(UfuLink($_POST['title']), 255, str);
    $view = ViewLevelToInt($_POST['view']);
    $enabled = EnToInt($_POST['enabled']);
    $showinmenu = EnToInt($_POST['showinmenu']);
    if (isset($_GET['id'])) {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('pages', "`id`='" . $id . "'");
        $page = System::database()->FetchRow();
        $order = SafeDB($page['order'], 11, int);
    } else {
        $order = AdminPagesNewOrder($parent_id);
    }
    $values = Values('', $parent_id, $title, '', '', time(), time(), '0', '0', '', $link, $view, $enabled, '', '', '', 'cat', $order, $showinmenu);
    if (isset($_GET['id'])) {
        // Редатирование
        System::database()->Update('pages', $values, "`id`='" . $id . "'", true);
        Audit('Страницы: Изменение категории "' . $title . '"');
    } else {
        System::database()->Insert('pages', $values);
        Audit('Страницы: Добавление категории "' . $title . '"');
    }
    AdminPagesClearCache();
    GO(ADMIN_FILE . '?exe=pages');
}
function AdminDownloadsSaveFile($action)
{
    if ($_POST == array()) {
        AddTextBox('Ошибка', '<b>Внимание! Превышен максимальный размер POST данных. Изменения не сохранены.</b>');
        return;
    }
    $Error = '';
    if (!System::user()->CheckAccess2('downloads', 'edit_files')) {
        System::admin()->AccessDenied();
    }
    $category = SafeEnv($_POST['category'], 11, int);
    if (in_array($category, AdminDownloadsGetTree()->GetAllChildId(0)) === false || $category == 0) {
        GO(ADMIN_FILE . '?exe=downloads');
    }
    $title = SafeEnv($_POST['title'], 250, str);
    // Обрабатываем upload_file если загрузился файл
    $exts = explode(',', System::config('downloads/file_exts'));
    $exts2 = array();
    foreach ($exts as $ext) {
        $exts2[trim($ext)] = true;
    }
    $UploadErrors = array(0 => '', 1 => 'Размер файла превышен', 2 => 'Размер файла превышен', 3 => 'Файл загружен только частично', 4 => 'Файл не был загружен.', 6 => 'Не найдена папка для временных файлов на сервере', 7 => 'Ошибка во время записи на диск', 8 => 'Загрузка файла была прервана расширением PHP', 9 => 'Ошибка во время записи на диск');
    if ($_FILES['upload_file']['error'] == UPLOAD_ERR_OK) {
        if (isset($exts2[strtolower(GetFileExt($_FILES['upload_file']['name']))])) {
            // Загружаем файл
            $Dir = System::config('downloads/files_dir');
            $file_name = Translit($_FILES['upload_file']['name'], true);
            $ext = GetFileExt($file_name);
            $name = GetFileName($file_name, true);
            $i = 1;
            while (is_file($Dir . $file_name)) {
                $i++;
                $file_name = $name . '_' . $i . $ext;
            }
            $FileName = $Dir . $file_name;
            copy($_FILES['upload_file']['tmp_name'], $FileName);
            $url = SafeEnv($FileName, 255, str);
        } else {
            $url = SafeEnv($_POST['url'], 255, str);
        }
    } else {
        if ($_FILES['upload_file']['error'] != 4) {
            $Error = $UploadErrors[$_FILES['upload_file']['error']];
        }
        $url = SafeEnv($_POST['url'], 255, str);
    }
    if ($_POST['size'] > 0) {
        $file_size = SafeEnv($_POST['size'], 11, real);
        // Дробное число
        $size_type = SafeEnv($_POST['filesize_type'], 1, str);
    } elseif (file_exists($url)) {
        $file_size = filesize($url);
        $size_type = 'b';
    } elseif (file_exists(System::config('general/site_url') . $url)) {
        $file_size = filesize(System::config('general/site_url') . $url);
        $size_type = 'b';
    } else {
        $file_size = SafeEnv($_POST['size'], 11, int);
        $size_type = 'b';
    }
    $shortdesc = SafeEnv($_POST['shortdesc'], 0, str);
    $description = SafeEnv($_POST['description'], 0, str);
    // Загружаем изображение
    $ImageUploadError = false;
    $image = LoadImage('up_image', System::config('downloads/images_dir'), System::config('downloads/images_dir') . 'thumbs/', System::config('downloads/thumb_max_width'), System::config('downloads/thumb_max_height'), $_POST['image'], $ImageUploadError);
    $author = SafeEnv($_POST['author'], 50, str);
    $author_site = SafeEnv(Url($_POST['author_site']), 250, str);
    $author_email = SafeEnv($_POST['author_email'], 50, str);
    $file_ver = SafeEnv($_POST['version'], 250, str);
    $allow_comments = EnToInt($_POST['allow_comments']);
    $allow_votes = EnToInt($_POST['allow_votes']);
    $view = ViewLevelToInt($_POST['view']);
    $active = EnToInt($_POST['active']);
    if ('editfilesave' == $action) {
        //Здесь генерируем Set запрос
        $set = "title='{$title}',category='{$category}',size='{$file_size}',size_type='{$size_type}',url='{$url}',shortdesc='{$shortdesc}',description='{$description}',image='{$image}',author='{$author}',author_site='{$author_site}',author_email='{$author_email}',file_version='{$file_ver}',allow_comments='{$allow_comments}',allow_votes='{$allow_votes}',view='{$view}',active='{$active}'";
        $id = SafeEnv($_GET['id'], 11, int);
        $r = System::database()->Select('downloads', "`id`='{$id}'");
        if ($r[0]['category'] != $category && $r[0]['active'] == '1') {
            AdminDownloadsGetTree()->CalcFileCounter($r[0]['category'], false);
            AdminDownloadsGetTree()->CalcFileCounter($category, true);
        }
        if ($r[0]['active'] != $active) {
            // Выключили / Включили
            if ($active == 0) {
                AdminDownloadsGetTree()->CalcFileCounter($category, false);
            } else {
                AdminDownloadsGetTree()->CalcFileCounter($category, true);
            }
        }
        System::database()->Update('downloads', $set, "`id`='{$id}'");
        Audit('Архив файлов: Редактирование файла "' . $title . '"');
    } elseif ('addfilesave' == $action) {
        $values = Values('', $category, time(), $file_size, $size_type, $title, $url, $shortdesc, $description, $image, $author, $author_site, $author_email, $file_ver, $allow_comments, 0, $allow_votes, 0, 0, 0, $view, $active);
        System::database()->Insert('downloads', $values);
        Audit('Архив файлов: Добавление файла "' . $title . '"');
        if ($active) {
            AdminDownloadsGetTree()->CalcFileCounter($category, true);
        }
    }
    if ($ImageUploadError) {
        AddTextBox('Ошибка', '<p align="center">Неправильный формат файла. Можно загружать только изображения формата GIF, JPEG или PNG. Остальные изменения сохранены.</p><br><a href="' . GetRefererUrl($_REQUEST['back']) . '" class="button">Далее</a>');
        return;
    }
    if ($Error != '') {
        AddTextBox('Ошибка', '<p align="center">Не удалось загрузить файл, изменения сохранены. Ошибка: ' . $Error . '.</p><br><a href="' . GetRefererUrl($_REQUEST['back']) . '" class="button">Далее</a>');
        return;
    }
    GoRefererUrl($_REQUEST['back']);
}
function AdminPollsSave()
{
    global $editpolls;
    if (!$editpolls) {
        System::admin()->AccessDenied();
    }
    $poll = SafeEnv($_POST['poll'], 255, str);
    $desc = SafeEnv($_POST['desc'], 255, str);
    $showinblock = EnToInt($_POST['showinblock']);
    $multianswers = EnToInt($_POST['multianswers']);
    $allow_comments = EnToInt($_POST['allow_comments']);
    $active = EnToInt($_POST['active']);
    $view = ViewLevelToInt($_POST['view']);
    // Ответы
    $answer = SafeEnv($_POST['answer'], 255, str);
    $color = SafeEnv($_POST['color'], 8, str);
    $voices = SafeEnv($_POST['voices'], 11, int);
    $cnt = count($answer);
    $answers = array();
    for ($i = 0; $i < $cnt; $i++) {
        $answers[] = array($answer[$i], $color[$i], $voices[$i]);
    }
    $answers = serialize($answers);
    $answers = SafeEnv($answers, 0, str, false, true, false);
    if (isset($_GET['id'])) {
        //Редактирование
        $set = "`question`='{$poll}',`description`='{$desc}',`multianswers`='{$multianswers}',`answers`='{$answers}',`showinblock`='{$showinblock}',`allow_comments`='{$allow_comments}',`view`='{$view}',`active`='{$active}'";
        $poll_id = SafeEnv($_GET['id'], 11, int);
        System::database()->Update('polls', $set, "`id`='{$poll_id}'");
        Audit('Опросы: Изменение опроса "' . $poll . '"');
    } else {
        // Добавление
        $vals = Values('', $poll, $desc, time(), $multianswers, $answers, $showinblock, $allow_comments, '0', $view, $active);
        System::database()->Insert('polls', $vals);
        Audit('Опросы: Добавление опроса "' . $poll . '"');
    }
    GO(ADMIN_FILE . '?exe=polls');
}