/**
 * Записывает реферал в базу данных.
 * @param $referer
 */
function AuditWriteReferer($referer)
{
    if (trim($referer) != '' && !IsMainHost($referer)) {
        $referer = SafeEnv(Url($referer), 255, str);
        $count = 1;
        System::database()->Select('referers', "`referer`='{$referer}'");
        if (System::database()->NumRows() > 0) {
            $ref = System::database()->FetchRow();
            $count = SafeDB($ref['count'], 11, int);
            $count++;
            System::database()->Update('referers', "count='{$count}'", "`referer`='{$referer}'");
        } else {
            $values = Values('', $referer, $count);
            System::database()->Insert('referers', $values);
        }
    }
}
function IndexMailSubscribe()
{
    global $mail_selected;
    if (isset($_POST['topic_id'])) {
        $topic_id = SafeEnv($_POST['topic_id'], 11, int);
        if (!isset($_POST['mail_block_form'])) {
            GO(GetSiteUrl() . Ufu('index.php?name=mail&op=topics', 'mail/{op}/'));
        }
        $html = SafeEnv($_POST['html'], 1, int);
    } elseif (isset($_GET['topic_id'])) {
        $topic_id = SafeEnv($_GET['topic_id'], 11, int);
        $html = 1;
    } else {
        GO(GetSiteUrl() . Ufu('index.php?name=mail&op=topics', 'mail/{op}/'));
    }
    System::database()->Delete('mail_list', "`email`='{$mail_selected}' and `topic_id`='{$topic_id}'");
    if (System::user()->Auth) {
        $user_id = System::user()->Get('u_id');
    } else {
        $user_id = 0;
    }
    System::database()->Select('mail_topics', "`id`='{$topic_id}'");
    $topic = System::database()->FetchRow();
    $count = SafeDB($topic['count'], 11, int) + 1;
    System::database()->Update('mail_topics', "count='{$count}'", "`id`='{$topic_id}'");
    $vals = Values($user_id, $topic_id, $mail_selected, $html);
    System::database()->Insert('mail_list', $vals);
    $back = Ufu('index.php?name=mail&op=topics', 'mail/{op}/');
    System::site()->AddTextBox('Рассылки', '<p align="center"><br>Спасибо, что Вы подписались на нашу рассылку.<br>Список других рассылок сайта можете посмотреть <a href="' . $back . '">Здесь</a>.<br><br><a href="javascript:history.go(-1)">Вернуться назад</a>.<br><br></p>');
}
function AdminFeedBackSave()
{
    $name = SafeEnv($_POST['name'], 255, str);
    $email = SafeEnv($_POST['email'], 50, str);
    $active = EnToInt($_POST['enabled']);
    if (!isset($_GET['id'])) {
        $vals = Values('', $name, $email, $active);
        System::database()->Insert('feedback', $vals);
        Audit('Обратная связь: Добавление департамента "' . $_POST['name'] . '"');
    } else {
        $id = SafeEnv($_GET['id'], 11, int);
        $set = "name='{$name}',email='{$email}',active='{$active}'";
        System::database()->Update('feedback', $set, "`id`='" . $id . "'");
        Audit('Обратная связь: Изменение департамента "' . $_POST['name'] . '"');
    }
    GO(ADMIN_FILE . '?exe=feedback');
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$table = SafeEnv($_GET['name'], 255, str);
$index = SafeEnv($_GET['index'], 11, int);
$where = '';
if (isset($_GET['where'])) {
    $where = $_GET['where'];
}
$rows = System::database()->Select($table, $where);
$row = $rows[$index];
$row2 = array();
$columns = System::database()->GetTableColumns($table);
foreach ($columns as $col) {
    $row2[] = $row[$col['name']];
}
$row2 = SafeEnv($row2, 0, str);
$code_vals = Values($row2);
$install_code = "System::database()->Insert('{$table}',\"{$code_vals}\");" . EOL;
System::admin()->AddCenterBox('PHP код вставки');
System::admin()->FormRow('Установка', $site->TextArea('code', $install_code, 'style="width: 800px; height: 200px;" class="autofocus selectall"'));
System::admin()->AddForm('', $site->Button('Назад', 'onclick="history.go(-1);"'));
AdminFdbAdminGenTableMenu(SafeDB($table, 255, str));
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 AdminConfigGroupSave()
{
    $name = SafeEnv($_POST['name'], 255, str);
    $hname = SafeEnv($_POST['hname'], 255, str);
    $description = SafeEnv($_POST['description'], 255, str);
    if (isset($_POST['visible'])) {
        $visible = '1';
    } else {
        $visible = '0';
    }
    $vals = Values('', $name, $hname, $description, $visible);
    if (isset($_GET['id'])) {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Update(AdminConfigGroupTable(), $vals, "`id`='{$id}'", true);
        Audit('Управление настройками: Редактирование группы настроек "' . $hname . '(' . $name . ')" в "' . AdminConfigGroupTable() . '"');
        $msg = '&saveok';
    } else {
        System::database()->Insert(AdminConfigGroupTable(), $vals);
        Audit('Управление настройками: Добавление группы настроек "' . $hname . '(' . $name . ')" в "' . AdminConfigGroupTable() . '"');
        $msg = '&addok';
    }
    GO(ADMIN_FILE . '?exe=config_admin' . (AdminConfigPlugins() ? '&a=view_groups_plugins&plugins=1' : '&a=view_groups') . $msg);
}
function AdminsEditGroupSave()
{
    global $action;
    $access = array();
    $access2 = array();
    if (isset($_POST['access'])) {
        $access = SafeEnv($_POST['access'], 0, str);
        $keys = array();
        for ($i = 0, $c = count($access); $i < $c; $i++) {
            $acca = explode(',', $access[$i]);
            $access2[$acca[0]][] = $acca[1];
            if (!in_array($acca[0], $keys)) {
                $keys[] = $acca[0];
            }
        }
        //Очищаем массив от "ненужных" доступов
        for ($i = 0, $c = count($keys); $i < $c; $i++) {
            if (!in_array($keys[$i], $access2[$keys[$i]])) {
                unset($access2[$keys[$i]]);
            }
        }
    }
    if (isset($access2['ALL'])) {
        $access = 'ALL';
    } else {
        $access = serialize($access2);
    }
    if ($action == 'editsave') {
        $adm = System::database()->Select('usertypes', "`id`='" . SafeEnv($_GET['id'], 11, int) . "'");
        if ($adm[0]['system'] == '1') {
            $access = 'ALL';
        }
        $vals = Values('', SafeEnv($_POST['name'], 255, str), SafeEnv($_POST['color'], 9, str), $access, SafeEnv($adm[0]['system'], 1, int), SafeEnv($_POST['image'], 250, str));
        System::database()->Update('usertypes', $vals, "`id`='" . SafeEnv($_GET['id'], 11, int) . "'", true);
        Audit('Администраторы: Изменение группы администраторов "' . $_POST['name'] . '"');
    } elseif ($action == 'addsave') {
        $vals = Values('', SafeEnv($_POST['name'], 255, str), SafeEnv($_POST['color'], 9, str), $access, 0, SafeEnv($_POST['image'], 250, str));
        System::database()->Insert('usertypes', $vals);
        Audit('Администраторы: Добавление группы администраторов "' . $_POST['name'] . '"');
    }
    // Очищаем кэш
    System::cache()->Delete(system_cache, 'usertypes');
    GO(ADMIN_FILE . '?exe=admins&a=groups');
}
 /**
  * Сохранение категории
  * @param null $Id
  * @return bool|int Истина при успешном изменении или id категории, при добавлении новой категории.
  */
 public function EditorSave($Id = null)
 {
     $ret = false;
     $title = SafeEnv($_POST['title'], 250, str);
     $desc = SafeEnv($_POST['desc'], 0, str);
     $icon = SafeEnv($_POST['icon'], 250, str);
     $parent = SafeEnv($_POST['cat'], 11, int);
     if ($Id == null) {
         $query = Values('', $title, $desc, $icon, 0, 0, $parent);
         System::database()->Insert($this->Table, $query);
         Audit('Категории: Добавление категории "' . $this->Table . '"/"' . $title . '"');
         $ret = System::database()->GetLastId();
         $this->CalcCatCounter($parent, true);
     } else {
         if (in_array($Id, $this->GetAllChildId($Id))) {
             $query = "`title`='{$title}',`description`='{$desc}',`icon`='{$icon}',`parent`='{$parent}'";
             System::database()->Update($this->Table, $query, "`id`='{$Id}'");
             Audit('Категории: Изменение категории "' . $this->Table . '"/"' . $title . '"');
             $ret = true;
         }
     }
     System::cache()->Delete('tree', $this->Table);
     return $ret;
 }
function IndexForumAddTopic()
{
    global $forum_lang;
    $forums_tree = ForumTree::Instance();
    // Проверки на доступ
    if (CheckGet('forum') && CheckPost('topic_title', 'text') && isset($forums_tree->IdCats[$_GET['forum']])) {
        $forum_id = SafeEnv($_GET['forum'], 11, int);
        $forum = $forums_tree->IdCats[$forum_id];
        $forum_config = $forums_tree->GetForumConfigRecursive($forum_id);
        if (!$forum_config['access']) {
            // Доступ
            System::site()->AddTextBox($forum_lang['error'], $forum_config['access_reason']);
            return;
        } elseif (!$forum_config['add_topic']) {
            // Разрешено ли добавлять новые темы
            System::site()->AddTextBox($forum_lang['error'], $forum_config['add_topic_reason']);
            return;
        }
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    if (!CheckPost('text') || strlen($_POST['text']) == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['no_data']);
        return;
    }
    $user_id = System::user()->Get('u_id');
    $user_name = System::user()->Get('u_name');
    $time = time();
    // Добавляем топик
    // TODO: Зачем здесь пустое поле?
    $uniq_code = '';
    //GenRandomString(12, '1234567890');
    $topic_title = SafeEnv($_POST['topic_title'], 255, str);
    if (strlen($topic_title) == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['no_title_topic']);
        return;
    }
    $topic_values = Values('', $forum_id, $topic_title, '1', '0', '0', $time, $user_id, $user_name, $time, '0', '', $uniq_code, 0, 0, 0);
    System::database()->Insert('forum_topics', $topic_values);
    $topic_id = System::database()->GetLastId();
    $topic = System::database()->Select('forum_topics', "`id`='{$topic_id}'");
    $topic = $topic[0];
    // Добавляем сообщение
    $email = System::user()->Get('u_email');
    $hideemail = System::user()->Get('u_hideemail');
    $site = System::user()->Get('u_homepage');
    $icq = System::user()->Get('u_icq');
    $text = SafeEnv($_POST['text'], 0, str);
    System::database()->Insert('forum_posts', Values('', $topic_id, $user_id, time(), $user_name, $site, $email, $hideemail, $icq, $text, getip(), 0));
    // Добавляем очков пользователю
    System::user()->ChargePoints(System::config('points/forum_post'));
    // Увеличиваем счётчик сообщений и тем пользователя
    ForumCalcUserCounters(1, 1);
    $forum['topics'] = SafeDB($forum['topics'], 11, int) + 1;
    IndexForumSetLastPostInfo($forum, $topic);
    // Добавляем метку о прочтении темы автором топика
    System::database()->Insert('forum_topics_read', Values($user_id, $topic_id, $time));
    // Очищаем кэш
    ForumCacheClear();
    GO(Ufu('index.php?name=forum&op=showforum&forum=' . $forum_id, GetSiteUrl() . 'forum/{forum}/'));
}
function IndexGBAddMsgSave()
{
    $r = array();
    $er = array();
    if (!isset($_GET['name']) || !isset($_POST['email']) || !isset($_POST['site']) || !isset($_POST['icq']) || !isset($_POST['text'])) {
        $er[] = 'Данные не инициализированы.';
    }
    if (GBCheckFlood()) {
        $er[] = 'Флуд защита, подождите немного.';
    }
    if (strlen($_POST['name']) == 0) {
        $er[] = 'Вы не ввели имя.';
    }
    if (strlen($_POST['email']) == 0) {
        $er[] = 'Вы не ввели свой e-mail.';
    } elseif (!CheckEmail($_POST['email'])) {
        $er[] = 'Вы совершили ошибку при вводе e-mail.';
    }
    if (strlen($_POST['text']) == 0) {
        $er[] = 'Вы не ввели текст сообщения, либо сообщение слишком короткое.';
    }
    if ($_POST['icq'] != '') {
        if (!is_numeric($_POST['icq'])) {
            $er[] = 'Ваш номер ICQ должен состоять только из чисел.';
        }
    }
    // Проверяем капчу
    if (!System::user()->Auth || !System::user()->isAdmin() && System::config('gb/show_captcha')) {
        if (!System::user()->isDef('captcha_keystring') || System::user()->Get('captcha_keystring') != $_POST['keystr']) {
            $er[] = 'Вы ошиблись при вводе кода с картинки.';
        }
    }
    if (count($er) == 0) {
        if (isset($_POST['hideemail'])) {
            $hideemail = '1';
        } else {
            $hideemail = '0';
        }
        if (System::user()->isAdmin() || !System::config('gb/moderation')) {
            $moderated = 1;
        } else {
            $moderated = 0;
        }
        $name = SafeEnv($_POST['name'], 50, str, true);
        $email = SafeEnv($_POST['email'], 50, str, true);
        $_site = SafeEnv(Url($_POST['site']), 250, str, true);
        $icq = SafeEnv($_POST['icq'], 15, str, true);
        $text = SafeEnv($_POST['text'], System::config('gb/msgmaxlen'), str, true);
        $vals = Values('', $name, $email, $hideemail, $_site, $icq, $text, '', time(), getip(), $moderated);
        System::database()->Insert('guestbook', $vals);
        System::user()->ChargePoints(System::config('points/gb_public'));
        if (System::user()->isAdmin() || !System::config('gb/moderation')) {
            GO(GetSiteUrl() . Ufu('index.php?name=guestbook', '{name}/'));
        } else {
            $text = '<p align="center"><br>Спасибо! Ваше сообщение будет добавлено после модерации.<br><br>';
            $text .= '<input type="button" value="Назад" onclick="history.back();"><br></p>';
            System::site()->AddTextBox('', $text);
        }
    } else {
        $text = 'Ваше сообщение не добавлено по следующим причинам:<br><ul>';
        foreach ($er as $error) {
            $text .= '<li>' . $error;
        }
        $text .= '</ul><p align="center"><input type="button" value="Назад" onclick="history.back();"></p>';
        System::site()->AddTextBox('', $text);
    }
}
function AdminSmiliesAutoSave()
{
    global $mod;
    $count = count($_POST['smilies']);
    foreach ($_POST['smilies'] as $file) {
        $file = RealPath2(SafeEnv($file, 255, str));
        $code = SafeEnv($_POST['code'][$file], 255, str);
        $desc = SafeEnv($_POST['desc'][$file], 255, str);
        $disp = isset($_POST['en'][$file]) ? '1' : '0';
        $vals = Values('', $code, $desc, $file, $disp);
        System::database()->Insert('smilies', $vals);
    }
    Audit('Смайлики: Авто-добавление, добалено ' . $count . ' смайликов.');
    GO($mod);
}
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');
    }
}
/**
 * Сохранение изменений категории
 * @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 AdminMailAddEmail()
{
    if (!isset($_GET['topic_id'])) {
        GO(ADMIN_FILE . '?exe=mail');
    }
    $topic_id = SafeEnv($_GET['topic_id'], 11, int);
    if (!isset($_POST['email'])) {
        GO(ADMIN_FILE . '?exe=mail');
    }
    if (CheckEmail($_POST['email'])) {
        $email = SafeEnv($_POST['email'], 50, str, true);
    } else {
        $text = 'Не правильный формат E-mail. Он должен быть вида: <b>domain@host.ru</b>.<br />' . '<a href="javascript:history.go(-1)">Назад</a>';
        AddTextBox("Внимание!", $text);
        return;
    }
    System::database()->Select('mail_topics', "`id`='{$topic_id}'");
    $topic = System::database()->FetchRow();
    $html = SafeEnv($_POST['html'], 1, int);
    $vals = Values('0', $topic_id, $email, $html);
    System::database()->Insert('mail_list', $vals);
    Audit('Рассылки: Добавление адреса ' . $email . ' в список рассылки темы "' . $topic['title'] . '"');
    CalcListCounter($topic_id, true);
    GO(ADMIN_FILE . '?exe=mail&a=list&topic_id=' . $topic_id);
}
/**
 * Простая функция для добавления безымянных правил.
 * Используется при автогенерации правил в функции Ufu().
 * @param        $UfuTemplate
 * @param        $Params
 * @param int    $MinOrder
 * @return array Добавленное правило замены.
 * @see UfuAddRuleByTemplate()
 */
function UfuAddRewriteRule($UfuTemplate, $Params, $MinOrder = 10000)
{
    list($Pattern, $Replace) = UfuGeneratePattern($UfuTemplate, $Params);
    $rule = array('id' => '', 'name' => '', 'module' => '_any', 'description' => '', 'ufu' => SafeEnv($UfuTemplate, 255, str), 'pattern' => SafeEnv($Pattern, 255, str), 'params' => SafeEnv($Replace, 255, str), 'order' => UfuGetOrder($MinOrder));
    System::database()->Insert('rewrite_rules', Values($rule));
    $rule['id'] = System::database()->GetLastId();
    UfuGetRules(null, true);
    return $rule;
}
function IndexUserRegistrationOk()
{
    System::site()->SetTitle('Регистрация на сайте');
    if (isset($_POST['usersave']) && $_POST['usersave'] == 'update') {
        $edit = true;
        $user_id = System::user()->Get('u_id');
        System::database()->Select('users', "`id`='" . $user_id . "'");
        $user = System::database()->FetchRow();
    } else {
        $edit = false;
    }
    if (!$edit) {
        System::user()->UnLogin(false);
    } else {
        if (!System::user()->Auth) {
            GO(Ufu('index.php'));
        }
    }
    if (System::config('user/registration') == 'off' && !$edit) {
        System::site()->AddTextBox('Ошибка', '<p align="center">Извините, регистрация временно приостановлена.</p>');
        return;
    }
    //Обрабатываем данные
    $errors = array();
    // Логин
    $login = '';
    $sendlogin = '';
    if (isset($_POST['login']) && CheckLogin(SafeEnv($_POST['login'], 30, str), $errors, true, $edit ? $user_id : 0)) {
        $login = SafeEnv($_POST['login'], 30, str);
        $sendlogin = $_POST['login'];
    }
    // Пароль
    $pass = '';
    $sendpass = '';
    $pass_generate_message = '';
    if (!System::user()->isAdmin() && $_POST['pass'] != '') {
        $pass = SafeEnv($_POST['pass'], 255, str);
        $rpass = SafeEnv($_POST['rpass'], 255, str);
        $sendpass = $_POST['pass'];
        if ($edit) {
            if ($rpass != '') {
                if (!CheckPass(SafeEnv($_POST['pass'], 255, str), $errors)) {
                    $pass = '';
                } elseif ($rpass != $pass) {
                    $errors[] = 'Пароли не совпадают.';
                    $pass = '';
                }
            } else {
                $pass = '';
            }
        } else {
            if ($_POST['pass'] == '') {
                srand(time());
                $pass = GenBPass(rand(System::config('user/pass_min_length'), 15));
                $sendpass = $pass;
                $pass_generate_message = '<br>Так как Вы не указали пароль, он был сгенерирован автоматически и выслан Вам на E-mail.';
            } else {
                if (CheckPass(SafeEnv($_POST['pass'], 255, str), $errors)) {
                    if ($rpass != $pass) {
                        $errors[] = 'Пароли не совпадают.';
                    }
                }
            }
        }
        $pass2 = md5($pass);
    }
    // E-mail
    if (!System::user()->isAdmin() && isset($_POST['email']) && CheckUserEmail(SafeEnv($_POST['email'], 50, str, true), $errors, true, $edit ? $user_id : 0)) {
        $email = SafeEnv($_POST['email'], 50, str, true);
    } else {
        $email = '';
    }
    // Скрыть E-mail
    if (isset($_POST['hideemail'])) {
        $hide_email = '1';
    } else {
        $hide_email = '0';
    }
    // Имя пользователя
    if (isset($_POST['nikname']) && CheckNikname(SafeEnv($_POST['nikname'], 50, str, true), $errors, true, $edit ? $user_id : 0)) {
        $nik_name = SafeEnv($_POST['nikname'], 50, str, true);
    } else {
        $nik_name = '';
    }
    // Настоящее имя
    if (isset($_POST['realname'])) {
        $real_name = SafeEnv($_POST['realname'], 250, str, true);
    } else {
        $real_name = '';
    }
    // Возраст лет
    if (isset($_POST['age'])) {
        if ($_POST['age'] == '' || is_numeric($_POST['age'])) {
            $age = SafeEnv($_POST['age'], 3, int);
        } else {
            $errors[] = 'Ваш возраст должен быть числом!';
        }
    } else {
        $age = '';
    }
    // Адрес домашней страницы
    if (isset($_POST['homepage'])) {
        $homepage = SafeEnv(Url($_POST['homepage']), 250, str, true);
    } else {
        $homepage = '';
    }
    // Номер ICQ
    if (isset($_POST['icq'])) {
        if ($_POST['icq'] == '' || is_numeric($_POST['icq'])) {
            $icq = SafeEnv($_POST['icq'], 15, str, true);
        } else {
            $errors[] = 'Номер ICQ должен содержать только числа!';
        }
    } else {
        $icq = '';
    }
    // Город
    if (isset($_POST['city'])) {
        $city = SafeEnv($_POST['city'], 100, str, true);
    } else {
        $city = '';
    }
    // Часовой пояс
    if (isset($_POST['gmt'])) {
        $gmt = SafeEnv($_POST['gmt'], 255, str);
    } else {
        $gmt = System::config('general/default_timezone');
    }
    // О себе
    if (isset($_POST['about'])) {
        $about = SafeEnv($_POST['about'], System::config('user/about_max_length'), str, true);
    } else {
        $about = '';
    }
    // Подписка на рассылку
    if (isset($_POST['snews'])) {
        $server_news = '1';
    } else {
        $server_news = '0';
    }
    if (!$edit && (!System::user()->Auth && !System::user()->isDef('captcha_keystring') || System::user()->Get('captcha_keystring') != $_POST['keystr'])) {
        $errors[] = 'Вы ошиблись при вводе кода с картинки.';
    }
    // Аватар
    $updateAvatar = true;
    if (isset($_POST['avatar'])) {
        if (System::config('user/avatar_transfer') == '1' && isset($_FILES['upavatar']) && file_exists($_FILES['upavatar']['tmp_name'])) {
            UserLoadAvatar($errors, $avatar, $a_personal, $user['avatar'], $user['a_personal'] == '1', $edit);
        } elseif ($_POST['avatar'] == '') {
            $updateAvatar = false;
        } elseif (file_exists(RealPath2(System::config('general/avatars_dir') . $_POST['avatar']))) {
            if ($edit) {
                if ($user['a_personal'] == '1') {
                    UnlinkUserAvatarFiles($user['avatar']);
                }
            }
            $a_personal = '0';
            $avatar = $_POST['avatar'];
        } else {
            $avatar = 'noavatar.gif';
            $a_personal = '0';
        }
    } else {
        $avatar = 'noavatar.gif';
        $a_personal = '0';
    }
    // Активация аккаунта
    $active = '1';
    $code = '';
    $SendActivation = false;
    $activate = '';
    if (!$edit) {
        $activate = System::config('user/activate_type');
        switch ($activate) {
            case 'manual':
                $active = '0';
                $code = '';
                $SendActivation = false;
                break;
            case 'auto':
                $active = '1';
                $code = '';
                $SendActivation = false;
                break;
            case 'mail':
                $active = '0';
                $code = GenRandomString(32);
                $SendActivation = true;
                break;
        }
    }
    $status = 2;
    $access = -1;
    $reg_date = time();
    $last_visit = time();
    $ip = getip();
    $points = 0;
    $visits = 0;
    // Сохранение
    if (count($errors) == 0) {
        if ($SendActivation) {
            UserSendActivationMail($nik_name, $email, $sendlogin, $sendpass, $code, $reg_date);
            $finish_message = Indent('
				<br>
				На указанный Вами E-Mail отправлено письмо,
				содержащее ссылку для подтверждения регистрации.
				Для активации Вашего аккаунта перейдите по данной ссылке
				и подтвердите регистрацию!
			');
        } elseif (!$edit) {
            UserSendEndRegMail($email, $nik_name, $sendlogin, $sendpass, $reg_date);
            $finish_message = '<br>На ваш E-mail отправлено письмо с данными о регистрации.';
        }
        if (!$edit) {
            // Добавление нового пользователя
            $values = Values('', $login, $pass2, $nik_name, $real_name, $age, $email, $hide_email, $city, $icq, $homepage, $gmt, $avatar, $about, $server_news, $reg_date, $last_visit, $ip, $points, $visits, $active, $code, $status, $access, $a_personal, serialize(array()));
            System::database()->Insert('users', $values);
            // Очищаем кэш пользователей
            System::cache()->Delete(system_cache, 'users');
            // Автоматический вход
            if ($activate == 'auto') {
                System::user()->Login($login, $pass, true, false);
                System::site()->InitVars();
            } elseif ($activate == 'mail') {
                System::user()->Def('activate_ps', base64_encode($pass));
            }
            System::site()->AddTextBox('Регистрация', '<p align="center">Поздравляем! Вы успешно зарегистрированы на сайте.' . $pass_generate_message . $finish_message . '<br>С уважением, администрация сайта <strong>' . System::config('general/site_name') . '.</strong></p>');
        } else {
            // Сохранение изменений
            $set = "`login`='{$login}',`hideemail`='{$hide_email}',`name`='{$nik_name}'," . "`truename`='{$real_name}',`age`='{$age}',`url`='{$homepage}',`icq`='{$icq}',`city`='{$city}',`timezone`='{$gmt}'" . ($updateAvatar == true ? ",`avatar`='{$avatar}',`a_personal`='{$a_personal}'" : '') . ",`about`='{$about}'," . "`servernews`='{$server_news}'" . ($pass != '' ? ",`pass`='{$pass2}'" : '') . ($email != '' ? ",`email`='{$email}'" : '');
            System::database()->Update('users', $set, "`id`='" . System::user()->Get('u_id') . "'");
            System::user()->UpdateMemberSession();
            UpdateUserComments(System::user()->Get('u_id'), System::user()->Get('u_id'), $nik_name, $email, $hide_email, $homepage, getip());
            // Очищаем кэш пользователей
            System::cache()->Delete(system_cache, 'users');
            GO(GetSiteUrl() . Ufu('index.php?name=user&op=userinfo', 'user/{op}/'));
        }
    } else {
        // Ошибка
        $text = 'Ваш аккаунт не ' . ($edit ? 'сохранен' : 'добавлен') . ', произошли следующие ошибки:<br><ul>';
        foreach ($errors as $error) {
            $text .= '<li>' . $error;
        }
        $text .= '</ul>';
        // Удаляем аватар
        if ($a_personal == '1' && !$edit) {
            unlink(System::config('general/personal_avatars_dir') . $avatar);
        }
        System::site()->AddTextBox('Ошибка', $text);
        IndexUserRegistration(true, $edit);
    }
}
function AdminNewsTopicSave()
{
    global $news_access_edittopics, $action;
    if (!$news_access_edittopics) {
        System::admin()->AccessDenied();
    }
    $image = SafeEnv($_POST['topic_image'], 255, str, true);
    if ($action == 'addtopic') {
        $values = Values('', SafeEnv($_POST['topic_name'], 255, str), SafeEnv($_POST['topic_description'], 255, str), $image, '0');
        System::database()->Insert('news_topics', $values);
        Audit('Новости: Добавление новостного раздела "' . $_POST['topic_name'] . '"');
    } elseif ($action == 'savetopic') {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('news_topics', "`id`='" . $id . "'");
        $topic = System::database()->FetchRow();
        $values = Values('', SafeEnv($_POST['topic_name'], 255, str), SafeEnv($_POST['topic_description'], 255, str), $image, SafeEnv($topic['counter'], 11, int));
        System::database()->Update('news_topics', $values, "`id`='{$id}'", true);
        Audit('Редактирование новостного раздела "' . $_POST['topic_name'] . '"');
    }
    GO(ADMIN_FILE . '?exe=news&a=topics');
}
/**
 * Регистрирует таблицу комментариев.
 * @param $Name
 * @param $ObjTable
 * @param $ObjIdColl
 * @param $ObjCounterColl
 * @param $ObjCounterCollIndex
 */
function RegisterCommentTable($Name, $ObjTable, $ObjIdColl, $ObjCounterColl, $ObjCounterCollIndex, $SearchUrl = '', $SearchUfu = '', $SearchNavUfu = '', $PageParam = 'page')
{
    $vals = Values('', $Name, $ObjTable, $ObjIdColl, $ObjCounterColl, $ObjCounterCollIndex, $SearchUrl, $SearchUfu, $SearchNavUfu, $PageParam);
    System::database()->Insert('comments', $vals);
}
/**
 * Сохраняет данные формы сгенерированной фукцией AdminUserEditor
 *
 * @param  $back_link
 * @param string $a
 * @param int $id
 * @param bool $IsAdmin
 * @return void
 */
function AdminUserEditSave($back_link, $a = 'insert', $id = 0, $IsAdmin = false)
{
    $SystemAdmin = System::user()->isSuperUser();
    $edit = $a == 'update';
    $editProfile = $edit && !$SystemAdmin && $id == System::user()->Get('u_id');
    // Администратор редактирует свой профиль
    $editStatus = false;
    // Разрешено редактирование статуса
    $editType = false;
    // Разрешено редактировать тип пользователя
    // Загружаем данные пользователя из БД
    if ($edit) {
        $user = System::database()->SelectOne('users', "`id`='{$id}'" . ($IsAdmin ? " and `type`='1'" : " and `type`='2'"));
        if (!$user) {
            AddTextBox('Ошибка', '<p align="center">Пользователь не найден, либо у вас не достаточно прав для редактирования администраторов.</p>');
            return;
        }
    }
    // Устанавливаем ограничения доступа
    if ($IsAdmin) {
        // Редактируем администратора
        if ($SystemAdmin) {
            // Только системные администраторы могут редактировать статус и тип администраторов
            if (!$edit) {
                $editStatus = true;
            } elseif (!(groupIsSystem(SafeEnv($user['access'], 11, int)) && GetSystemAdminsCount() <= 1)) {
                // Если он не системный или системных больше 1
                $editStatus = true;
            }
            $editType = $editStatus;
        }
    } else {
        // Если пользователь
        $editStatus = true;
        // Все администраторы с доступом могут редактировать статус пользователя
        $editType = $SystemAdmin;
        // Только системные администраторы могут создавать администраторов
    }
    // Обрабатываем данные
    $errors = array();
    // Логин
    if (isset($_POST['login']) && CheckLogin($_POST['login'], $errors, !$edit)) {
        $login = SafeEnv($_POST['login'], 30, str);
    } else {
        $login = '';
    }
    // Пароль
    $pass = '';
    if (!$edit || $_POST['pass'] != '') {
        $pass_generate_message = '';
        if (isset($_POST['pass']) && CheckPass($_POST['pass'], $errors)) {
            $pass = SafeEnv($_POST['pass'], 30, str);
            if (!isset($_POST['rpass']) || SafeEnv($_POST['rpass'], 30, str) != $pass) {
                $errors[] = 'Пароли не совпадают.';
            }
        } else {
            $pass = '';
        }
        if (isset($_POST['pass']) && $_POST['pass'] == '') {
            srand(time());
            $pass = GenBPass(rand(System::config('user/pass_min_length'), 15));
            $pass_generate_message = '<br />Так как вы не указали пароль, он был сгенерирован автоматически и выслан на указанный E-mail пользователя.';
        }
        $pass2 = md5($pass);
    }
    // e-mail
    if (isset($_POST['email']) && $_POST['email'] != '') {
        if (!CheckEmail($_POST['email'])) {
            $errors[] = 'Не правильный формат E-mail. Он должен быть вида: <b>domain@host.ru</b> .';
        }
        $email = SafeEnv($_POST['email'], 50, str, true);
    } else {
        $email = '';
        $errors[] = 'Вы не ввели E-mail.';
    }
    // Скрыть e-mail
    if (isset($_POST['hideemail'])) {
        $hide_email = '1';
    } else {
        $hide_email = '0';
    }
    // Имя пользователя на сайте
    if (isset($_POST['nikname']) && CheckNikname($_POST['nikname'], $errors, !$edit)) {
        $nik_name = SafeEnv($_POST['nikname'], 50, str, true);
    } else {
        $nik_name = '';
    }
    // Полное имя
    if (isset($_POST['realname'])) {
        $real_name = SafeEnv($_POST['realname'], 250, str, true);
    } else {
        $real_name = '';
    }
    // Возраст
    if (isset($_POST['age'])) {
        if ($_POST['age'] == '' || is_numeric($_POST['age'])) {
            $age = SafeEnv($_POST['age'], 3, int);
        } else {
            $errors[] = 'Ваш возраст должен быть числом!';
        }
    } else {
        $age = '';
    }
    // Домашняя страница
    if (isset($_POST['homepage'])) {
        if ($_POST['homepage'] != '' && substr($_POST['homepage'], 0, 7) == 'http://') {
            $_POST['homepage'] = substr($_POST['homepage'], 7);
        }
        $homepage = SafeEnv($_POST['homepage'], 250, str, true);
    } else {
        $homepage = '';
    }
    // Номер ICQ
    if (isset($_POST['icq'])) {
        if ($_POST['icq'] == '' || is_numeric($_POST['icq'])) {
            $icq = SafeEnv($_POST['icq'], 15, str, true);
        } else {
            $errors[] = 'Номер ICQ должен содержать только числа!';
        }
    } else {
        $icq = '';
    }
    // Город
    if (isset($_POST['city'])) {
        $city = SafeEnv($_POST['city'], 100, str, true);
    } else {
        $city = '';
    }
    // Часовой пояс
    if (isset($_POST['gmt'])) {
        $gmt = SafeEnv($_POST['gmt'], 255, str);
    } else {
        $gmt = System::config('general/default_timezone');
    }
    // О себе
    if (isset($_POST['about'])) {
        $about = SafeEnv($_POST['about'], System::config('user/about_max_length'), str, true);
    } else {
        $about = '';
    }
    // Подписка на новости
    if (isset($_POST['snews'])) {
        $server_news = '1';
    } else {
        $server_news = '0';
    }
    //Обрабатываем аватар
    $updateAvatar = true;
    if (isset($_POST['avatar'])) {
        if (System::config('user/avatar_transfer') == '1' && isset($_FILES['upavatar']) && file_exists($_FILES['upavatar']['tmp_name'])) {
            if ($edit) {
                $avatar = $user['avatar'];
                $a_personal = $user['a_personal'];
            } else {
                $avatar = '';
                $a_personal = '0';
            }
            UserLoadAvatar($errors, $avatar, $a_personal, $avatar, $a_personal, $edit);
        } elseif ($_POST['avatar'] == '') {
            $updateAvatar = false;
        } elseif (file_exists(RealPath2(System::config('general/avatars_dir') . $_POST['avatar']))) {
            if ($edit) {
                if ($user['a_personal'] == '1') {
                    UnlinkUserAvatarFiles($user['avatar']);
                }
            }
            $a_personal = '0';
            $avatar = $_POST['avatar'];
        } else {
            $avatar = '';
            $a_personal = '0';
        }
    } else {
        $avatar = '';
        $a_personal = '0';
    }
    $SendActivation = false;
    if ($edit) {
        $active = SafeEnv($user['active'], 11, int);
        $code = SafeEnv($user['activate'], 11, int);
    } else {
        $active = '1';
        $code = '';
    }
    if ($editStatus) {
        $activate = $_POST['activate'];
        $lastactivate = 'manual';
        if ($active == '0' && $code != '') {
            $lastactivate = 'mail';
        } elseif ($active == '1' && $code == '') {
            $lastactivate = 'auto';
        }
        if ($activate != $lastactivate) {
            switch ($activate) {
                case 'manual':
                    $active = '0';
                    $code = '';
                    $SendActivation = false;
                    break;
                case 'auto':
                    $active = '1';
                    $code = '';
                    $SendActivation = false;
                    break;
                case 'mail':
                    $active = '0';
                    $code = GenRandomString(8, 'qwertyuiopasdfghjklzxcvbnm');
                    $SendActivation = true;
                    break;
            }
        }
    }
    if ($edit) {
        $access = SafeEnv($user['type'], 11, int);
        $user_type = SafeEnv($user['access'], 11, int);
    } else {
        $access = '2';
        $user_type = '-1';
    }
    if ($editType && $_POST['status'] != 'member') {
        $access = '1';
        $user_type = SafeEnv($_POST['status'], 11, int);
    }
    $reg_date = time();
    $last_visit = time();
    $ip = getip();
    $points = 0;
    $visits = 0;
    if ($SendActivation) {
        UserSendActivationMail($nik_name, $email, $login, $pass, $code, $reg_date);
    } elseif (!$edit) {
        UserSendEndRegMail($email, $nik_name, $login, $pass, $reg_date);
    }
    if (!$edit) {
        $values = Values('', $login, $pass2, $nik_name, $real_name, $age, $email, $hide_email, $city, $icq, $homepage, $gmt, $avatar, $about, $server_news, $reg_date, $last_visit, $ip, $points, $visits, $active, $code, $access, $user_type, $a_personal, serialize(array()));
        System::database()->Insert('users', $values);
    } else {
        $set = "`login`='{$login}',`email`='{$email}',`hideemail`='{$hide_email}',`name`='{$nik_name}'," . "`truename`='{$real_name}',`age`='{$age}',`url`='{$homepage}',`icq`='{$icq}',`city`='{$city}'," . "`timezone`='{$gmt}'" . ($updateAvatar == true ? ",`avatar`='{$avatar}',`a_personal`='{$a_personal}'" : '') . "," . "`about`='{$about}',`servernews`='{$server_news}'" . ($pass != '' ? ",`pass`='{$pass2}'" : '') . ",`type`='{$access}'," . "`access`='{$user_type}',`active`='{$active}',`activate`='{$code}'";
        System::database()->Update('users', $set, "`id`='" . $id . "'");
        System::user()->UpdateMemberSession();
        UpdateUserComments($id, $id, $nik_name, $email, $hide_email, $homepage);
    }
    if (count($errors) > 0) {
        $text = 'Аккаунт сохранен, но имели место следующие ошибки:<br /><ul>';
        foreach ($errors as $error) {
            $text .= '<li>' . $error;
        }
        $text .= '</ul>';
        AddTextBox('Внимание', $text);
    } else {
        // Очищаем кэш пользователей
        System::cache()->Delete(system_cache, 'users');
        if (!$editProfile) {
            GO(ADMIN_FILE . '?exe=' . $back_link);
        } else {
            System::admin()->AddCenterBox('Редактирование профиля');
            System::admin()->Highlight('Ваш профиль сохранён, обновите страницу.');
        }
    }
}
function Moderation_Do_Basket_Post($post_id, $reason = '')
{
    System::database()->Update('forum_posts', "`delete`='1'", "`id`='{$post_id}'");
    $vals = Values('', time(), System::user()->Get('u_id'), $reason, $post_id);
    System::database()->Insert('forum_basket_post', $vals);
}
/**
 * Функция пересчитывает инкремент поля таблицы и сбрасывает counter на количество записей в таблице.
 */
function AdminDbRepairResetId()
{
    if (System::database()->Name != 'FilesDB') {
        return;
    }
    $table = $_GET['table'];
    $columns = System::database()->GetTableColumns($table);
    $increment_columns = array();
    foreach ($columns as $c) {
        if (isset($c['auto_increment']) && $c['auto_increment'] == true) {
            $increment_columns[] = $c['name'];
        }
    }
    $data = System::database()->Select($table);
    System::database()->Truncate($table);
    foreach ($data as $row) {
        foreach ($increment_columns as $name) {
            $row[$name] = '';
        }
        $row = SafeEnv($row, 0, str, false, true, false);
        System::database()->Insert($table, Values($row));
    }
}
function AdminUserRankSave($action)
{
    $rankname = SafeEnv($_POST['rankname'], 250, str);
    $rankimage = SafeEnv($_POST['rankimage'], 250, str);
    $minpoints = SafeEnv($_POST['minpoints'], 11, int);
    if ($action == 'addrank') {
        System::database()->Insert('userranks', Values('', $rankname, $minpoints, $rankimage));
        Audit('Пользователи: Добавление ранга "' . $rankname . '"');
    } elseif ($action == 'saverank') {
        System::database()->Update('userranks', "`title`='{$rankname}',`min`='{$minpoints}',`image`='{$rankimage}'", "`id`='" . SafeEnv($_GET['id'], 11, int) . "'");
        Audit('Пользователи: Изменение ранга "' . $rankname . '"');
    }
    // Очищаем кэш
    System::cache()->Delete(system_cache, 'userranks');
    GO(ADMIN_FILE . '?exe=user&a=ranks');
}
 public function SavePost($ObjectId, $Edit = false)
 {
     $errors = array();
     if ($Edit) {
         if (!isset($_GET['post_id'])) {
             $errors[] = 'post_id не инициализирована в GET.';
         } else {
             $post_id = SafeEnv($_GET['post_id'], 11, int);
             System::database()->Select($this->PostsTable, "`id`='{$post_id}'");
             $post = System::database()->FetchRow();
         }
     } else {
         if (!$this->AlloyComments) {
             $errors[] = 'Обсуждение закрыто';
             return;
         }
         if ($this->DisableComments) {
             $errors[] = 'Система комментариев отключена. Вы не сможете добавить комментарий.';
         }
     }
     $post_message = '';
     $post_parent_id = 0;
     if (System::user()->Auth) {
         // Авторизованный пользователь, добавляет комментарий
         if (!isset($_POST['post_message']) || !isset($_POST['parent_id'])) {
             $errors[] = 'Данные не инициализированы.';
         }
         $user_id = System::user()->Get('u_id');
         $user_name = System::user()->Get('u_name');
         $user_email = System::user()->Get('u_email');
         $user_hideemail = System::user()->Get('u_hideemail');
         $user_homepage = System::user()->Get('u_homepage');
         if ($Edit && !System::user()->isAdmin() && $post['user_id'] != System::user()->Get('u_id')) {
             $errors[] = 'У вас недостаточно прав для редактирования этого сообщения.';
         }
     } else {
         // Гость, добавляет или редактирует комментарий
         if ($Edit && ($post['user_id'] != '0' || $post['user_ip'] != getip())) {
             $errors[] = 'У вас недостаточно прав для редактирования этого сообщения.';
         } else {
             if ($this->GuestPost || $Edit) {
                 // Разрешено комментировать гостям?
                 if (!$Edit) {
                     if (!isset($_POST['user_name']) || !isset($_POST['user_email']) || !isset($_POST['user_homepage']) || !isset($_POST['post_message']) || !isset($_POST['parent_id'])) {
                         $errors[] = 'Данные не инициализированы.';
                     } else {
                         $user_id = 0;
                         $user_name = SafeEnv($_POST['user_name'], 255, str, true);
                         CheckNikname($user_name, $er, true);
                         System::user()->Def('u_name', $user_name);
                         $user_email = SafeEnv($_POST['user_email'], 255, str, true);
                         if ($user_email != '') {
                             if (!CheckEmail($user_email)) {
                                 $errors[] = 'Формат E-mail не правильный. Он должен быть вида: <b>domain@host.ru</b> .';
                             }
                         }
                         System::user()->Def('u_email', $user_email);
                         if (isset($_POST['hideemail'])) {
                             $user_hideemail = '1';
                         } else {
                             $user_hideemail = '0';
                         }
                         System::user()->Def('u_hideemail', $user_hideemail);
                         $user_homepage = Url(SafeEnv($_POST['user_homepage'], 250, str, true));
                         System::user()->Def('u_homepage', $user_homepage);
                     }
                 } else {
                     if (!isset($_POST['post_message']) || !isset($_POST['parent_id'])) {
                         $errors[] = 'Данные не инициализированы.';
                     }
                     $user_id = SafeDB($post['user_id'], 11, int);
                     $user_name = SafeDB($post['user_name'], 255, str);
                     $user_email = SafeDB($post['user_email'], 255, str);
                     $user_hideemail = SafeDB($post['user_hideemail'], 1, int);
                     $user_homepage = SafeDB($post['user_homepage'], 255, str);
                 }
             } else {
                 $errors[] = 'Чтобы оставлять сообщения, вам необходимо зарегистрироваться.';
             }
         }
     }
     if ($user_name == '') {
         $errors[] = 'Вы не ввели имя.';
     }
     if ($user_email == '') {
         $errors[] = 'Вы не указали ваш E-mail.';
     }
     $post_message = SafeEnv($_POST['post_message'], $this->PostMaxLength, str);
     if (strlen($post_message) == 0) {
         $errors[] = 'Вы не ввели текст сообщения.';
     }
     // Проверяем капчу
     if (!System::user()->Auth || !System::user()->isAdmin() && $this->ShowKaptchaForMembers) {
         if (!System::user()->isDef('captcha_keystring') || System::user()->Get('captcha_keystring') != $_POST['keystr']) {
             $errors[] = 'Вы ошиблись при вводе кода с картинки.';
         }
     }
     if (!isset($_POST['parent_id'])) {
         $errors[] = 'parent_id не инициализирована в POST.';
     } else {
         if ($this->Answers == '1' || System::user()->isAdmin()) {
             $parent = $_POST['parent_id'];
             $parent = explode('_', $parent, 2);
             $post_parent_id = SafeEnv($parent[1], 11, int);
         } else {
             $post_parent_id = '0';
         }
     }
     if ($this->CheckFlood() && !$Edit) {
         $errors[] = 'Флуд-защита, подождите немного.';
     }
     $this->LastSaveErrors = $errors;
     if (count($errors) == 0) {
         if (!$Edit) {
             $vals = Values('', $ObjectId, $user_id, $user_name, $user_homepage, $user_email, $user_hideemail, getip(), time(), $post_message, $post_parent_id);
             $cols = array('id', 'object_id', 'user_id', 'user_name', 'user_homepage', 'user_email', 'user_hideemail', 'user_ip', 'post_date', 'post_message', 'post_parent_id');
             System::database()->Insert($this->PostsTable, $vals, $cols);
         } else {
             System::database()->Update($this->PostsTable, "`post_message`='{$post_message}'", "`id`='{$post_id}'");
             if (System::user()->isAdmin()) {
                 Audit('Posts: Изменение комментария "' . $this->PostsTable . '"/"' . "(user: {$user_name}, object_id: {$ObjectId})" . '"');
             }
         }
         return true;
     } else {
         return false;
     }
 }
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 IndexForumAddPost()
{
    global $forum_lang;
    $forums_tree = ForumTree::Instance();
    // Проверки на доступ
    if (CheckGet('topic')) {
        // Тема
        $topic_id = SafeEnv($_GET['topic'], 11, int);
        System::database()->Select('forum_topics', "`id`='{$topic_id}'");
        if (System::database()->NumRows() > 0) {
            $topic = System::database()->FetchRow();
        } else {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_access_category']);
            return;
        }
        if ($topic['delete'] == '1') {
            // Тема на удалении
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_basket'] . '.' . $forum_lang['no_topic_basket_edit']);
            return;
        }
        if ($topic['close_topics'] == '1') {
            // Тема закрыта
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_close_for_discussion'] . '.' . $forum_lang['no_create_new_message_current_topic_add']);
            return;
        }
        // Форум
        $forum_id = SafeEnv($topic['forum_id'], 11, int);
        if (!isset($forums_tree->IdCats[$forum_id])) {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
            return;
        }
        $forum = $forums_tree->IdCats[$forum_id];
        $forum_config = $forums_tree->GetForumConfigRecursive($forum_id);
        if (!$forum_config['access']) {
            // Доступ
            System::site()->AddTextBox($forum_lang['error'], $forum_config['access_reason']);
            return;
        } elseif (!$forum_config['add_post']) {
            // Разрешено ли добавлять новые сообщения (+ защита от гостей)
            System::site()->AddTextBox($forum_lang['error'], $forum_config['add_post_reason']);
            return;
        }
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    // Добавляем сообщение
    if (!CheckPost('text') || strlen($_POST['text']) == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    $name = System::user()->Get('u_name');
    $email = System::user()->Get('u_email');
    $hideemail = System::user()->Get('u_hideemail');
    $site = System::user()->Get('u_homepage');
    $icq = System::user()->Get('u_icq');
    $uid = System::user()->Get('u_id');
    $text = SafeEnv($_POST['text'], 0, str);
    $vals = Values('', $topic_id, $uid, time(), $name, $site, $email, $hideemail, $icq, $text, getip(), 0);
    System::database()->Insert('forum_posts', $vals);
    // Обновляем время прочтения темы автором сообщения
    $user_id = System::user()->Get('u_id');
    System::database()->Delete('forum_topics_read', "`tid`='{$topic_id}' and `mid`='{$user_id}'");
    $time = time();
    $vals = "'{$user_id}','{$topic_id}','{$time}'";
    System::database()->Insert('forum_topics_read', $vals);
    // Информация о последнем сообщении в теме и форуме
    $forum['posts'] = (int) $forum['posts'] + 1;
    $topic['posts'] = (int) $topic['posts'] + 1;
    IndexForumSetLastPostInfo($forum, $topic);
    // Добавляем очков пользователю
    System::user()->ChargePoints(System::config('points/forum_post'));
    // Увеличиваем счётчик сообщений пользователя
    ForumCalcUserCounters(1);
    // Делаем рассылку подписчикам на эту тему
    Forum_Subscription_Send($topic_id);
    // Очищаем кэш форума
    ForumCacheClear();
    GO(Ufu('index.php?name=forum&op=showtopic&topic=' . $topic_id . '&view=lastpost#last', 'forum/topic{topic}-new.html'));
}
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');
}