function IndexForumEditTopics()
{
    global $forum_lang;
    if (!System::user()->isAdmin()) {
        System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $forum_lang['error_no_right_edit'] . '.</p>');
        return;
    }
    if (!isset($_POST['topics'])) {
        System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $forum_lang['error_no_topics'] . '</p><br><a href="javascript:history.go(-1)">' . System::site()->Button('Назад') . '</a>');
        return;
    }
    if (isset($_GET['ok']) && $_GET['ok'] == '1') {
        $topics_ids = SafeEnv(explode(',', $_POST['topics']), 11, int);
        $back_url = $_POST['backurl'];
        if (isset($_GET['back'])) {
            $back_url = GetRefererUrl($_GET['back']);
        }
        $moderation_result = ForumModerationTopics($_GET['edit'], $topics_ids, true);
        if ($moderation_result !== false) {
            $text = $moderation_result . '<br><br><b><a href="' . $back_url . '">' . $forum_lang['return_read'] . '</a></b>';
            System::site()->AddTextBox($forum_lang['executed'], $text);
        }
    } else {
        $topics_ids = array();
        foreach (array_keys($_POST['topics']) as $topic_id) {
            $topics_ids[] = SafeEnv($topic_id, 11, int);
        }
        $form_url = 'index.php?name=forum&op=edit_topics&edit=' . SafeDB($_POST['do'], 255, str) . '&ok=1';
        if (isset($_GET['back'])) {
            $form_url .= '&back=' . SafeDB($_GET['back'], 10, str);
        }
        $moderation_content = ForumModerationTopics($_POST['do'], $topics_ids, false);
        if ($moderation_content !== false) {
            $text = System::site()->FormOpen($form_url) . System::site()->Hidden('topics', implode(',', $topics_ids)) . System::site()->Hidden('backurl', $_SERVER['HTTP_REFERER']) . $moderation_content . System::site()->Button($forum_lang['back'], 'onclick="history.go(-1);"') . System::site()->Submit($forum_lang['execute']);
            System::site()->AddTextBox('Модерация тем', $text);
        }
    }
}
function AcAddRetrofitting()
{
    if (RequestMethod() != 'POST') {
        return;
    }
    $back_url = '';
    if (!AdminConfigPlugins()) {
        $access_config = 'System::config(';
        $back_url = ADMIN_FILE . '?exe=config_admin&a=view_all&saveok';
    } else {
        $access_config = 'System::plug_config(';
        $back_url = ADMIN_FILE . '?exe=config_admin&a=view_all_plugins&plugins=1&saveok';
    }
    System::database()->Select(AdminConfigGroupTable());
    $groups = array();
    while ($g = System::database()->FetchRow()) {
        $groups[$g['id']] = $g['name'];
    }
    $group = SafeEnv($_POST['group'], 11, int);
    $hname = SafeEnv($_POST['hname'], 255, str, true);
    $name = SafeEnv($_POST['name'], 255, str);
    $value = SafeEnv($_POST['value'], 0, str);
    $description = SafeEnv($_POST['description'], 255, str, true);
    if (isset($_POST['visible'])) {
        $visible = '1';
    } else {
        $visible = '0';
    }
    if (isset($_POST['autoload'])) {
        $autoload = '1';
    } else {
        $autoload = '0';
    }
    // генерируем kind
    $kind = '';
    $values = '';
    $savefunc = '';
    $type = '';
    if ($visible == '1') {
        $kind .= SafeEnv($_POST['control'], 25, str);
        $width = SafeEnv($_POST['cwidth'], 14, str);
        $height = SafeEnv($_POST['cheight'], 14, str);
        $cols = SafeEnv($_POST['ccols'], 11, int);
        if ($width != '') {
            $kind .= ':w' . $width;
        }
        if ($height != '') {
            $kind .= ':h' . $height;
        }
        if ($cols > 1) {
            $kind .= ':c' . $cols;
        }
        $getfunc = SafeEnv($_POST['valuesfunc'], 255, str);
        if ($getfunc == '' || !function_exists(CONF_GET_PREFIX . $getfunc)) {
            $values = SafeEnv($_POST['values'], 0, str);
        } else {
            $values = 'function:' . $getfunc;
        }
    }
    if (function_exists(CONF_SAVE_PREFIX . $_POST['savefunc'])) {
        $savefunc = SafeEnv($_POST['savefunc'], 255, str);
    } else {
        $savefunc = '';
    }
    $maxlenght = SafeEnv($_POST['maxlength'], 11, int);
    $type = SafeEnv($_POST['datatype'], 255, str);
    if (isset($_POST['striptags'])) {
        $striptags = 'true';
    } else {
        $striptags = 'false';
    }
    $type = $maxlenght . ',' . $type . ',' . $striptags;
    // Сохраняем
    $to_db = Values('', $group, $name, $value, $visible, $hname, $description, $kind, $values, $savefunc, $type, $autoload);
    if (isset($_GET['id'])) {
        $id = SafeEnv($_GET['id'], 11, str);
        System::database()->Update(AdminConfigConfigTable(), $to_db, "`id`='{$id}'", true);
        Audit('Управление настройками: Изменение настройки "' . $hname . '(' . $name . ')" в "' . AdminConfigConfigTable() . '"');
        if (isset($_REQUEST['back'])) {
            GoRefererUrl($_REQUEST['back']);
        } else {
            GO($back_url);
        }
    } else {
        if (isset($_REQUEST['back'])) {
            $back_url = GetRefererUrl($_REQUEST['back']);
        }
        System::database()->Insert(AdminConfigConfigTable(), $to_db);
        Audit('Управление настройками: Добавление настройки "' . $hname . '(' . $name . ')" в "' . AdminConfigConfigTable() . '"');
        AddTextBox('Подтверждение', 'Новая настройка успешно добавлена.<br />Для доступа к значению настройки используйте код:<br /><br />' . $access_config . "<span style=\"color: #008200\">'" . $groups[$group] . '/' . "" . $name . "'</span>)" . '<br><br>' . System::admin()->SpeedButton('Назад', $back_url, '', true, true));
    }
}
function AdminGalleryImageRotate()
{
    global $GalleryDir, $ThumbsDir;
    $turn = $_GET['turn'];
    $id = SafeEnv($_GET['id'], 11, int);
    $angle = 0;
    if ($turn == 'left') {
        $angle = 90;
    } else {
        $angle = 270;
    }
    System::database()->Select('gallery', "`id`='{$id}'");
    $img = System::database()->FetchRow();
    $file_name = $img['file'];
    $file = $GalleryDir . $file_name;
    $thumb = $ThumbsDir . $file_name;
    // Поворачиваем изображение
    $pic = new TPicture($file);
    $pic->Rotate($angle);
    $pic->SaveToFile($file);
    // Обновляем эскиз
    if (is_file($thumb)) {
        unlink($thumb);
    }
    CreateThumb($file, $thumb, System::config('gallery/thumb_max_width'), System::config('gallery/thumb_max_height'));
    Audit('Фотогалерея: Поворот изображения ' . ($turn == 'left' ? 'влево' : 'вправо') . ' "' . $img['title'] . '" (id: ' . $img['id'] . ')');
    $back = new Url(GetRefererUrl($_REQUEST['back']));
    $back['update'] = SafeDB($_GET['id'], 11, int);
    // Добавляем / изменяем параметр update
    GO($back);
}
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 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']);
}