<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$name = SafeDB($_GET['name'], 255, str);
$id = SafeDB($_GET['collid'], 11, int);
$coll = System::database()->GetColl($name, $id);
$install = "System::database()->InsertColl('{$name}', Unserialize('" . Serialize($coll) . "'), " . ($id - 1) . ");" . EOL;
$install2 = "System::database()->EditColl('{$name}', {$id}, Unserialize('" . Serialize($coll) . "'));" . EOL;
AddCenterBox('Информация для установки колонки таблицы');
FormRow('Установка', $site->TextArea('code', $install, 'style="width: 800px; height: 100px;" class="autofocus selectall"'));
FormRow('Редактирование', $site->TextArea('code', $install2, 'style="width: 800px; height: 100px;"'));
AddForm('', $site->Button('Назад', 'onclick="history.go(-1);"'));
AdminFdbAdminGenTableMenu($name);
function AdminConfigGroupEdit()
{
    $id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select(AdminConfigGroupTable(), "`id`='{$id}'");
    $group = System::database()->FetchRow();
    FormRow('Имя', System::site()->Edit('name', SafeDB($group['name'], 255, str), false, 'style="width:400px;" class="autofocus"'));
    FormRow('Заголовок', System::site()->Edit('hname', SafeDB($group['hname'], 255, str), false, 'style="width:400px;"'));
    FormRow('Описание', System::site()->TextArea('description', SafeDB($group['description'], 255, str), 'style="width:400px;height:100px;"'));
    FormRow('Видимая', System::site()->Check('visible', '1', $group['visible'] == '1'));
    AddCenterBox('Редактирование группы');
    AddForm('<form action="' . ADMIN_FILE . '?exe=config_admin&a=savegroup&id=' . $id . (AdminConfigPlugins() ? '&plugins=1' : '') . '" method="post">', System::site()->Button('Отмена', 'onclick="history.go(-1)"') . System::site()->Submit('Сохранить'));
}
function AdminBlocksEdit($a)
{
    global $config, $site, $user;
    // Для обратной совместимости со старыми блоками
    $showin = array('ALL_EXCEPT');
    $showin_uri = array();
    $template = '';
    $b_vi = 4;
    $b_en = 1;
    if (isset($_POST['type']) || $a == 'edit') {
        $b_pos = array('L' => false, 'R' => false, 'T' => false, 'B' => false);
        $b_pos = array('L' => false, 'R' => false, 'T' => false, 'B' => false, 'A' => false);
        $b_title = '';
        $b_vi = 4;
        $b_en = 1;
        $block_config = '';
        // Используется в подключаемых файлах
        if ($a == 'edit') {
            System::database()->Select('blocks', "`id`='" . SafeEnv($_GET['id'], 11, int) . "'");
            $r = System::database()->FetchRow();
            $b_title = SafeDB($r['title'], 255, str);
            $b_pos[SafeDB($r['position'], 1, str)] = true;
            $b_vi = SafeDB($r['view'], 1, int);
            $b_en = SafeDB($r['enabled'], 1, bool);
            $b_type = SafeDB($r['type'], 255, str);
            $template = SafeDB($r['template'], 255, str);
            $block_config = $r['config'];
            // Используется в подключаемых файлах
            $title = 'Редактирование блока';
            $a_form = ADMIN_FILE . '?exe=blocks&a=update&id=' . SafeEnv($_GET['id'], 11, int);
            $button = 'Сохранить изменения';
            if ($r['showin'] != '') {
                $showin = unserialize($r['showin']);
            }
            if ($r['showin_uri'] != '') {
                $showin_uri = unserialize($r['showin_uri']);
            }
        } else {
            $a_form = ADMIN_FILE . '?exe=blocks&a=newsave';
            $b_type = SafeEnv($_POST['type'], 255, str);
            $title = 'Настройка блока';
            $button = 'Создать';
            $showin[] = array('ALL_EXCEPT');
        }
        FormRow('Заголовок', System::site()->Edit('title', $b_title, false, 'style="width:400px;" class="autofocus"'));
        $constructor = System::config('blocks_dir') . $b_type . '/constructor.php';
        if (is_file($constructor)) {
            include_once $constructor;
        }
        $btems = GetBlockTemplates();
        $temdata = array();
        foreach ($btems as $tem) {
            System::site()->DataAdd($temdata, $tem, $tem, $tem == $template);
        }
        FormRow('Шаблон блока', System::site()->Select('template', $temdata));
        System::site()->DataAdd($posdata, 'Left', 'Колонка слева', $b_pos['L']);
        System::site()->DataAdd($posdata, 'Right', 'Колонка справа', $b_pos['R']);
        System::site()->DataAdd($posdata, 'Top', 'В центре сверху', $b_pos['T']);
        System::site()->DataAdd($posdata, 'Bottom', 'В центре снизу', $b_pos['B']);
        //System::site()->DataAdd($posdata, 'ABottom', 'A В центре снизу', $b_pos['A']);
        FormRow('Позиционирование', System::site()->Select('position', $posdata));
        VisibilityConditionsAdmin($showin, $showin_uri);
        FormRow('Кто видит', System::site()->Select('view', GetUserTypesFormData($b_vi)));
        FormRow('Включить', System::site()->Select('enabled', GetEnData($b_en, 'Да', 'Нет')));
        AddCenterBox($title);
        AddForm('<form action="' . $a_form . '" method="post">' . System::site()->Hidden('type', $b_type), System::site()->Button('Отмена', 'onclick="history.go(-1);"') . System::site()->Submit($button));
    } else {
        GO(ADMIN_FILE);
    }
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
if (isset($_POST['newname'])) {
    System::database()->RenameTable(SafeEnv($_GET['name'], 255, str), SafeEnv($_POST['newname'], 255, str));
    Audit('Управление БД: Переименование таблицы "' . $_GET['name'] . '" в "' . $_POST['newname'] . '"');
    GO(ADMIN_FILE . '?exe=dbadmin');
} else {
    AddCenterBox('Переименовать таблицу "' . SafeDB($_GET['name'], 255, str) . '"');
    FormRow('Новое имя', $site->Edit('newname', SafeDB($_GET['name'], 255, str), false, 'style="width: 210px;" class="autofocus"'));
    AddForm('<form action="' . ADMIN_FILE . '?exe=dbadmin&a=renametable&name=' . SafeEnv($_GET['name'], 255, str) . '" method="post">', $site->Button('Отмена', 'onclick="history.go(-1);"') . $site->Submit('Переименовать'));
}
/**
 * Генерирует форму редактирования пользователя в админ-панели.
 *
 * @param  $save_link Ссылка на обработчик формы (имя модуля и параметр action)
 * @param string $a Добавление или редавтирование пользователя (edit or add)
 * @param int $id Идентификатор пользователя
 * @param bool $isadmin Редактирование администратора (влияет на выборку и отключает активацию по email)
 * @param bool $EditProfile Редактирование своего профиля администратором (не может изменить свой статус если не системный администратор)
 * @return
 */
function AdminUserEditor($save_link, $a = 'add', $id = '0', $isadmin = false)
{
    $active = array(false, false, false);
    $SystemAdmin = System::user()->isSuperUser();
    $edit = $a == 'edit';
    $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 (!(groupIsSystem(SafeEnv($user['access'], 11, int)) && GetSystemAdminsCount() <= 1)) {
                // Если он не системный или системных больше 1
                $editStatus = true;
            }
            $editType = $editStatus;
        }
    } else {
        // Если пользователь
        $editStatus = true;
        // Все администраторы с доступом могут редактировать статус пользователя
        $editType = $SystemAdmin;
        // Только системные администраторы могут создавать администраторов
    }
    if ($editType) {
        $user_types_db = System::database()->Select('usertypes');
        $types = array('member' => array('member', 'Пользователь', false));
        foreach ($user_types_db as $type) {
            $types[$type['id']] = array(SafeDB($type['id'], 11, int), SafeDB($type['name'], 255, str), false);
        }
    }
    if ($edit) {
        $login = SafeDB($user['login'], 30, str);
        $mail = SafeDB($user['email'], 50, str);
        $hideemail = $user['hideemail'] == 1 ? true : false;
        $snews = $user['servernews'] == 1 ? true : false;
        $name = SafeDB($user['name'], 50, str);
        $tname = SafeDB($user['truename'], 250, str);
        $age = SafeDB($user['age'], 11, str);
        $city = SafeDB($user['city'], 100, str);
        $url = SafeDB($user['url'], 250, str);
        $icq = SafeDB($user['icq'], 15, str);
        $gmt = SafeDB($user['timezone'], 255, str);
        $about = SafeDB($user['about'], 0, str);
        $avatar = SafeDB($user['avatar'], 250, str);
        $apersonal = SafeDB($user['a_personal'], 1, int);
        if ($editStatus) {
            if ($user['active'] == '1') {
                $active[0] = true;
            } elseif ($user['active'] == '0' && $user['activate'] == '') {
                $active[1] = true;
            } elseif ($user['active'] == '0' && $user['activate'] != '') {
                $active[2] = true;
            }
        }
        if ($editType) {
            if ($user['type'] == '1') {
                $types[$user['access']][2] = true;
            } else {
                $types['member'][2] = true;
                //пользователь
            }
        }
        $caption = 'Сохранить';
        if ($isadmin) {
            if ($editProfile) {
                $title = 'Редактирование профиля';
            } else {
                $title = 'Редактирование администратора';
            }
        } else {
            $title = 'Редактирование пользователя';
        }
    } else {
        $login = '';
        $mail = '';
        $snews = false;
        $hideemail = false;
        $name = '';
        $tname = '';
        $age = '';
        $city = '';
        $url = '';
        $icq = '';
        $gmt = System::config('general/default_timezone');
        $about = '';
        $avatar = '';
        $apersonal = '0';
        if ($editStatus) {
            $active[0] = true;
        }
        if ($editType) {
            $types['member'][2] = true;
        }
        $caption = 'Добавить';
        $title = 'Добавить пользователя';
    }
    FormRow('Логин', System::site()->Edit('login', $login, false, 'style="width:400px;" class="autofocus"'));
    FormRow('Пароль', System::site()->Edit('pass', '', true, 'style="width:400px;"'));
    FormRow('Повторите пароль<br /><small>(для проверки)</small>', System::site()->Edit('rpass', '', true, 'style="width:400px;"'));
    FormRow('E-mail', System::site()->Edit('email', $mail, false, 'style="width:300px;"') . ' <label for="hideemail">Скрыть</label>&nbsp;' . System::site()->Check('hideemail', '1', $hideemail, 'id="hideemail"'));
    FormRow('<label for="snews">Рассылка</label>', System::site()->Check('snews', '1', $snews, 'id="snews"'));
    FormRow('Ник', System::site()->Edit('nikname', $name, false, 'style="width:400px;"'));
    FormRow('Настоящее имя', System::site()->Edit('realname', $tname, false, 'style="width:400px;"'));
    FormRow('Возраст', System::site()->Edit('age', $age, false, 'style="width:400px;"'));
    FormRow('Город', System::site()->Edit('city', $city, false, 'style="width:400px;"'));
    FormRow('Сайт', System::site()->Edit('homepage', $url, false, 'style="width:400px;"'));
    FormRow('ICQ', System::site()->Edit('icq', $icq, false, 'style="width:400px;"'));
    $gmt = GetGmtData($gmt);
    FormRow('Часовой пояс', System::site()->Select('gmt', $gmt, false, 'style="width:400px;"'));
    FormRow('О себе', System::site()->TextArea('about', $about, 'style="width:400px; height:200px;"'));
    $avatars = GetGalleryAvatarsData($avatar, $apersonal);
    if ($apersonal == '1') {
        $selected = GetPersonalAvatar($id);
    } else {
        $selected = GetGalleryAvatar($avatars[1]);
    }
    System::site()->AddJS('
	ShowAvatar = function(){
		if(document.userform.avatar.value==\'\'){
			document.userform.avatarview.src = \'' . (System::config('user/secure_avatar_upload') ? 'index.php?name=plugins&p=avatars_render&user='******'general/personal_avatars_dir') . $avatar) . '\';
		}else{
			document.userform.avatarview.src = \'' . (System::config('user/secure_avatar_upload') ? 'index.php?name=plugins&p=avatars_render&aname=' : System::config('general/avatars_dir')) . '\'+document.userform.avatar.value;
		}
	}');
    FormRow('Аватар', System::site()->Select('avatar', $avatars[0], false, 'onchange="ShowAvatar();"'));
    FormRow('', '<img id="avatarview" src="' . $selected . '" border="0">');
    FormRow('Загрузить аватар', System::site()->FFile('upavatar'));
    if ($editStatus) {
        FormRow('Активация', System::site()->Radio('activate', 'auto', $active[0]) . 'Активировать' . System::site()->Radio('activate', 'manual', $active[1]) . 'Не активировать' . (!$isadmin ? System::site()->Radio('activate', 'mail', $active[2]) . 'По E-mail' : ''));
    }
    if ($editType) {
        $user_types = array();
        foreach ($types as $type) {
            System::site()->DataAdd($user_types, $type[0], $type[1], $type[2]);
        }
        FormRow('Статус', System::site()->Select('status', $user_types));
    }
    TAddSubTitle($title);
    AddCenterBox($title);
    AddForm('<form name="userform" action="' . ADMIN_FILE . '?exe=' . $save_link . '&id=' . $id . '" method="post"  enctype="multipart/form-data">', System::site()->Button('Отмена', 'onclick="history.go(-1);"') . System::site()->Submit($caption));
}
 /**
  * Редактор категорий
  * @param null   $CatId
  * @param null   $ToId
  * @param string $OtherUrlParams
  * @return void
  */
 public function CatEditor($CatId = null, $ToId = null, $OtherUrlParams = '')
 {
     $title = '';
     $desc = '';
     $icon = '';
     $boxtitle = 'Добавить категорию';
     $save_met = $this->save_met;
     if ($CatId != null) {
         $cat = System::database()->SelectOne($this->Table, "`id`='{$CatId}'");
         $title = SafeDB($cat['title'], 255, str);
         $desc = SafeDB($cat['description'], 0, str, false);
         $icon = SafeDB($cat['icon'], 255, str);
         $parent = SafeDB($cat['parent'], 11, int);
         $boxtitle = 'Редактирование категории';
         $save_met = $this->save_met . '&' . $this->id_par_name . '=' . $CatId;
         $cmd = 'Сохранить изменения';
     } else {
         if ($ToId != null) {
             $parent = $ToId;
         } elseif (isset($_GET['_cat_adto'])) {
             $parent = SafeEnv($_GET['_cat_adto'], 11, int);
         } else {
             $parent = -1;
         }
         $cmd = 'Добавить';
     }
     $cats_data = $this->GetCatsData($parent, false, true, $CatId, true);
     FormRow('В категорию', System::site()->Select('cat', $cats_data, false, $parent == -1 ? 'class="autofocus"' : ''));
     FormRow('Имя категории', System::site()->Edit('title', $title, false, 'maxlength="250" style="width:400px;"' . ($parent != -1 ? 'class="autofocus"' : '')));
     FormRow('Иконка', System::site()->Edit('icon', $icon, false, 'maxlength="250" style="width:400px;"'));
     FormTextRow('Описание', System::site()->HtmlEditor('desc', $desc));
     AddCenterBox($boxtitle);
     AddForm('<form action="' . ADMIN_FILE . '?exe=' . $this->module . '&' . $this->action_par_name . '=' . $save_met . $OtherUrlParams . '" method="post">', System::site()->Button('Отмена', 'onclick="history.go(-1);"') . System::site()->Submit($cmd));
 }
function AdminNewsEditTopic()
{
    global $news_access_edittopics;
    if (!isset($_GET['id']) || !$news_access_edittopics) {
        System::admin()->AccessDenied();
    }
    AddCenterBox('Редактирование раздела');
    UseScript('jquery_ui', 'colorbox?theme=admin');
    $id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select('news_topics', "`id`='" . $id . "'");
    $topic = System::database()->FetchRow();
    FormRow('Название раздела', System::admin()->Edit('topic_name', SafeDB($topic['title'], 255, str), false, 'maxlength="255" style="width:400px;" class="autofocus"'));
    FormTextRow('Описание (HTML)', System::admin()->HtmlEditor('topic_description', SafeDB($topic['description'], 255, str), 600, 200));
    $image = SafeDB($topic['image'], 255, str);
    list($width, $height) = SafeDB(explode(':', System::config('news/topics_tmb_size')), 11, int);
    FormRow('Изображение', System::admin()->FileManager('topic_image', $image) . '<br>
		<a href="' . $image . '" class="filemanager_topic_image colorbox" data-content="href:path" target="_blank">
			<img src="' . GetThumb($image, $width, $height) . '" class="filemanager_topic_image" data-content="src:tmb" style="margin-top: 5px; max-width: 250px;">
		</a>');
    AddForm('<form name="topicsform" action="' . ADMIN_FILE . '?exe=news&a=savetopic&id=' . $id . '" method="post" enctype="multipart/form-data" name="topicsform">', System::admin()->Button('Отмена', 'onclick="history.go(-1);"') . System::admin()->Submit('Сохранить'));
}
function AdminSiteMessagesEditor()
{
    $title = '';
    $text = '';
    $showin = array('ALL_EXCEPT');
    $extrauri = array();
    $time = '0';
    $view = 4;
    $enabled = 1;
    $view_title = array(false, false);
    $position = array(false, false);
    $resettime = '';
    if (!isset($_GET['id'])) {
        $view_title[1] = true;
        $position[1] = true;
        $url = '';
        $btitle = 'Создать сообщение';
        $method = 'Создать';
        $a = 'add';
    } else {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('messages', "`id`='{$id}'");
        $msg = System::database()->FetchRow();
        $title = SafeDB($msg['title'], 250, str);
        $text = SafeDB($msg['text'], 0, str, false);
        $time = SafeDB($msg['expire'], 11, int);
        if ($time != '0') {
            $total = TotalTime(time(), SafeDB($msg['date'], 11, int) + Day2Sec * SafeDB($msg['expire'], 11, int));
            $resettime = 'Осталось времени ' . $total['sdays'] . ' и ' . $total['shours'];
        }
        $showin = unserialize($msg['showin']);
        $extrauri = unserialize($msg['showin_uri']);
        $view_title[SafeDB($msg['view_title'], 1, int)] = true;
        $position[SafeDB($msg['position'], 1, int)] = true;
        $view = SafeDB($msg['view'], 1, int);
        $enabled = SafeDB($msg['active'], 1, int);
        $url = '&id=' . $id;
        $btitle = 'Редактирование сообщения';
        $method = 'Сохранить изменения';
        $a = 'edit';
    }
    FormRow('Заголовок', System::site()->Edit('title', $title, false, 'maxlength="250" style="width:400px;" class="autofocus"'));
    FormRow('Показывать заголовок', System::site()->Radio('vtitle', 'on', $view_title[1]) . 'Да&nbsp;' . System::site()->Radio('vtitle', 'off', $view_title[0]) . 'Нет');
    FormTextRow('Текст сообщения', System::site()->HtmlEditor('text', $text, 625, 300));
    FormRow('Отображать&nbsp;дней:<br /><small> (0 - неограниченно)</small>', System::site()->Edit('time', $time, false, 'maxlength="3" style="width:40px;"') . $resettime);
    if ($a == 'edit') {
        FormRow('Сбросить таймер', System::site()->Check('resettime', '1', false));
    }
    VisibilityConditionsAdmin($showin, $extrauri);
    System::site()->DataAdd($posd, 'top', 'Вверху', $position[1]);
    System::site()->DataAdd($posd, 'bottom', 'Внизу', $position[0]);
    FormRow('Положение', System::site()->Select('position', $posd));
    FormRow('Кто видит', System::site()->Select('view', GetUserTypesFormData($view)));
    FormRow('Включить', System::site()->Select('enabled', GetEnData($enabled)));
    AddCenterBox($btitle);
    AddForm('<form action="' . ADMIN_FILE . '?exe=messages&a=save' . $url . '" method="post">', System::site()->Button('Отмена', 'onclick="history.go(-1)"') . System::site()->Submit($method));
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$title = 'Настройка новостного блока';
$topic_id = 0;
$count = 10;
$template = 'standart.html';
if ($a == 'edit') {
    $bconf = unserialize($block_config);
    $topic_id = SafeDB($bconf['topic'], 11, int);
    $count = SafeDB($bconf['count'], 11, int);
}
System::database()->Select('news_topics', '');
$topicdata = array();
System::admin()->DataAdd($topicdata, '0', 'Все разделы', $topic_id == 0);
while ($topic = System::database()->FetchRow()) {
    System::admin()->DataAdd($topicdata, $topic['id'], $topic['title'], $topic['id'] == $topic_id);
}
FormRow('Раздел новостей', System::admin()->Select('topic', $topicdata, false, ''));
FormRow('Количество новостей', System::admin()->Edit('count', $count, false, 'style="width: 40px;" maxlength="11"'));
function AdminDownloadsFileEditor($action)
{
    if (!System::user()->CheckAccess2('downloads', 'edit_files')) {
        System::admin()->AccessDenied();
    }
    $category = isset($_GET['to']) ? SafeDB($_GET['to'], 11, int) : 0;
    $title = '';
    $url = '';
    $file_size = '0';
    $size_type = 'b';
    $shortdesc = '';
    $description = '';
    $image = '';
    $author = '';
    $author_site = '';
    $author_email = '';
    $file_ver = '';
    $allow_comments = true;
    $allow_votes = true;
    $view = 4;
    $active = true;
    if (!isset($_GET['id'])) {
        $action = 'addfilesave';
        $top = 'Добавить файл';
        $cap = 'Добавить';
    } else {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('downloads', "`id`='{$id}'");
        $file = System::database()->FetchRow();
        $category = SafeDB($file['category'], 11, int);
        $title = SafeDB($file['title'], 250, str);
        $url = SafeDB($file['url'], 250, str);
        $file_size = SafeDB($file['size'], 11, real);
        $size_type = SafeDB($file['size_type'], 1, str);
        $shortdesc = SafeDB($file['shortdesc'], 0, str, false);
        $description = SafeDB($file['description'], 0, str, false);
        $image = SafeDB($file['image'], 250, str);
        $author = SafeDB($file['author'], 200, str);
        $author_site = SafeDB($file['author_site'], 250, str);
        $author_email = SafeDB($file['author_email'], 50, str);
        $file_ver = SafeDB($file['file_version'], 250, str);
        $allow_comments = SafeDB($file['allow_comments'], 1, int);
        $allow_votes = SafeDB($file['allow_votes'], 1, int);
        $view = SafeDB($file['view'], 1, int);
        $active = SafeDB($file['active'], 1, int);
        $action = 'editfilesave&id=' . $id;
        $top = 'Редактирование файла';
        $cap = 'Сохранить изменения';
    }
    $cats_data = AdminDownloadsGetTree()->GetCatsData($category);
    if (count($cats_data) == 0) {
        $back_to_form = SaveRefererUrl();
        AddTextBox($top, 'Нет категорий для добавления! ' . System::admin()->SpeedButton('Добавить категорию', ADMIN_FILE . '?exe=downloads&a=cateditor&back=' . $back_to_form, '', true, true));
        return;
    }
    $filesize_data = array();
    System::site()->DataAdd($filesize_data, 'b', 'Байт', $size_type == 'b');
    System::site()->DataAdd($filesize_data, 'k', 'Килобайт', $size_type == 'k');
    System::site()->DataAdd($filesize_data, 'm', 'Мегабайт', $size_type == 'm');
    System::site()->DataAdd($filesize_data, 'g', 'Гигабайт', $size_type == 'g');
    $max_file_size = ini_get('upload_max_filesize');
    AddCenterBox($top);
    FormRow('В категорию', System::site()->Select('category', $cats_data, false, $category == 0 ? 'class="autofocus"' : ''));
    FormRow('Название', System::site()->Edit('title', $title, false, 'style="width:400px;"' . ($category != 0 ? ' class="autofocus"' : '')));
    FormRow('Путь к файлу', System::site()->Edit('url', $url, false, 'style="width:400px;"'));
    //FormRow('Путь к файлу', System::site()->FileManager( 'url', $url, 400));
    FormRow('Загрузить файл<br />(<small>Максимальный размер файла: ' . $max_file_size . '</small>)', System::site()->FFile('upload_file') . '<br /><div style="width: 400px; word-wrap:break-word;">Разрешенные форматы:<br />' . System::config('downloads/file_exts') . '</div>');
    FormRow('Размер файла', System::site()->Edit('size', $file_size, false, 'style="width:200px;"') . ' ' . System::site()->Select('filesize_type', $filesize_data));
    AdminImageControl('Изображение', 'Загрузить изображение', $image, System::config('downloads/images_dir'));
    FormTextRow('Краткое описание', System::site()->HtmlEditor('shortdesc', $shortdesc, 600, 200));
    FormTextRow('Полное описание', System::site()->HtmlEditor('description', $description, 600, 400));
    FormRow('Версия файла', System::site()->Edit('version', $file_ver, false, 'style="width:400px;"'));
    FormRow('Автор', System::site()->Edit('author', $author, false, 'style="width:400px;"'));
    FormRow('E-mail автора', System::site()->Edit('author_email', $author_email, false, 'style="width:400px;"'));
    FormRow('Сайт автора', System::site()->Edit('author_site', $author_site, false, 'style="width:400px;"'));
    FormRow('Комментарии', System::site()->Select('allow_comments', GetEnData($allow_comments, 'Разрешить', 'Запретить')));
    FormRow('Оценки', System::site()->Select('allow_votes', GetEnData($allow_votes, 'Разрешить', 'Запретить')));
    FormRow('Кто видит', System::site()->Select('view', GetUserTypesFormData($view)));
    FormRow('Активен', System::site()->Select('active', GetEnData($active, 'Да', 'Нет')));
    if (!isset($_REQUEST['back'])) {
        $_REQUEST['back'] = SaveRefererUrl(ADMIN_FILE . '?exe=downloads');
    }
    AddForm('<form action="' . ADMIN_FILE . '?exe=downloads&a=' . $action . '&back=' . SafeDB($_REQUEST['back'], 255, str) . '" method="post" enctype="multipart/form-data" name="edit_form">', System::site()->Button('Отмена', 'onclick="history.go(-1)"') . System::site()->Submit($cap));
}
/**
 * Редактирование категории
 * @return void
 */
function AdminPagesCatEditor()
{
    $id = -1;
    $title = '';
    $parent_id = -1;
    if (isset($_GET['parent'])) {
        $parent_id = SafeEnv($_GET['parent'], 11, int);
    }
    $view = array(1 => false, 2 => false, 3 => false, 4 => false);
    $enabled = true;
    $showinmenu = true;
    if (!isset($_GET['id'])) {
        $view[4] = true;
        $form_title = 'Добавить категорию';
        $submit = 'Добавить';
    } else {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('pages', "`id`='{$id}'");
        $pg = System::database()->FetchRow();
        $parent_id = SafeEnv($pg['parent'], 11, int);
        $title = SafeEnv($pg['title'], 255, str);
        $view[SafeDB($pg['view'], 1, int)] = true;
        $enabled = SafeDB($pg['enabled'], 1, bool);
        $showinmenu = SafeDB($pg['showinmenu'], 1, bool);
        $form_title = 'Редактирование категории';
        $submit = 'Сохранить изменения';
    }
    // Возможные родительские страницы
    $pages = System::database()->Select('pages');
    SortArray($pages, 'order');
    $tree = new Tree($pages);
    $cats_data = $tree->GetCatsData($parent_id, false, true, $id, true);
    // Кто видит
    $visdata = array();
    System::site()->DataAdd($visdata, 'all', 'Все', $view['4']);
    System::site()->DataAdd($visdata, 'members', 'Только пользователи', $view['2']);
    System::site()->DataAdd($visdata, 'guests', 'Только гости', $view['3']);
    System::site()->DataAdd($visdata, 'admins', 'Только администраторы', $view['1']);
    FormRow('Родительская страница', System::site()->Select('parent_id', $cats_data, false, $parent_id == -1 ? 'class="autofocus"' : ''));
    FormRow('Заголовок', System::site()->Edit('title', $title, false, 'style="width:400px;" maxlength="255"' . ($parent_id != -1 ? ' class="autofocus"' : '')));
    FormRow('Кто видит', System::site()->Select('view', $visdata));
    FormRow('Показать в меню', System::admin()->Select('showinmenu', GetEnData($showinmenu, 'Да', 'Нет')));
    FormRow('Включить', System::admin()->Select('enabled', GetEnData($enabled, 'Да', 'Нет')));
    AddCenterBox($form_title);
    AddForm('<form action="' . ADMIN_FILE . '?exe=pages&a=savecat' . ($id != -1 ? '&id=' . $id : '') . '" method="post">', System::site()->Button('Отмена', 'onclick="history.go(-1)"') . System::site()->Submit($submit));
}
function AdminFeedBackEditor()
{
    $name = '';
    $email = '';
    $active = array(false, false);
    if (!isset($_GET['id'])) {
        $active[1] = true;
        $headt = 'Добавить департамент';
        $bbb = 'Добавить';
    } elseif (isset($_GET['id'])) {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('feedback', "`id`='" . $id . "'");
        $fb = System::database()->FetchRow();
        $name = SafeDB($fb['name'], 255, str);
        $email = SafeDB($fb['email'], 50, str);
        $active[$fb['active']] = true;
        $headt = 'Редактирование департамента';
        $bbb = 'Сохранить изменения';
    }
    FormRow('Название', System::site()->Edit('name', $name, false, 'style="width:200px;" class="autofocus"'));
    FormRow('E-mail', System::site()->Edit('email', $email, false, 'style="width:200px;"'));
    FormRow('Включить', System::site()->Select('enabled', GetEnData($active[1])));
    AddCenterBox($headt);
    AddForm('<form action="' . ADMIN_FILE . '?exe=feedback&a=save' . (isset($id) ? '&id=' . $id : '') . '" method="post">', System::site()->Submit($bbb));
}
/**
 * Выводит поля формы в админке, для настройки видимости объекта на определенных страницах сайта.
 * @param array|string $Conditions
 * @param array|string $Uri
 */
function VisibilityConditionsAdmin($Conditions = array(), $Uri = array())
{
    if (is_string($Conditions)) {
        $Conditions = unserialize($Conditions);
    }
    if (is_string($Uri)) {
        $Uri = unserialize($Uri);
    }
    $extrauri = SafeDB(implode(WIN_EOL, $Uri), 0, str);
    // Загружаем все модули из базы данных которые работают с пользователем
    $mods = System::database()->Select('modules', "`isindex`='1'");
    array_unshift($mods, array('name' => 'Главная страница', 'folder' => 'INDEX'));
    $num = 0;
    $ac = '';
    $ac .= Indent('
		<table width="100%" cellspacing="0" cellpadding="0" style="margin-bottom: 5px;">
			<tr>
				<td style="border: none;"><label>' . System::site()->Radio('showin[]', 'SELECT_ONLY', in_array('SELECT_ONLY', $Conditions) || !in_array('ALL_EXCEPT', $Conditions)) . '<span style="display: inline-block; vertical-align: top; padding-top: 3px;">Показывать только:</span></label></td>
				<td style="border: none;"><label>' . System::site()->Radio('showin[]', 'ALL_EXCEPT', in_array('ALL_EXCEPT', $Conditions)) . '<span style="display: inline-block; vertical-align: top; padding-top: 3px;">Показывать везде, кроме:<span></label></td>
			</tr>
		</table>
		<table width="100%" cellspacing="0" cellpadding="0" style="margin-bottom: 5px;">
	');
    foreach ($mods as $a) {
        if ($num == 0) {
            $ac .= '<tr>';
        }
        $num++;
        $ac .= '<td style="border: none;"><label>' . System::site()->Check('showin[]', SafeDB($a['folder'], 255, str), in_array(SafeDB($a['folder'], 255, str), $Conditions)) . '<span style="display: inline-block; vertical-align: top; padding-top: 3px;">' . SafeDB($a['name'], 255, str) . '</span></label></td>';
        if ($num == 3) {
            $ac .= '</tr>';
            $num = 0;
        }
    }
    if ($num != 0) {
        $ac .= '</tr>';
    }
    $ac .= Indent('
		</table>
		<table width="100%" cellspacing="0" cellpadding="0" style="margin-bottom: 5px;">
			<tr>
				<td style="border: none; padding-bottom: 4px;">Страницы (URL):<br>Например: /index.php?name=pages&amp;file=page или /pages/page.html. По одному на строку.</td>
			</tr>
			<tr>
				<td style="border: none;">' . System::site()->TextArea('extra_uri', $extrauri, 'style="width: 95%; min-width: 400px; height: 100px;"') . '</td>
			</tr>
		</table>
	');
    System::admin()->FormTitleRow('Параметры видимости');
    FormRow('', $ac);
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$count = 1;
$cat = 0;
$tree = new AdminTree('gallery_cats');
$tree->module = 'gallery';
$tree->obj_table = 'gallery';
$tree->obj_cat_coll = 'cat_id';
$tree->showcats_met = 'cats';
$tree->id_par_name = 'id';
$tree->index_id_par_name = 'cat';
if ($a == 'edit') {
    $bconf = unserialize($block_config);
    $count = $bconf['count'];
    $cat = $bconf['cats'];
}
$cat_data = $tree->GetCatsData($cat);
System::site()->DataAdd($cat_data, 0, 'Все категории', $cat == 0);
FormRow('Количество показываемых изображений', System::admin()->Edit('count', $count, false, 'style="width: 400px;"'));
FormRow('Показывать из категории', System::admin()->Select('cats[]', $cat_data, true, 'style="width: 200px;"'));
function AdminUserAvatarsGallery()
{
    global $galeryedit;
    TAddSubTitle('Галерея аватар');
    if (isset($_GET['user']) && $_GET['user'] == '1') {
        $personal = true;
        $dir = System::config('general/personal_avatars_dir');
        $dirlink = System::admin()->Link('Показать аватары из галереи', ADMIN_FILE . '?exe=user&a=avatars');
        $users = System::database()->Select('users', "`type`='2'");
        $c = sizeof($users);
        for ($i = 0; $i < $c; $i++) {
            $users[$users[$i]['avatar']] = $i;
        }
    } else {
        $personal = false;
        $dir = System::config('general/avatars_dir');
        $dirlink = System::admin()->Link('Показать аватары пользователей', ADMIN_FILE . '?exe=user&a=avatars&user=1');
    }
    $avatars2 = GetFiles($dir, false, true, '.gif.jpg.jpeg.png');
    $avatars = array();
    foreach ($avatars2 as $av) {
        $name = GetFileName($av, true);
        $sub = substr($name, -3);
        if ($sub != 'x24' && $sub != 'x64') {
            $avatars[] = $av;
        }
    }
    $c = count($avatars);
    $allsize = 0;
    $text = '<table cellspacing="0" cellpadding="0" class="cfgtable">';
    if ($c > 0) {
        $col = 0;
        for ($i = 0; $i < $c; $i++) {
            if ($col == 0) {
                $text .= '<tr>';
            }
            $col++;
            $imagfn = $dir . $avatars[$i];
            $size = getimagesize($imagfn);
            $fsize = filesize($imagfn);
            $allsize = $allsize + $fsize;
            if ($galeryedit) {
                $funcs = System::admin()->SpeedConfirm('Удалить', ADMIN_FILE . '?exe=user&a=delavatar&filename=' . $avatars[$i] . ($personal ? '&personal' : ''), 'images/admin/delete.png', 'Удалить аватар?');
            } else {
                $funcs = '&nbsp;';
            }
            $text .= '<td align="center">
				<table cellspacing="0" cellpadding="0" align="center" style="border:none; background: none;">
				<tr style="border:none; background: none;">
					<td style="border:none; background: none;"><a href="' . $imagfn . '" target="_blank"><img src="' . $imagfn . '" border="0" width="64" title="(' . $size[0] . ' x ' . $size[1] . ', ' . FormatFileSize($fsize) . ') ' . $avatars[$i] . '" /></a></td>
					<td valign="top" style="border:none; background: none;">' . $funcs . '</td>
				</tr>
				';
            if ($personal && isset($users[$avatars[$i]])) {
                $text .= '<tr><td colspan="2" align="left" style="border:none; background: none;"><a href="' . ADMIN_FILE . '?exe=user&a=edituser&id=' . SafeDB($users[$users[$avatars[$i]]]['id'], 11, int) . '">' . SafeDB($users[$users[$avatars[$i]]]['name'], 255, str) . '</a></td></tr>';
            }
            $text .= '</table></td>';
            if ($col == 5) {
                $text .= '</tr>';
                $col = 0;
            }
        }
        if ($col < 5) {
            $text .= '<td colspan="' . (5 - $col) . '"></td>';
            $text .= '</tr>';
        }
    } else {
        $text .= '<tr><td>В галерее нет ни одного аватара.</td></tr>';
    }
    $text .= '</table>';
    $info = '<table cellspacing="0" cellpadding="0" border="0" class="cfgtable">
		<tr>
		<td width="34%">Аватар в галерее: ' . $c . '</td>
		<td width="33%">Общий размер: ' . FormatFileSize($allsize) . '</td>
		<td>' . $dirlink . '</td>
		</tr>
	</table>';
    $text = $info . $text;
    AddCenterBox('Галерея аватар', $text);
    AddText($text);
    if (!$personal && $galeryedit) {
        System::admin()->FormTitleRow('Загрузить аватар');
        FormRow('Выберите файл', System::site()->FFile('avatar'));
        AddForm(System::site()->FormOpen(ADMIN_FILE . '?exe=user&a=saveavatar', 'post', true), System::site()->Submit('Загрузить'));
    }
    AddText('<br />');
}
function AdminFormsFieldEditor($action)
{
    global $cl_plugins, $cs_plugins;
    if (!isset($_GET['id'])) {
        GO(ADMIN_FILE . '?exe=forms');
    }
    $id = SafeEnv($_GET['id'], 11, int);
    $collsd = array();
    for ($i = 1; $i < 11; $i++) {
        System::site()->DataAdd($collsd, $i, $i);
    }
    $getfuncdata = array();
    System::site()->DataAdd($getfuncdata, '', '');
    foreach ($cl_plugins as $pl) {
        System::site()->DataAdd($getfuncdata, $pl[0], $pl[0]);
    }
    $savefuncdata = array();
    System::site()->DataAdd($savefuncdata, '', '');
    foreach ($cs_plugins as $pl) {
        System::site()->DataAdd($savefuncdata, $pl[0], $pl[0]);
    }
    $controls = array();
    System::site()->DataAdd($controls, 'edit', 'Текстовое поле');
    System::site()->DataAdd($controls, 'text', 'Область редактирования');
    System::site()->DataAdd($controls, 'combo', 'Раскрывающийся список');
    System::site()->DataAdd($controls, 'list', 'Список (мультивыделение)');
    System::site()->DataAdd($controls, 'check', 'Флажки');
    System::site()->DataAdd($controls, 'radio', 'Радиокнопки');
    System::site()->DataAdd($controls, 'file', 'Файл');
    $datatypes = array();
    System::site()->DataAdd($datatypes, 'int', 'Целочисленный');
    System::site()->DataAdd($datatypes, 'float', 'Вещественный');
    System::site()->DataAdd($datatypes, 'string', 'Текстовый');
    System::site()->DataAdd($datatypes, 'bool', 'Логический');
    System::site()->DataAdd($datatypes, 'file', 'Файл');
    $required = false;
    if ($action == 'add') {
        $hname = '';
        $name = '';
        $width = '';
        $height = '';
        $length = '0';
        $values = '';
        $cp = 'Добавить';
        $edit = false;
        System::admin()->FormTitleRow('Добавить поле');
    } else {
        $index = SafeEnv($_GET['index'], 11, int);
        System::database()->Select('forms', "`id`='{$id}'");
        $form = System::database()->FetchRow();
        $fields = unserialize($form['form_data']);
        $field = $fields[$index];
        $hname = $field['hname'];
        $name = $field['name'];
        $stype = FormsParseParams(explode(':', $field['kind']));
        $width = $stype['width'];
        $height = $stype['height'];
        $cols = $stype['cols'];
        $required = $stype['required'];
        $controls['selected'] = $stype['control'];
        $collsd['selected'] = $cols;
        $vv = explode(':', $field['values']);
        if (count($vv) == 2 && FormsConfigCheck2Func($vv[0], $vv[1])) {
            $getfuncdata['selected'] = $vv[1];
            $values = '';
        } else {
            $values = $field['values'];
        }
        if (function_exists($field['savefunc'])) {
            $savefuncdata['selected'] = $field['savefunc'];
        }
        $type = explode(',', $field['type']);
        $datatypes['selected'] = $type[1];
        $length = $type[0];
        $cp = 'Сохранить изменения';
        $edit = true;
    }
    FormRow('Название', System::site()->Edit('hname', $hname, false, 'maxlength="250" style="width:400px;" class="autofocus"'));
    FormRow('Имя HTML (уникальное для всех полей)', System::site()->Edit('name', $name, false, 'maxlength="250" style="width:400px;"'));
    FormRow('Элемент управления (укажите единицу измерения после ширины и высоты: %, px)', '<table>' . '<tr><td colspan="2" style="border:none; padding: 2px;">' . System::site()->Select('control', $controls) . '<td></tr>' . '<tr><td style="border:none; padding: 2px;">Ширина:</td>' . '<td style="border:none; padding: 2px;">' . System::site()->Edit('cwidth', $width, false, 'style="width:100px;"') . '</td></tr>' . '<tr><td style="border:none; padding: 2px;">Высота:</td>' . '<td style="border:none; padding: 2px;">' . System::site()->Edit('cheight', $height, false, 'style="width:100px;"') . '</td></tr>' . '<tr><td style="border:none; padding: 2px;">Колонок:</td>' . '<td style="border:none; padding: 2px;">' . System::site()->Select('ccols', $collsd) . '</td></tr>' . '</table>');
    FormTextRow('Возможные значения (Например: name:имя,name:имя, .... Только для элементов выбора.)', System::site()->TextArea('values', $values, 'style="width:600px;height:100px;"'));
    FormRow('Функция заполнения значений', System::site()->Select('valuesfunc', $getfuncdata));
    FormRow('Функция обработчик', System::site()->Select('savefunc', $savefuncdata));
    FormRow('Тип данных', System::site()->Select('datatype', $datatypes));
    FormRow('Длина поля (Размер файла Кб., 0 - неограниченно)', System::site()->Edit('maxlength', $length, false, 'style="width:60px;" maxlength="11"'));
    FormRow('Обязательное для заполнения', System::site()->Select('required', GetEnData($required, 'Да', 'Нет')));
    AddForm(System::site()->FormOpen(ADMIN_FILE . '?exe=forms&a=addfield&id=' . $id . ($edit ? '&index=' . $index : '')), ($edit ? System::site()->Button('Отмена', 'onclick="history.go(-1);"') : '') . System::site()->Submit($cp));
}
function AdminArticlesEditor()
{
    global $editarticles;
    if (!$editarticles) {
        System::admin()->AccessDenied();
    }
    $cat_id = isset($_GET['to']) ? SafeDB($_GET['to'], 11, int) : 0;
    $author = '';
    $email = '';
    $www = '';
    $title = '';
    $description = '';
    $article = '';
    $image = '';
    $auto_br_desc = false;
    $auto_br_article = false;
    $allow_comments = true;
    $allow_votes = true;
    $view = 4;
    $active = true;
    //Модуль SEO
    $seo_title = '';
    $seo_keywords = '';
    $seo_description = '';
    //
    $form = 0;
    $product_id = '';
    if (!isset($_GET['id'])) {
        $action = 'add';
        $top = 'Добавить статью';
        $cap = 'Добавить';
    } else {
        $id = SafeEnv($_GET['id'], 11, str);
        System::database()->Select('articles', "`id`='{$id}'");
        $art = System::database()->FetchRow();
        $cat_id = SafeDB($art['cat_id'], 11, int);
        $author = SafeDB($art['author'], 200, str);
        $email = SafeDB($art['email'], 50, str);
        $www = SafeDB($art['www'], 250, str);
        $title = SafeDB($art['title'], 255, str);
        $description = SafeDB($art['description'], 0, str, false);
        $article = SafeDB($art['article'], 0, str, false);
        $image = SafeDB($art['image'], 250, str);
        $auto_br_article = SafeDB($art['auto_br_article'], 1, bool);
        $auto_br_desc = SafeDB($art['auto_br_desc'], 1, bool);
        $active = SafeDB($art['active'], 1, bool);
        $allow_comments = SafeDB($art['allow_comments'], 1, int);
        $allow_votes = SafeDB($art['allow_votes'], 1, int);
        $view = SafeDB($art['view'], 1, int);
        //Модуль SEO
        $seo_title = SafeDB($art['seo_title'], 255, str);
        $seo_keywords = SafeDB($art['seo_keywords'], 255, str);
        $seo_description = SafeDB($art['seo_description'], 255, str);
        //
        $form = SafeDB($art['form'], 11, int);
        $product_id = SafeDB($art['product_id'], 255, str);
        $action = 'save&id=' . $id;
        $top = 'Редактирование статьи';
        $cap = 'Сохранить изменения';
    }
    System::admin()->AddJS(Indent('
		ArticlesPreviewOpen = function(){
			if(tinyMCE){
				tinyMCE.triggerSave();
			}
			var form_data = Admin.SerializeFormData(document.forms.edit_form);
			var left = parseInt(screen.width / 2) - 400;
			var top = parseInt(screen.height / 10);
			var wp = window.open("", "Preview", "resizable=yes,scrollbars=yes,menubar=no,status=no,location=no,width=800,height=600,left="+left+",top="+top+"");
			wp.document.open();
			$.ajax({
				type: "POST",
				url: "' . ADMIN_FILE . '?exe=articles&a=preview",
				data: form_data,
				dataType: "html",
				success: function(data){
					wp.document.write(data);
					wp.document.close();
				}
			});
		}
	'));
    $cats_data = AdminArticlesGetTree()->GetCatsData($cat_id);
    if (count($cats_data) == 0) {
        $back_to_form = SaveRefererUrl();
        AddTextBox($top, 'Нет категорий для добавления! ' . System::admin()->SpeedButton('Добавить категорию', ADMIN_FILE . '?exe=articles&a=cateditor&back=' . $back_to_form, '', true, true));
        return;
    }
    FormRow('В категорию', System::site()->Select('category', $cats_data, false, $cat_id == 0 ? 'class="autofocus"' : ''));
    FormRow('Заголовок', System::site()->Edit('title', $title, false, 'maxlength="250" style="width:400px;"' . ($cat_id != 0 ? 'class="autofocus"' : '')));
    //Модуль SEO
    FormRow('[seo] Заголовок страницы', System::site()->Edit('seo_title', $seo_title, false, 'style="width:400px;"'));
    FormRow('[seo] Ключевые слова', System::site()->Edit('seo_keywords', $seo_keywords, false, 'style="width:400px;"'));
    FormRow('[seo] Описание', System::site()->Edit('seo_description', $seo_description, false, 'style="width:400px;"'));
    //
    // Веб форма
    $forms = System::database()->Select('forms', "`active`='1'");
    $forms_data = array();
    System::site()->DataAdd($forms_data, '0', 'Нет', $form == 0);
    foreach ($forms as $f) {
        System::site()->DataAdd($forms_data, SafeDB($f['id'], 11, int), SafeDB($f['hname'], 255, str), $f['id'] == $form);
    }
    FormRow('Форма', System::site()->Select('form', $forms_data));
    FormRow('Код товара', System::site()->Edit('product_id', $product_id, false, 'maxlength="250" style="width:400px;"'));
    AdminImageControl('Изображение', 'Загрузить изображение', $image, System::config('articles/images_dir'));
    FormTextRow('Короткая статья (HTML)', System::site()->HtmlEditor('description', $description, 600, 200));
    FormRow('', 'Преобразовать текст в HTML: ' . System::site()->Select('auto_br_desc', GetEnData($auto_br_desc, 'Да', 'Нет')));
    FormTextRow('Полная статья (HTML)', System::site()->HtmlEditor('article', $article, 600, 400));
    FormRow('', 'Преобразовать текст в HTML: ' . System::site()->Select('auto_br_article', GetEnData($auto_br_article, 'Да', 'Нет')));
    FormRow('Автор', System::site()->Edit('author', $author, false, 'style="width:400px;" maxlength="50"'));
    FormRow('E-mail автора', System::site()->Edit('email', $email, false, 'style="width:400px;" maxlength="50"'));
    FormRow('Сайт автора', System::site()->Edit('www', $www, false, 'style="width:400px;" maxlength="250"'));
    FormRow('Комментарии', System::site()->Select('allow_comments', GetEnData($allow_comments, 'Разрешить', 'Запретить')));
    FormRow('Оценки', System::site()->Select('allow_votes', GetEnData($allow_votes, 'Разрешить', 'Запретить')));
    FormRow('Кто видит', System::site()->Select('view', GetUserTypesFormData($view)));
    FormRow('Активна', System::site()->Select('active', GetEnData($active, 'Да', 'Нет')));
    AddCenterBox($top);
    if (!isset($_REQUEST['back'])) {
        $_REQUEST['back'] = SaveRefererUrl(ADMIN_FILE . '?exe=articles');
    }
    AddForm('<form name="edit_form" action="' . ADMIN_FILE . '?exe=articles&a=' . $action . '&back=' . SafeDB($_REQUEST['back'], 255, str) . '" method="post" enctype="multipart/form-data">', System::site()->Button('Отмена', 'onclick="history.go(-1)"') . System::site()->Button('Предпросмотр', 'onclick="ArticlesPreviewOpen();"') . System::site()->Submit($cap));
}
function AdminForumEditor()
{
    $site = System::site();
    $f_title = '';
    $f_desc = '';
    if (CheckGet('parent')) {
        $f_parent = SafeDB($_GET['parent'], 11, int);
    } else {
        $f_parent = 0;
    }
    $f_view = 4;
    $f_status = 1;
    $f_admin_theme_add = array(false, false);
    $f_new_message_email = array(false, true);
    $f_no_link_guest = array(false, false);
    $rang_access = 0;
    $rang_add_theme = 0;
    $rang_message = 0;
    $close_topic = array(false, false);
    if (isset($_GET['id'])) {
        // Редактирование
        $id = SafeDB($_GET['id'], 11, int);
        System::database()->Select('forums', "`id`='{$id}'");
        $forum = System::database()->FetchRow();
        $f_title = SafeDB($forum['title'], 255, str);
        $f_desc = SafeDB($forum['description'], 0, str);
        $f_parent = SafeDB($forum['parent_id'], 11, int);
        $f_admin_theme_add[(int) $forum['admin_theme_add']] = true;
        $f_new_message_email[(int) $forum['new_message_email']] = true;
        $f_no_link_guest[(int) $forum['no_link_guest']] = true;
        $rang_access = SafeDB($forum['rang_access'], 11, int);
        $rang_add_theme = SafeDB($forum['rang_add_theme'], 11, int);
        $rang_message = SafeDB($forum['rang_message'], 11, int);
        $close_topic[(int) $forum['close_topic']] = true;
        $f_view = SafeDB($forum['view'], 1, int);
        $f_status = SafeDB($forum['status'], 1, int);
        $id_param = '&id=' . $id;
        $b_cap = 'Сохранить изменения';
        if ($f_parent == 0) {
            $c_cap = 'Редактирование категории';
        } else {
            $c_cap = 'Редактирование форума';
        }
    } else {
        // Добавление
        $f_title = '';
        $f_admin_theme_add[0] = true;
        $f_new_message_email[1] = true;
        $f_no_link_guest[0] = true;
        $close_topic[0] = true;
        $id_param = '';
        $b_cap = 'Добавить';
        if ($f_parent == 0) {
            $c_cap = 'Добавить категорию';
        } else {
            $c_cap = 'Добавить форум';
        }
    }
    FormRow('Название', $site->Edit('title', $f_title, false, 'style="width:400px;" maxlength="255" class="autofocus"'));
    if ($f_parent != 0) {
        $where = '';
        if (isset($_GET['id'])) {
            $where = " `id`<>'" . SafeEnv($_GET['id'], 11, int) . "'";
        }
        $forums = System::database()->Select('forums', $where);
        $cat = false;
        if (count($forums) == 0) {
            $cat = false;
        } else {
            foreach ($forums as $forum) {
                if ($forum['parent_id'] == 0) {
                    $cat = true;
                }
            }
        }
        SortArray($forums, 'order');
        $tree = ForumTree::Instance($forums);
        $tree->NumItemsCaption = '';
        $tree->TopCatName = 'Нет родительского раздела';
        $data = array();
        if ($cat) {
            $data = $tree->GetCatsDataF($f_parent, true, true);
        } else {
            $site->DataAdd($data, 0, $tree->TopCatName, true);
        }
        FormRow('Родительский раздел', $site->Select('sub_id', $data));
        FormTextRow('Описание', $site->HtmlEditor('desc', $f_desc, 600, 200));
    }
    System::admin()->FormTitleRow('Настройки форума');
    $endata = array();
    $site->DataAdd($endata, '1', 'Да', $f_admin_theme_add[1]);
    $site->DataAdd($endata, '0', 'Нет', $f_admin_theme_add[0]);
    FormRow('', 'Только администраторы могут создавать новые темы: ' . $site->Select('admin_theme_add', $endata));
    $endata = array();
    $site->DataAdd($endata, '1', 'Да', $f_no_link_guest[1]);
    $site->DataAdd($endata, '0', 'Нет', $f_no_link_guest[0]);
    FormRow('', 'Скрывать ссылки от гостей: ' . $site->Select('no_link_guest', $endata));
    $endata = array();
    $site->DataAdd($endata, '1', 'Да', $f_new_message_email[1]);
    $site->DataAdd($endata, '0', 'Нет', $f_new_message_email[0]);
    FormRow('', 'Разрешить подписку на уведомление о новых сообщениях в теме: ' . $site->Select('new_message_email', $endata));
    $endata = array();
    $site->DataAdd($endata, '1', 'Да', $close_topic[1]);
    $site->DataAdd($endata, '0', 'Нет', $close_topic[0]);
    FormRow('', 'Закрыть для обсуждения (будет доступен только просмотр): ' . $site->Select('close_topic', $endata));
    System::admin()->FormTitleRow('Настройка прав доступа по рангам пользователей');
    FormRow('Доступ (с меньшим рангом доступ будет закрыт)', ForumAdminGetUsersTypesComboBox('rang_access', $rang_access));
    FormRow('Создание тем (с меньшим рангом темы создавать будет запрещено)', ForumAdminGetUsersTypesComboBox('rang_add_theme', $rang_add_theme));
    FormRow('Создание сообщений в теме (с меньшим рангом сообщения создавать будет запрещено)', ForumAdminGetUsersTypesComboBox('rang_message', $rang_message));
    System::admin()->FormTitleRow('Параметры видимости');
    FormRow('Видят', $site->Select('view', GetUserTypesFormData($f_view)));
    FormRow('Включить', $site->Select('status', GetEnData($f_status, 'Да', 'Нет')));
    FormRow('Внимание', 'Ограничения прав и видимости действует на все дочерние форумы.');
    AddCenterBox($c_cap);
    AddForm($site->FormOpen(ADMIN_FILE . '?exe=forum&a=forum_save' . $id_param), $site->Submit($b_cap));
}
function AdminGalleryUploadForm()
{
    global $edit_images;
    if (!$edit_images) {
        System::admin()->AccessDenied();
    }
    $top = 'Мультизагрузка';
    $cat_id = isset($_GET['to']) ? SafeDB($_GET['to'], 11, int) : 0;
    $cats_data = AdminGalleryGetTree()->GetCatsData($cat_id);
    if (count($cats_data) == 0) {
        $back_to_form = SaveRefererUrl();
        AddTextBox($top, 'Нет категорий для добавления! ' . System::admin()->SpeedButton('Добавить категорию', ADMIN_FILE . '?exe=gallery&a=cateditor&back=' . $back_to_form, '', true, true));
        return;
    }
    System::admin()->AddCenterBox($top);
    UseScript('swfupload');
    $formid = uniqid();
    // Уникальный ID формы
    $_SESSION['uploadforms'][$formid] = array('photos' => array(), 'category' => '0', 'allow_comments' => '1', 'allow_votes' => '1', 'view' => '4', 'show' => '1');
    System::admin()->AddOnLoadJS(Indent('
		window.photo_id = 1;
		window.allUploadComplete = false;
		window.photosCountFiles = 0;
		window.photosUploaded = 0;

		// SWFUpload
		if(window.gallery_swfu){
			window.gallery_swfu.destroy();
		}else{
			window.GallerySubmitFormGuard = function(){
				if(window.photosCountFiles == 0){
					alert("Выберите фотографии для загрузки");
					return false;
				}
				if(!window.allUploadComplete){
					window.gallery_swfu.startUpload();
					Admin.ShowSplashScreen("Загрузка фотографий на хостинг");
					return false;
				}
				return true;
			}
		}

		window.gallery_swfu = new SWFUpload({
			upload_url: "' . ADMIN_FILE . '?exe=gallery&a=upload&formid=' . $formid . '",
			file_post_name : "up_image",
			post_params: {
				"action": "upload"
			},
			file_size_limit: "100 MB",
			file_types: "*.jpg; *.png; *.jpeg; *.gif",
			file_types_description: "Все файлы",
			file_upload_limit: 0,
			file_queue_limit: 0,
			debug: false,

			button_placeholder_id: "uploadbutton",
			button_width: "54",
			button_height: "18",
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_text: "<span class=\\"btnCap\\">Обзор<span>",
			button_text_style: ".btnCap{ align: center; color: #4F4F4F; font-family: Verdana, Tahoma, sans-serif; font-weight: bold; }",
			button_text_left_padding: 4,
			button_text_top_padding: 1,

			file_dialog_complete_handler: function(numFilesSelected, numFilesQueued, total){
				$("#uploadFilesCount").html("Выбрано " + total + " файл(ов)");
				window.photosCountFiles = total;
			},
			upload_progress_handler: function(file, bytesLoaded, bytesTotal){
				var current = window.photosUploaded + 1;
				Admin.SetSplashScreenMessage("Загрузка фотографий на хостинг: " + current + "/" + window.photosCountFiles + " (" + Math.round(bytesLoaded/bytesTotal*100) + "%)");
			},
			upload_complete_handler: function(file){
				window.photosUploaded++;
				if(window.photosUploaded == window.photosCountFiles){
					window.allUploadComplete = true;
					$("#galleryForm").submit();
				}
			}
		});
	'));
    FormRow('В категорию', System::site()->Select('category', $cats_data));
    FormRow('Выберите файлы', RemoveIndent('
		<div style="float: left;" id="uploadFilesCount">Выбрано 0 файл(ов)</div>
		&nbsp;&nbsp;&nbsp;&nbsp;
		<div class="button" style="float: right; border: 1px #ccc solid;">
			<span id="uploadbutton">
				<a href="http://www.adobe.com/go/getflashplayer">Get Adobe Flash player</a>
			</span>
		</div>
	'));
    FormRow('Комментарии', System::site()->Select('allow_comments', GetEnData(true, 'Разрешить', 'Запретить')));
    FormRow('Оценки', System::site()->Select('allow_votes', GetEnData(true, 'Разрешить', 'Запретить')));
    FormRow('Кто видит', System::site()->Select('view', GetUserTypesFormData(4)));
    FormRow('Показать', System::site()->Select('show', GetEnData(true, 'Да', 'Нет')));
    AddForm('<form action="' . ADMIN_FILE . '?exe=gallery&a=upload&formid=' . $formid . '" method="post" onsubmit="return GallerySubmitFormGuard();" id="galleryForm">', System::admin()->Hidden('action', 'preview') . System::admin()->Submit('Загрузить'));
}
function AdminSmilesEditSmile()
{
    global $smilies_dir, $mod;
    System::admin()->AddJS(Indent('
		SelectSmile = function(){
			var selected = $("#smile_file option:selected");
			$("#smile_image").prop("src", "' . $smilies_dir . '"+selected.val());
			$("#smile_code").val(selected.attr("code"));
			$("#smile_desc").val(selected.attr("description"));
		};
	'));
    $id = 0;
    $file = '';
    $code = '';
    $desc = '';
    $enabled = true;
    $box_title = 'Добавить смайлик';
    $submit = 'Добавить';
    if (isset($_GET['id'])) {
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('smilies', "`id`='{$id}'");
        $smile = System::database()->FetchRow();
        $file = $smile['file'];
        $code = SafeDB($smile['code'], 255, str);
        $desc = SafeDB($smile['desc'], 255, str);
        $enabled = SafeDB($smile['enabled'], 1, bool);
        $submit = 'Сохранить';
        $box_title = 'Редактирование смайлика';
        System::admin()->AddOnLoadJS('$("#smile_image").prop("src", "' . $smilies_dir . '"+$("#smile_file option:selected").val());');
    } else {
        System::admin()->AddOnLoadJS('SelectSmile();');
    }
    AddCenterBox($box_title);
    $smilies = System::database()->Select('smilies');
    $xor = array();
    if ($id == 0) {
        $xor =& $smilies;
    } else {
        foreach ($smilies as $smile) {
            if ($smile['id'] != $id) {
                $xor[] = $smile;
            }
        }
    }
    $smilies_data = AdminSmiliesGetData($file, $xor);
    if ($id == 0 && count($smilies_data) == 0) {
        System::admin()->Highlight('Загрузите изображения смайликов в папку <b>' . $smilies_dir . '</b> для добавления.');
        return;
    }
    FormRow('Изображение', System::site()->Select('file', $smilies_data, false, 'onchange="SelectSmile()" id="smile_file" class="autofocus"'));
    FormRow('Предпросмотр', '<img id="smile_image">');
    FormRow('Код', System::site()->Edit('code', $code, false, 'style="width: 200px;" id="smile_code"'));
    FormRow('Описание', System::site()->Edit('desc', $desc, false, 'style="width: 200px;" id="smile_desc"'));
    FormRow('Показывать', System::admin()->Select('indexview', GetEnData($enabled, 'Да', 'Нет')));
    AddForm('<form name="newsmile" action="' . $mod . '&a=save' . ($id != 0 ? '&id=' . $id : '') . '" method="post">', System::site()->Button('Отмена', 'onclick="history.go(-1)"') . System::site()->Submit($submit));
}
function AdminsEditGroup()
{
    global $action;
    if ($action == 'editgroup') {
        System::database()->Select('usertypes', "`id`='" . SafeEnv($_GET['id'], 11, int) . "'");
        $group = System::database()->FetchRow();
        $name = SafeDB($group['name'], 255, str);
        $color = SafeDB($group['color'], 9, str);
        $access = SafeDB($group['access'], 0, str, false, false);
        $image = SafeDB($group['image'], 250, str);
        $method = 'editsave&id=' . SafeEnv($_GET['id'], 11, int);
        $title = 'Редактирование группы';
        if ($group['system']) {
            $other = 'disabled';
        } else {
            $other = '';
        }
    } elseif ($action == 'addgroup') {
        $name = '';
        $color = '#000000';
        $image = '';
        $access = serialize(array());
        $method = 'addsave';
        $title = 'Добавить группу';
        $other = '';
    }
    FormRow('Название', System::site()->Edit('name', $name, false, 'style="width:400px;" class="autofocus"'));
    FormRow('Цвет', System::site()->Edit('color', $color, false, 'style="width:400px;"'));
    FormRow('Картинка', System::site()->Edit('image', $image, false, 'style="width:400px;"'));
    $access = AdminsGetAccessArray($access);
    $ac = '';
    foreach ($access as $a) {
        $ac .= '<table width="100%" cellspacing="0" cellpadding="3" style="border:1px #ABC5D8 solid;margin-bottom:2px;">';
        for ($i = 0, $c = count($a); $i < $c; $i++) {
            $ac .= '<tr>
			<td style="border:none;"><label>' . System::site()->Check('access[]', $a[$i][0] . ',' . $a[$i][1], $a[$i][3], $other) . '<span style="display: inline-block; vertical-align: top; padding-top: 3px;">' . $a[$i][2] . '</span></label></td>
			</tr>';
        }
        $ac .= '</table>';
    }
    FormRow('Доступ', $ac);
    AddCenterBox($title);
    AddForm('<form action="' . ADMIN_FILE . '?exe=admins&a=' . $method . '" method="post">', System::site()->Button('Отмена', 'onclick="history.go(-1);"') . System::site()->Submit('Сохранить'));
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
System::admin()->AddCenterBox('Создать таблицу');
FormRow('Имя таблицы (без префикса)', System::admin()->Edit('name', '', false, 'style="width: 200px;" class="autofocus"'));
FormRow('Количество полей', System::admin()->Edit('cols', '', false, 'style="width: 50px;" title="Введите сюда количество колонок"'));
AddForm('<form action="' . ADMIN_FILE . '?exe=dbadmin&a=newtable" method="post">', System::admin()->Submit('Далее', 'title="Перейти к след. шагу создания таблицы."'));
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$count = 10;
$title = 'Настройка блока для показа последних тем на форуме';
if ($a == 'edit') {
    $count = SafeDB($block_config, 11, int);
}
FormRow('Сколько последних тем показывать', System::admin()->Edit('count', $count, false, 'style="width:400px;"'));
function AdminGuestBookAnswerEditor()
{
    if (!System::user()->CheckAccess2('guestbook', 'answer')) {
        System::admin()->AccessDenied();
    }
    $id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select('guestbook', "`id`='" . $id . "'");
    if (System::database()->NumRows() > 0) {
        AddCenterBox('Ответ на сообщение');
        $msg = System::database()->FetchRow();
        if ($msg['answers'] == '') {
            $answers = array();
        } else {
            $answers = unserialize($msg['answers']);
        }
        if (array_key_exists(System::user()->Name(), $answers)) {
            $ans = $answers[System::user()->Name()];
        } else {
            $ans = '';
        }
        FormRow('Ответ', System::site()->TextArea('answer', HtmlChars($ans), 'style="width:400px;height:200px;" class="autofocus"'));
        if (isset($_GET['back'])) {
            $back = '&back=' . SafeDB($_GET['back'], 255, str);
        } else {
            $back = '';
        }
        AddForm('<form action="' . ADMIN_FILE . '?exe=guestbook&a=saveanswer&id=' . $id . $back . '" method="POST">', System::site()->Button('Отмена', 'onclick="history.go(-1);"') . System::site()->Submit('Сохранить'));
    } else {
        GO(ADMIN_FILE . '?exe=guestbook');
    }
}
    if (!isset($col['default'])) {
        $col['default'] = '';
    }
    if (!isset($col['attributes'])) {
        $col['attributes'] = '';
    }
    if (!isset($col['auto_increment'])) {
        $col['auto_increment'] = false;
    }
    $func = '';
    $func .= SpeedButton('Просмотреть информацию для установки', ADMIN_FILE . '?exe=dbadmin&a=viewcollinfo&name=' . $name . '&collid=' . $i, 'images/admin/info.png');
    $func .= System::admin()->SpeedConfirm('Удалить колонку', ADMIN_FILE . '?exe=dbadmin&a=deletecoll&name=' . $name . '&collid=' . $i, 'images/admin/delete.png', 'Удалить колонку?');
    $text .= '<tr>
	<td>' . $i . '</td>
	<td>' . SafeDB($col['name'], 255, str) . '</td>
	<td>' . SafeDB($col['type'], 255, str) . (isset($col['length']) ? '(' . SafeDB($col['length'], 11, int) . ')' : '') . '</td>
	<td>' . SafeDB($col['attributes'], 255, str) . '</td>
	<td>' . ($col['notnull'] ? '<font color="#0000FF">Нет</font>' : '<font color="#FF0000">Да</font>') . '</td>
	<td>' . SafeDB($col['default'], 255, str) . '</td>
	<td>' . ($col['auto_increment'] ? '<font color="#FF0000">Да</font>' : '<font color="0000FF">Нет</a>') . '</td>
	<td>' . $func . '</td>';
    System::site()->DataAdd($selcoldata, $i, SafeDB($col['name'], 255, str), $i == $colcount);
    $i++;
}
$text .= '</table><br />';
AddCenterBox('Структура таблицы "' . $name . '"');
AddText($text);
System::admin()->FormTitleRow('Вставить колонку');
FormRow('После', System::site()->Select('toindex', $selcoldata));
AddForm('<form action="' . ADMIN_FILE . '?exe=dbadmin&a=newcoll&name=' . $name . '" method="post">', $site->Submit('Далее', 'title="Перейти к след. шагу добавления колонки."'));
AdminFdbAdminGenTableMenu($name);
function AdminMailMail()
{
    if (isset($_GET['topic_id'])) {
        $topic_id = SafeEnv($_GET['topic_id'], 11, int);
    } else {
        $topic_id = 0;
    }
    $subject = '';
    $from = System::config('general/site_name');
    $from_email = System::config('general/site_email');
    $text = '';
    $text_html = '';
    $auto_br = array(false, false);
    if (!isset($_GET['id'])) {
        AddCenterBox('Создание новой рассылки');
        $auto_br[0] = true;
        $submit = System::site()->Submit('Разослать');
    } else {
        AddCenterBox('Редактирование');
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('mail_history', "`id`='{$id}'");
        $msg = System::database()->FetchRow();
        $topic_id = SafeDB($msg['topic_id'], 11, int);
        $subject = SafeDB($msg['subject'], 255, str);
        $from = System::config('general/site_name');
        $from_email = System::config('general/site_email');
        $text = SafeDB($msg['plain_text'], 0, str);
        $text_html = SafeDB($msg['text_html'], 0, str);
        $auto_br[SafeDB($msg['auto_br'], 11, int)] = true;
        $b = 'Сохранить изменения';
        $submit = System::site()->Button('Отмена', 'onclick="history.go(-1);"') . System::site()->Submit('Сохранить изменения');
    }
    System::database()->Select('mail_topics', '');
    $topicdata = array();
    while ($topic = System::database()->FetchRow()) {
        System::site()->DataAdd($topicdata, SafeDB($topic['id'], 11, int), SafeDB($topic['title'], 250, str), $topic['id'] == $topic_id);
    }
    FormRow('Тема рассылки', System::site()->Select('topic', $topicdata, false, ''));
    FormRow('Заголовок писем', System::site()->Edit('subject', $subject, false, 'style="width:400px;"'));
    FormRow('Имя отправителя', System::site()->Edit('from', $from, false, 'style="width:400px;"'));
    FormRow('Адрес Email отправителя', System::site()->Edit('from_email', $from_email, false, 'style="width:400px;"'));
    FormTextRow('Текст письма в текстовом формате', System::site()->TextArea('text', $text, 'style="width:600px;height:400px;"'));
    FormTextRow('Текст письма в HTML формате', System::site()->HtmlEditor('html', $text_html, 600, 400));
    FormRow('', '<label>' . System::site()->Check('auto_br', '1', $auto_br[1]) . '&nbsp;Преобразовать текст в HTML (если вы не используете визуальный редактор)</label>');
    AddForm('<form action="' . ADMIN_FILE . '?exe=mail&a=send' . (isset($id) ? '&id=' . $id : '') . '" method="POST">', $submit);
}
if ($action == 'editfield') {
    if (isset($_GET['where'])) {
        $where = $_GET['where'];
        $where_url = '&where=' . SafeDB($_GET['where'], 255, str);
    }
    $edit = true;
    $index = SafeEnv($_GET['index'], 255, int);
    $rows = System::database()->Select($table, $where);
    $row = $rows[$index];
}
$i = 0;
foreach ($columns as $col) {
    if ($edit) {
        $val = HtmlChars($row[$columns[$i]['name']]);
        $cap = 'Сохранить';
        $title = 'Редактирование записи';
    } else {
        $val = '';
        $cap = 'Добавить';
        $title = 'Добавление записи';
    }
    if (strtolower($col['type']) != 'text') {
        FormRow('<font color="#0000FF">' . (isset($col['auto_increment']) && $col['auto_increment'] == true ? '<u>' . $col['name'] . '</u>' : $col['name']) . '</font>' . '<br /><font color="#666666">' . $col['type'] . (isset($col['length']) ? '(' . $col['length'] . ')</font>' : '</font>'), System::admin()->Edit($col['name'], $val, false, 'style="width: 400px;"' . ($i == 0 ? ' class="autofocus"' : '')));
    } else {
        FormRow('<font color="#0000FF">' . $col['name'] . '</font>', System::admin()->TextArea($col['name'], $val, 'style="width: 400px; height: 200px;"' . ($i == 0 ? ' class="autofocus"' : '')));
    }
    $i++;
}
AddCenterBox($title);
AddForm('<form action="' . ADMIN_FILE . '?exe=dbadmin&a=' . ($edit ? 'editsave' : 'insertsave') . '&name=' . $table . ($edit ? '&index=' . $index : '') . $where_url . $back . '" method="post">', ($edit ? System::site()->Button('Отмена', 'onclick="history.go(-1)"') : '') . System::admin()->Submit($cap));
AdminFdbAdminGenTableMenu($table);
function AdminCommentsEdit()
{
    if (isset($_GET['page'])) {
        $page = SafeEnv($_GET['page'], 10, int);
    } else {
        $page = 1;
    }
    $id = SafeEnv($_GET['id'], 11, int);
    $table = SafeEnv($_GET['table'], 255, str);
    System::database()->Select($table, "`id`='{$id}'");
    $post = System::database()->FetchRow();
    $user_id = SafeDB($post['user_id'], 11, int);
    $user_name = SafeDB($post['user_name'], 255, str);
    $user_homepage = SafeDB($post['user_homepage'], 255, str);
    $user_email = SafeDB($post['user_email'], 255, str);
    $user_hideemail = $post['user_hideemail'] == 1 ? true : false;
    $user_ip = SafeDB($post['user_ip'], 19, str);
    $post_message = SafeDB($post['post_message'], 0, str, false);
    if ($user_id == 0) {
        FormRow('Имя', System::admin()->Edit('user_name', $user_name, false, 'style="width:400px;" class="autofocus"'));
        FormRow('E-mail', System::admin()->Edit('user_email', $user_email, false, 'style="width:400px;"'));
        FormRow('Скрыть e-mail', System::admin()->Check('user_hideemail', '1', $user_hideemail));
        FormRow('Сайт', System::admin()->Edit('user_homepage', $user_homepage, false, 'style="width:400px;"'));
    }
    FormRow('Текст', System::admin()->TextArea('post_message', $post_message, 'style="width:400px;height:200px;"' . ($user_id != 0 ? ' class="autofocus"' : '')));
    $action = ADMIN_FILE . '?exe=comments&a=save&id=' . $id . '&table=' . $table . '&page=' . $page;
    AddCenterBox('Редактирование комментария');
    AddForm('<form action="' . $action . '" method="post">', System::admin()->Button('Отмена', 'onclick="history.go(-1)"') . System::admin()->Submit('Сохранить'));
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$topic_id = 0;
if ($a == 'edit') {
    $topic_id = SafeDB($block_config, 11, int);
}
System::database()->Select('mail_topics', '');
$topicdata = array();
while ($topic = System::database()->FetchRow()) {
    System::admin()->DataAdd($topicdata, $topic['id'], $topic['title'], $topic['id'] == $topic_id);
}
FormRow('Тема рассылки', System::admin()->Select('topic', $topicdata, false, ''));
$title = 'Настройка блока рассылки';
function AdminPollsEditor()
{
    global $editpolls;
    if (!$editpolls) {
        System::admin()->AccessDenied();
    }
    $view = 4;
    $answers = array();
    if (isset($_GET['id'])) {
        //Редактирование
        $title = 'Редактирование опроса';
        $btitle = 'Сохранить изменения';
        $id = SafeEnv($_GET['id'], 11, int);
        System::database()->Select('polls', "`id`='{$id}'");
        $p = System::database()->FetchRow();
        $poll = SafeDB($p['question'], 255, str);
        $desc = SafeDB($p['description'], 255, str);
        $showinblock = SafeDB($p['showinblock'], 1, int);
        $multianswers = SafeDB($p['multianswers'], 1, int);
        //Ответы
        $answers = unserialize($p['answers']);
        $allow_comments = SafeDB($p['allow_comments'], 1, int);
        $active = $p['active'];
        $view = SafeDB($p['view'], 1, int);
        $uid = '&id=' . $id;
    } else {
        //Добавление
        $title = 'Добавить опрос';
        $btitle = 'Добавить';
        $poll = '';
        $desc = '';
        $showinblock = true;
        $multianswers = false;
        $answers[] = array('Вариант ответа 1', '', '0');
        $answers[] = array('Вариант ответа 2', '', '0');
        $allow_comments = true;
        $active = true;
        $uid = '';
    }
    FormRow('Вопрос', System::site()->Edit('poll', $poll, false, 'maxlength="250" style="width:400px;" class="autofocus"'));
    FormRow('Описание', System::site()->Edit('desc', $desc, false, 'maxlength="250" style="width:400px;"'));
    FormRow('Показывать в блоке', System::site()->Select('showinblock', GetEnData($showinblock, 'Да', 'Нет')));
    FormRow('Мультиответы', System::site()->Select('multianswers', GetEnData($multianswers, 'Да', 'Нет')));
    $answers_js = '';
    foreach ($answers as $answer) {
        $answers_js .= ",['" . HtmlChars($answer[0], ENT_QUOTES) . "', '" . HtmlChars($answer[1], ENT_QUOTES) . "', " . SafeDB($answer[2], 11, int) . "]";
    }
    $answers_js = '[' . substr($answers_js, 1) . ']';
    // Выводим поле для редактирования ответов
    System::admin()->AddOnLoadJS(Indent('
		if(!("map" in Array.prototype)) Array.prototype.map = function(mapper, that){
			var other = new Array(this.length);
			for(var i=0, n=this.length; i<n; i++){
				if(i in this){
					other[i] = mapper.call(that, this[i], i, this);
				}
			}
			return other;
		};

		answersdata = ' . $answers_js . ';

		tableAddRow = function(answer, color, voices){
			var tr = $("<tr>");
			var answerinput = $("<input>", {type: "text", name: "answer[]", "class": "fd_answer"}).val(answer).css("width", "400px");
			$("<td>").append(answerinput).appendTo(tr);
			$("<td>").append($("<input>", {type: "text", name: "color[]", "class": "fd_color"}).val(color).css("width", "80px")).appendTo(tr);
			$("<td>").append($("<input>", {type: "text", name: "voices[]", "class": "fd_voices"}).val(voices).css("width", "50px").css("text-align", "right")).appendTo(tr);

			var td_delete = $("<td>").appendTo(tr);
			$("<a>", {"class": "button", html: "<img src=\\"images/admin/delete.png\\">", href: "#", title: "Удалить"}).click(function(){
				tr.remove();
				return false;
			}).appendTo(td_delete);

			tr.appendTo($("#answers_table tbody"));
			answerinput.focus();
		};

		AddPollAnswer = function(){
			tableAddRow("", "", "0");
		};

		answersdata.map(function(item){
			tableAddRow(item[0], item[1], item[2]);
		});

		$("#answers_table tbody").sortable();
	'));
    FormRow('Ответы', Indent('
		<table cellspacing="0" cellpadding="0" class="cfgtable" id="answers_table">
			<thead>
				<tr>
					<th style="width: 400px;">Ответ</th>
					<th style="width: 80px;">Цвет</th>
					<th style="width: 50px;">Ответы</th>
					<th style="width: 40px;">&nbsp;</th>
				</tr>
			</thead>
			<tbody></tbody>
		</table>
		<div style="float: right;">' . System::admin()->SpeedConfirmJs('Добавить ответ', 'AddPollAnswer();', 'images/admin/plus.png', '', true) . '</div>
	'));
    FormRow('Разрешить комментарии', System::site()->Select('allow_comments', GetEnData($allow_comments, 'Да', 'Нет')));
    FormRow('Включить', System::site()->Select('active', GetEnData($active, 'Да', 'Нет')));
    FormRow('Кто может отвечать', System::site()->Select('view', GetUserTypesFormData($view)));
    AddCenterBox($title);
    AddForm('<form action="' . ADMIN_FILE . '?exe=polls&a=save' . $uid . '" method="post">', System::site()->Button('Отмена', 'onclick="history.go(-1)"') . System::site()->Submit($btitle));
}