/**
 * Генерирует форму редактирования пользователя в админ-панели.
 *
 * @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));
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
TAddSubTitle('√лавна¤');
global $adminpanel_content;
$adminpanel_content = '';
IncludePluginsGroup('adminpanel');
AddTextBox('јдмин-панель', $adminpanel_content);
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 />');
}
/**
 * Редактор новостей (редактирование / добавление)
 * @return void
 */
function AdminNewsEditor()
{
    global $news_access_editnews;
    if (!$news_access_editnews) {
        System::admin()->AccessDenied();
    }
    UseScript('jquery_ui', 'colorbox?theme=admin');
    System::admin()->AddOnLoadJS('
	$("#datepicker").datepicker({
		dateFormat: "dd.mm.yy",
		changeMonth: true,
		changeYear: true
	});');
    $topic_id = 0;
    // Номер темы
    $newstitle = '';
    // Заголовок новости
    $icon = '';
    // Иконки
    $stext = '';
    // Короткая новость
    $ctext = '';
    // Полная новость
    $view = 4;
    // Кто видит
    $allow_comments = true;
    // Разрешить комментарии
    $auto_br = false;
    // Авто добавление тега <br />
    $enabled = true;
    // Включить да/нет
    $alname = 'Разместить';
    // Надпись на отправляющей кнопке
    $img_view = 0;
    //Модуль SEO
    $seo_title = '';
    $seo_keywords = '';
    $seo_description = '';
    $public_date = date("d.m.Y", time());
    $public_time = date("G:i", time());
    if (!isset($_GET['id'])) {
        // Добавление новости
        $auto_br = false;
        $title = 'Добавить новость';
        $caption = 'Добавить';
        TAddSubTitle($title);
        $met = '';
    } else {
        // Редактирование новости
        System::database()->Select('news', "`id`='" . SafeEnv($_GET['id'], 11, int) . "'");
        $news = System::database()->FetchRow();
        $topic_id = SafeDB($news['topic_id'], 11, int);
        $newstitle = SafeDB($news['title'], 255, str);
        $icon = SafeDB($news['icon'], 255, str);
        $stext = SafeDB($news['start_text'], 0, str, false);
        $ctext = SafeDB($news['end_text'], 0, str, false);
        $allow_comments = SafeDB($news['allow_comments'], 1, bool);
        $auto_br = SafeDB($news['auto_br'], 1, bool);
        $img_view = SafeDB($news['img_view'], 1, int);
        $view = SafeDB($news['view'], 1, int);
        $enabled = SafeDB($news['enabled'], 1, bool);
        //Модуль SEO
        $seo_title = SafeDB($news['seo_title'], 255, str);
        $seo_keywords = SafeDB($news['seo_keywords'], 255, str);
        $seo_description = SafeDB($news['seo_description'], 255, str);
        $public_date = date("d.m.Y", $news['date']);
        $public_time = date("G:i", $news['date']);
        $title = 'Редактирование новости';
        $caption = 'Сохранить изменения';
        TAddSubTitle($title);
        $met = '&id=' . SafeEnv($_GET['id'], 11, int);
    }
    System::admin()->AddJS(Indent('
		NewsPreviewOpen = function(){
			if(tinyMCE){
				tinyMCE.triggerSave();
			}
			var form_data = Admin.SerializeFormData(document.forms.news_editor);
			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=news&a=preview' . $met . '",
				data: form_data,
				dataType: "html",
				success: function(data){
					wp.document.write(data);
					wp.document.close();
				}
			});
		}
	'));
    System::database()->Select('news_topics', '');
    $topicdata = array();
    while ($topic = System::database()->FetchRow()) {
        System::admin()->DataAdd($topicdata, $topic['id'], $topic['title'], $topic['id'] == $topic_id);
    }
    if (count($topicdata) == 0) {
        AddTextBox($title, 'Нет раздела для добавления. Создайте хотя бы один раздел.');
        return;
    }
    $img_view_data = array();
    System::admin()->DataAdd($img_view_data, '0', 'Авто', $img_view == 0);
    System::admin()->DataAdd($img_view_data, '1', 'Исходная картинка', $img_view == 1);
    System::admin()->DataAdd($img_view_data, '2', 'Эскиз', $img_view == 2);
    $acts = array();
    System::admin()->DataAdd($acts, 'save', $alname);
    System::admin()->DataAdd($acts, 'preview', 'Предпросмотр');
    FormRow('Раздел', System::admin()->Select('topic_id', $topicdata, false, 'class="autofocus"'));
    FormRow('Заголовок новости', System::admin()->Edit('title', $newstitle, false, 'style="width:400px;"'));
    // Модуль SEO
    FormRow('[seo] Заголовок страницы', System::admin()->Edit('seo_title', $seo_title, false, 'style="width:400px;"'));
    FormRow('[seo] Ключевые слова', System::admin()->Edit('seo_keywords', $seo_keywords, false, 'style="width:400px;"'));
    FormRow('[seo] Описание', System::admin()->Edit('seo_description', $seo_description, false, 'style="width:400px;"'));
    list($width, $height) = SafeDB(explode(':', System::config('news/tmb_size')), 11, int);
    FormRow('Изображение', System::admin()->FileManager('icon', $icon) . '<br>
		<a href="' . $icon . '" class="filemanager_icon colorbox" data-content="href:path" target="_blank">
			<img src="' . GetThumb($icon, $width, $height) . '" class="filemanager_icon" data-content="src:tmb" style="margin-top: 5px; max-width: 250px;">
		</a>');
    //AdminImageControl('Изображение', 'Загрузить изображение', $icon, System::config('news/icons_dirs'), 'icon', 'up_photo', 'news_editor');
    FormRow('Отображение рисунка', System::admin()->Select('img_view', $img_view_data));
    FormTextRow('Короткая новость (HTML)', System::admin()->HtmlEditor('shorttext', $stext, 600, 200));
    FormTextRow('Полная новость (HTML)', System::admin()->HtmlEditor('continuation', $ctext, 600, 400));
    FormRow('', 'Преобразовать текст в HTML: ' . System::admin()->Select('auto_br', GetEnData($auto_br, 'Да', 'Нет')));
    FormRow('Дата и время публикации', System::admin()->Edit('public_date', $public_date, false, 'id="datepicker" style="width:120px;"') . '&nbsp;' . System::admin()->Edit('public_time', $public_time, false, 'style="width:60px;"'));
    FormRow('Комментарии', System::admin()->Select('acomments', GetEnData($allow_comments, 'Разрешить', 'Запретить')));
    FormRow('Кто видит', System::admin()->Select('view', GetUserTypesFormData($view)));
    FormRow('Включить', System::admin()->Select('enabled', GetEnData($enabled, 'Да', 'Нет')));
    AddCenterBox($title);
    $back = '';
    if (isset($_REQUEST['back'])) {
        $back = '&back=' . SafeDB($_REQUEST['back'], 255, str);
    }
    AddForm('<form name="news_editor" action="' . ADMIN_FILE . '?exe=news&a=save' . $met . $back . '" method="post" enctype="multipart/form-data" name="news_editor">', System::admin()->Button('Отмена', 'onclick="history.go(-1)"') . System::admin()->Button('Предпросмотр', 'onclick="NewsPreviewOpen();"') . System::admin()->Submit($caption));
}
     System::admin()->ConfigGroups('forum');
     System::admin()->AddConfigsForm(ADMIN_FILE . '?exe=forum&a=configsave');
     break;
 case 'configsave':
     System::admin()->SaveConfigs('forum');
     Audit('Форум: Изменение настроек модуля');
     GO(ADMIN_FILE . '?exe=forum&a=config&saveok');
     break;
     ////////////////////////////////////////////
     // Корзина ////////////////////////////////////
 ////////////////////////////////////////////
 // Корзина ////////////////////////////////////
 case 'forum_basket_posts':
 case 'forum_basket_topics':
 case 'forum_basket':
     TAddSubTitle('Форум > Корзина');
     switch ($action) {
         ////////////////// Корзина
         case 'forum_basket_posts':
             AdminForumBasket();
             break;
         case 'forum_basket_topics':
             AdminForumBasket('forum_basket_topics');
             break;
         default:
             AdminForumBasket();
     }
     return true;
     break;
 case 'basket_restore':
     AdminForumBasketRestore();