/**
 * Загружает информацию об установленных подключаемых плагинах из базы данных и возвращает результат.
 * Кэшируется.
 * @return array
 */
function PluginsGetInstalled()
{
    static $plugins = null;
    if (System::cache()->HasCache(system_cache, 'plugins')) {
        $plugins = System::cache()->Get(system_cache, 'plugins');
    }
    if (!isset($plugins)) {
        $plugins = System::database()->Select('plugins', "(`type`='5' or `type`='7') and `enabled`='1'");
        System::cache()->Write(system_cache, 'plugins', $plugins, Day2Sec);
    }
    return $plugins;
}
/**
 * Возвращает правило замены.
 * @param string $Ufu
 * @param bool $Clear
 * @return array
 */
function &UfuGetRules($Ufu = null, $Clear = false)
{
    static $UfuRewriteRules = null;
    if ($Clear) {
        $UfuRewriteRules = null;
        System::cache()->Delete(system_cache, 'rewrite_rules');
        return $UfuRewriteRules;
    }
    if ($UfuRewriteRules == null) {
        if (System::cache()->HasCache(system_cache, 'rewrite_rules')) {
            $UfuRewriteRules = System::cache()->Get(system_cache, 'rewrite_rules');
        } else {
            $UfuRewriteRules = array();
            $_rules = System::database()->Select('rewrite_rules');
            SortArray($_rules, 'order');
            foreach ($_rules as $_rule) {
                $rule = array('ufu' => $_rule['ufu'], 'pattern' => $_rule['pattern'], 'params' => $_rule['params']);
                if ($_rule['module'] != '' && $_rule['name'] != '') {
                    $UfuRewriteRules[$_rule['module'] . ':' . $_rule['name']] = $rule;
                } else {
                    $UfuRewriteRules[$_rule['ufu']] = $rule;
                }
            }
            System::cache()->Write(system_cache, 'rewrite_rules', $UfuRewriteRules, Day2Sec);
        }
    }
    if (isset($Ufu)) {
        if (isset($UfuRewriteRules[$Ufu])) {
            return $UfuRewriteRules[$Ufu];
        } else {
            $null = null;
            return $null;
        }
    }
    return $UfuRewriteRules;
}
/**
 * Очистка кэша страниц и меню
 * @return void
 */
function AdminPagesClearCache()
{
    System::cache()->Delete('block', array('menu1', 'menu2', 'menu3', 'menu4'));
    System::cache()->Delete('tree', 'pages');
    // Нестандартное дерево, используем апи при построении но не используем его при редактировании
}
function AdminExtensionsUninstall()
{
    global $db, $config, $user;
    // Для старых модулей
    $ext_type = $_GET['type'];
    $folder = $_GET['name'];
    if (isset($_GET['group'])) {
        $group = $_GET['group'];
    }
    switch ($ext_type) {
        case EXT_MODULE:
            $mod_path = RealPath2(System::config('mod_dir') . $folder);
            $info = ExtLoadInfo($mod_path);
            if (isset($_POST['ok']) || isset($info['1.3'])) {
                $uninstall = $mod_path . '/uninstall.php';
                if (file_exists($uninstall)) {
                    $delete_tables = isset($_POST['delete_tables']);
                    // Могут быть использованы в uninstall.php
                    $delete_files = isset($_POST['delete_files']);
                    include $uninstall;
                    System::cache()->Clear('config');
                    if (isset($info['1.3'])) {
                        // Удаляем пункт меню
                        $folder = SafeEnv($folder, 255, str);
                        AdminMenuDeleteModule($folder);
                    }
                }
                Audit('Расширения: Удаление модуля "' . $folder . '"');
                GO(ADMIN_FILE . '?exe=extensions#tabs-1');
            } else {
                $folder = SafeEnv($folder, 255, str);
                System::database()->Select('modules', "`folder`='{$folder}'");
                if (System::database()->NumRows() == 0) {
                    AddTextBox('Ошибка', 'Модуль не установлен.');
                    return;
                }
                $mod = System::database()->FetchRow();
                $name = SafeDB($mod['name'], 255, str);
                $text = '';
                $text .= '<form method="post">';
                $text .= '<div style="padding: 10px 0 10px 25px;">';
                $text .= '<div style="padding-bottom: 10px">';
                $text .= '<label><input type="checkbox" name="delete_tables">&nbsp;Удалить таблицы БД</label><br>';
                $text .= '<label><input type="checkbox" name="delete_files">&nbsp;Удалить файлы модуля</label>';
                $text .= '</div>';
                $text .= System::admin()->Hidden('ok', '1');
                $text .= '<div>' . System::admin()->Button('Отмена', 'onclick="history.go(-1)"') . System::admin()->Submit('Удалить') . '</div>';
                $text .= '</div></form>';
                AddTextBox('Удаление модуля "' . $name . '"', $text);
            }
            break;
        case EXT_BLOCK:
            $mod_path = RealPath2(System::config('blocks_dir') . $folder);
            if (isset($_POST['ok'])) {
                $uninstall = $mod_path . '/uninstall.php';
                if (file_exists($uninstall)) {
                    $delete_tables = isset($_POST['delete_tables']);
                    $delete_files = isset($_POST['delete_files']);
                    include $uninstall;
                    System::cache()->Clear('config');
                }
                Audit('Удаление блока "' . $folder . '"');
                GO(ADMIN_FILE . '?exe=extensions#tabs-2');
            } else {
                $folder = SafeEnv($folder, 255, str);
                System::database()->Select('block_types', "`folder`='{$folder}'");
                if (System::database()->NumRows() == 0) {
                    AddTextBox('Ошибка', 'Блок не установлен.');
                    return;
                }
                $mod = System::database()->FetchRow();
                $name = SafeDB($mod['name'], 255, str);
                $text = '';
                $text .= '<form method="post">';
                $text .= '<div style="padding: 10px 0 10px 25px;">';
                $text .= '<div style="padding-bottom: 10px">';
                $text .= '<label><input type="checkbox" name="delete_tables">&nbsp;Удалить таблицы БД</label><br>';
                $text .= '<label><input type="checkbox" name="delete_files">&nbsp;Удалить файлы</label>';
                $text .= '</div>';
                $text .= System::admin()->Hidden('ok', '1');
                $text .= '<div>' . System::admin()->Button('Отмена', 'onclick="history.go(-1)"') . System::admin()->Submit('Удалить') . '</div>';
                $text .= '</div></form>';
                AddTextBox('Удаление блока "' . $name . '"', $text);
            }
            break;
        case EXT_PLUGIN:
            if (isset($_GET['group'])) {
                $group = $_GET['group'] . '/';
                $groupenv = SafeEnv($_GET['group'], 255, str);
            } else {
                $group = '';
                $groupenv = '';
            }
            $mod_path = RealPath2(System::config('plug_dir') . $group . $folder);
            $info = ExtLoadInfo($mod_path);
            if (isset($_POST['ok']) || isset($info['1.3'])) {
                $uninstall = $mod_path . '/uninstall.php';
                if (file_exists($uninstall)) {
                    $delete_tables = isset($_POST['delete_tables']);
                    $delete_files = isset($_POST['delete_files']);
                    include $uninstall;
                    System::cache()->Clear('config');
                    // FIXME: plugin config
                }
                if (isset($info['1.3'])) {
                    $folder = SafeEnv($folder, 255, str);
                    System::database()->Delete('plugins', "`name`='{$folder}' and `group`='{$groupenv}'");
                }
                PluginsClearCache();
                Audit('Расширения: Удаление плагина "' . $folder . '"');
                GO(ADMIN_FILE . '?exe=extensions#tabs-3');
            } else {
                $folder = SafeEnv($folder, 255, str);
                System::database()->Select('plugins', "`name`='{$folder}' and `group`='{$groupenv}'");
                if (System::database()->NumRows() == 0) {
                    AddTextBox('Ошибка', 'Плагин не установлен.');
                    return;
                }
                $mod = System::database()->FetchRow();
                $name = SafeDB($info['name'], 255, str);
                $text = '';
                $text .= '<form method="post">';
                $text .= '<div style="padding: 10px 0 10px 25px;">';
                $text .= '<div style="padding-bottom: 10px">';
                $text .= '<label><input type="checkbox" name="delete_tables">&nbsp;Удалить таблицы БД</label><br>';
                $text .= '<label><input type="checkbox" name="delete_files">&nbsp;Удалить файлы</label>';
                $text .= '</div>';
                $text .= System::admin()->Hidden('ok', '1');
                $text .= '<div>' . System::admin()->Button('Отмена', 'onclick="history.go(-1)"') . System::admin()->Submit('Удалить') . '</div>';
                $text .= '</div></form>';
                AddTextBox('Удаление плагина "' . $name . '"', $text);
            }
            break;
        case EXT_TEMPLATE:
            $mod_path = RealPath2(System::config('tpl_dir') . $folder);
            if (isset($_POST['ok'])) {
                ExtRemoveTemplate($folder, isset($_POST['delete_files']));
                Audit('Расширения: Удаление шаблона "' . $folder . '"');
                GO(ADMIN_FILE . '?exe=extensions#tabs-4');
            } else {
                $info = ExtLoadInfo($mod_path);
                if ($info === false) {
                    $info = array('name' => $folder, 'description' => '', 'author' => '', 'site' => '', 'version' => '1.0', 'admin' => false);
                }
                $name = SafeDB($info['name'], 255, str);
                $text = '';
                $text .= '<form method="post">';
                $text .= '<div style="padding: 10px 0 10px 25px;">';
                $text .= '<div style="padding-bottom: 10px">';
                $text .= '<label><input type="checkbox" name="delete_files">&nbsp;Удалить файлы</label>';
                $text .= '</div>';
                $text .= System::admin()->Hidden('ok', '1');
                $text .= '<div>' . System::admin()->Button('Отмена', 'onclick="history.go(-1)"') . System::admin()->Submit('Удалить') . '</div>';
                $text .= '</div></form>';
                AddTextBox('Удаление шаблона "' . $name . '"', $text);
            }
            break;
    }
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$bconf['count'] = SafeEnv($_POST['count'], 11, int);
$bconf['cats'] = SafeEnv($_POST['cats'], 11, int);
$block_config = serialize($bconf);
System::cache()->Delete('block', array('random_images1', 'random_images2', 'random_images3', 'random_images4'));
function AdminsDeleteGroup()
{
    if (!isset($_GET['id'])) {
        GO(ADMIN_FILE . '?exe=admins&a=groups');
        exit;
    }
    $id = SafeEnv($_GET['id'], 11, int);
    if (isset($_GET['ok']) && SafeEnv($_GET['ok'], 1, int) == '1') {
        // Очищаем кэш
        if (System::cache()->HasCache(system_cache, 'usertypes')) {
            System::cache()->Delete(system_cache, 'usertypes');
        }
        System::database()->Select('users', "`access`='" . $id . "'");
        $num_users = System::database()->NumRows();
        System::database()->Select('usertypes', "`id`='{$id}'");
        $group = System::database()->FetchRow();
        if ($num_users > 0) {
            if (!isset($_GET['users'])) {
                $text = 'К этой группе принадлежат ' . $num_users . ' пользователей. Вы можете:<br />' . '<a href="' . ADMIN_FILE . '?exe=admins&a=delgroup&id=' . $id . '&ok=1&users=del">Удалить их...</a> <br />' . '<a href="' . ADMIN_FILE . '?exe=admins&a=delgroup&id=' . SafeEnv($_GET['id'], 11, int) . '&ok=1&users=move">Переместить их в другую группу.</a>';
                AddTextBox('Внимание!', $text);
            } else {
                if ($_GET['users'] == 'del') {
                    System::database()->Delete('users', "`access`='" . $id . "'");
                } elseif ($_GET['users'] == 'move' && !isset($_POST['to'])) {
                    $text = 'Выберите группу, в которую Вы желаете переместить пользователей:<br />' . '<form action="' . ADMIN_FILE . '?exe=admins&a=delgroup&id=' . $id . '&ok=1&users=move" method="post">';
                    System::database()->Select('usertypes', "`id`<>'" . $id . "'");
                    System::site()->DataAdd($group_data, '-1', 'Пользователи');
                    while ($tp = System::database()->FetchRow()) {
                        System::site()->DataAdd($group_data, $tp['id'], $tp['name']);
                    }
                    $text .= System::site()->Select('to', $group_data) . '<br />';
                    $text .= System::site()->Submit('Продолжить') . '<br />';
                    $text .= '</form>';
                    AddTextBox('Внимание!', $text);
                    return;
                } elseif ($_GET['users'] == 'move' && isset($_POST['to'])) {
                    $to = SafeEnv($_POST['to'], 11, int);
                    if ($to == '-1') {
                        $set = "type='2',access='" . $to . "'";
                    } else {
                        $set = "access='" . $to . "'";
                    }
                    System::database()->Update('users', $set, "`access`='" . $id . "'");
                }
            }
        }
        System::database()->Delete('usertypes', "`id`='" . $id . "'");
        Audit('Администраторы: Удаление группы администраторов "' . $group['name'] . '"');
        GO(ADMIN_FILE . '?exe=admins&a=groups');
    } else {
        System::database()->Select('usertypes', "`id`='" . $id . "'");
        $group = System::database()->FetchRow();
        $text = 'Вы действительно хотите удалить группу "' . SafeDB($group['name'], 255, str) . '"?<br />' . '<a href="' . ADMIN_FILE . '?exe=admins&a=delgroup&id=' . $id . '&ok=1">Да</a> &nbsp;&nbsp;&nbsp; <a href="javascript:history.go(-1)">Нет</a>';
        AddTextBox("Предупреждение", $text);
    }
}
function AdminGalleryMove()
{
    global $edit_images;
    if (!$edit_images) {
        System::admin()->AccessDenied();
    }
    $move = SafeEnv($_GET['to'], 4, str);
    // up, down
    $id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select('gallery', "`id`='{$id}'");
    if (System::database()->NumRows() > 0) {
        $img = System::database()->FetchRow();
        $pid = SafeDB($img['cat_id'], 11, int);
        $images = System::database()->Select('gallery', "`cat_id`='{$pid}'");
        SortArray($images, 'order');
        $c = count($images);
        //Исходный индекс
        $cur_order = 0;
        for ($i = 0; $i < $c; $i++) {
            $images[$i]['order'] = $i;
            if ($images[$i]['id'] == $id) {
                $cur_order = $i;
            }
        }
        //Индекс перемещения
        if ($move == 'up') {
            $rep_order = $cur_order - 1;
        } elseif ($move == 'down') {
            $rep_order = $cur_order + 1;
        } else {
            $rep_order = $cur_order;
        }
        if ($rep_order < 0 || $rep_order >= $c) {
            $rep_order = $cur_order;
        }
        $temp = intval($images[$cur_order]['order']);
        $images[$cur_order]['order'] = intval($images[$rep_order]['order']);
        $images[$rep_order]['order'] = intval($temp);
        for ($i = 0; $i < $c; $i++) {
            $order = $images[$i]['order'];
            $id = $images[$i]['id'];
            System::database()->Update('gallery', "`order`='{$order}'", "`id`='{$id}'");
        }
        Audit('Фотогалерея: Перемещение изображения "' . $img['title'] . '" (id: ' . $img['id'] . ')');
    }
    System::cache()->Delete('tree', 'gallery');
    $cat = isset($_GET['cat']) ? '&cat=' . SafeEnv($_GET['cat'], 11, int) : '';
    $page = isset($_GET['page']) ? '&page=' . SafeEnv($_GET['cat'], 11, int) : '';
    GO(ADMIN_FILE . '?exe=gallery' . $cat . $page);
}
function AdminUserDeleteRank()
{
    $rank_id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select('userranks', "`id`='{$rank_id}'");
    $rank = System::database()->FetchRow();
    System::database()->Delete('userranks', "`id`='{$rank_id}'");
    System::cache()->Delete(system_cache, 'userranks');
    Audit('Пользователи: Удаление ранга "' . $rank['title'] . '"');
    GO(ADMIN_FILE . '?exe=user&a=ranks');
}
function AdminMailDeleteTopic()
{
    $id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select('mail_topics', "`id`='{$id}'");
    $topic = System::database()->FetchRow();
    System::database()->Delete('mail_topics', "`id`='{$id}'");
    System::database()->Delete('mail_list', "`topic_id`='{$id}'");
    System::database()->Delete('mail_history', "`topic_id`='{$id}'");
    Audit('Рассылки: Удаление рассылки "' . $topic['title'] . '"');
    System::cache()->Delete('block', 'mail');
    GO(ADMIN_FILE . '?exe=mail');
}
    header("HTTP/1.1 404 Not Found");
    exit;
}
if (System::cache()->HasCache('block', 'mail')) {
    $tempvars['content'] = 'block/content/mail.html';
    $vars = System::cache()->Get('block', 'mail');
} else {
    $topic_id = SafeDB($block_config, 11, int);
    System::database()->Select('mail_topics', "`id`='{$topic_id}'");
    if (System::database()->NumRows() > 0) {
        $topic = System::database()->FetchRow();
        $tempvars['content'] = 'block/content/mail.html';
        $vars['title'] = $title;
        $vars['form_action'] = Ufu('index.php?name=mail&op=subscribe', 'mail/{op}/');
        $vars['topic_id'] = $topic['id'];
        $vars['lmail_title'] = 'Подписаться на рассылку ';
        $vars['mail_title'] = $topic['title'];
        $vars['lemail'] = 'Ваш e-mail';
        $vars['lsubmit'] = 'Подписаться';
        $vars['lother'] = 'Другие рассылки';
        $vars['lformat'] = 'Формат';
        $vars['lhtml'] = 'HTML';
        $vars['ltext'] = 'Текст';
        System::cache()->Write('block', 'mail', $vars);
    } elseif (System::user()->Auth && System::user()->isAdmin()) {
        $vars['title'] = $title;
        $vars['content'] = '<p align="center"><span style="color: #FF0000">Тема рассылки для блока не найдена. Пожалуйста выберите новую тему для блока.</span></p>';
    } else {
        $enabled = false;
    }
}
    } elseif ($page['type'] == 'link') {
        $link = SafeDB($page['text'], 255, str);
        if (substr($link, 0, 6) == 'mod://') {
            $link = Ufu('index.php?name=' . substr($link, 6), 'system:mod');
        }
    }
    $link = str_replace('&amp;', '&', $link);
    $item_vars = array('title' => $page['title'], 'link' => $link, 'selected' => false, 'subitems' => false);
    if (isset($catsPid[$page['id']])) {
        foreach ($catsPid[$page['id']] as $subpage) {
            if ($subpage['type'] == 'page') {
                $link = Ufu('index.php?name=pages&file=' . SafeDB($subpage['link'], 255, str), 'pages:page');
            } elseif ($subpage['type'] == 'link') {
                $link = SafeDB($subpage['text'], 255, str);
                if (substr($link, 0, 6) == 'mod://') {
                    $link = Ufu('index.php?name=' . substr($link, 6), 'system:mod');
                }
            } else {
                continue;
            }
            $link = str_replace('&amp;', '&', $link);
            $subitem_vars = array('title' => $subpage['title'], 'link' => $link, 'selected' => false);
            $subitems['sub'][] = Starkyt::CreateSubBlock(true, $subitem_vars);
        }
    }
    $item_vars['subitems'] = count($subitems['sub']) > 0;
    $items['sub'][] = Starkyt::CreateSubBlock(true, $item_vars, array(), '', '', array('block_menu_subitems' => $subitems));
}
System::cache()->Write('block', $bcache_name, $items);
BlockMenuSelectItem($items, $uri);
$childs['block_menu_items'] = $items;
/**
 * Добавляет новую настройку.
 * @param string         $Group       Идентификатор группы настроек.
 * @param string         $Name        Имя (для доступа из кода).
 * @param string         $Title       Заголовок.
 * @param string         $Value       Начальное значение.
 * @param string         $Description Описание.
 * @param bool           $Visible     Видимая.
 * @param string         $KindControl Элемент управления для изменения значения.
 * @param string         $Type        Тип данных (длина(255),тип(string - PHP Type),вырезать теги(true, false)).
 * @param string         $Values      Заполнение значений для элементов выбора. (optval:title,optval:title) или функция (function:Callback), см. плагины форм.
 * @param string         $SaveHandler Имя функции вызываемой при сохранении параметра. См. плагины форм.
 * @param bool           $Autoload    Загружать в $config.
 * @param string         $Table
 * @param string         $GroupsTable
 */
function AddConfig($Group, $Name, $Title, $Value, $Description = '', $Visible = false, $KindControl = '', $Type = '255,string,false', $Values = '', $SaveHandler = '', $Autoload = true, $Table = 'config', $GroupsTable = 'config_groups')
{
    if (!is_numeric($Group)) {
        $groups = GetConfigGroups($GroupsTable);
        $Group = SafeEnv($groups[$Group]['id'], 11, int);
    }
    if ($Visible) {
        $Visible = '1';
    } else {
        $Visible = '0';
    }
    if ($Autoload) {
        $Autoload = '1';
    } else {
        $Autoload = '0';
    }
    $Name = SafeEnv($Name, 255, str);
    $Value = SafeEnv($Value, 0, str);
    $Title = SafeEnv($Title, 255, str);
    $Description = SafeEnv($Description, 255, str);
    $Values = SafeEnv($Values, 255, str);
    System::database()->Insert($Table, "'','{$Group}','{$Name}','{$Value}','{$Visible}','{$Title}','{$Description}','{$KindControl}','{$Values}','{$SaveHandler}','{$Type}','{$Autoload}'");
    System::cache()->Clear('config');
}
 /**
  * Увеличивает индекс количества субкаталогов в каталоге
  * используя параметры и указанные настройки класса
  *
  * @param int $id Идентификатор объекта
  * @param int $inc Значение инкремента
  * @return void
  */
 public function CalcCatCounter($id, $inc)
 {
     $cat = System::database()->SelectOne($this->Table, "`" . $this->IdKey . "`='{$id}'");
     if ($cat) {
         if ($inc === true) {
             $counter_val = $cat[$this->CatCounterKey] + 1;
         } elseif ($inc === false) {
             $counter_val = $cat[$this->CatCounterKey] - 1;
         } else {
             $counter_val = $cat[$this->CatCounterKey] + intval($inc);
         }
         System::database()->Update($this->Table, $this->CatCounterKey . "='{$counter_val}'", "`" . $this->IdKey . "`='{$id}'");
         // Очищаем кеш
         System::cache()->Delete('tree', $this->Table);
     }
 }
function saveconf_Clear_Cache($Value)
{
    System::cache()->ClearAll();
    return $Value;
}
function AdminCacheCleanup()
{
    System::cache()->ClearAll();
    Audit('Управление кэшем: Полная очистка кэша');
    AdminCacheMain();
}
示例#16
0
require_once "config/config.php";
$data = new Data();
$uri = new Uri();
$system = new System();
if (USE_DATABASE) {
    $db = new dbHandler();
}
if ($uri->size() != 0) {
    $controllerName = $uri->getParam(1);
} else {
    $controllerName = DEFAULT_CONTROLLER;
}
if (USE_CACHE) {
    $system->load()->cacheFile('cache');
    if ($system->cache()->mustRecache($uri->fullUri()) || !file_exists($system->cache()->getFullPath($uri->fullUri()))) {
        ob_start();
        loadPage();
        file_put_contents($system->cache()->getFullPath($uri->fullUri()), ob_get_contents(), FILE_BINARY);
        $system->cache()->cached($uri->fullUri());
        $system->cache()->save();
        ob_end_flush();
    } else {
        include $system->cache()->getFullPath($uri->fullUri());
    }
} else {
    loadPage();
}
//-----------------------------------
function loadPage()
{
function ForumCacheClear()
{
    System::cache()->Clear('forum');
}
function IndexUserRegistrationOk()
{
    System::site()->SetTitle('Регистрация на сайте');
    if (isset($_POST['usersave']) && $_POST['usersave'] == 'update') {
        $edit = true;
        $user_id = System::user()->Get('u_id');
        System::database()->Select('users', "`id`='" . $user_id . "'");
        $user = System::database()->FetchRow();
    } else {
        $edit = false;
    }
    if (!$edit) {
        System::user()->UnLogin(false);
    } else {
        if (!System::user()->Auth) {
            GO(Ufu('index.php'));
        }
    }
    if (System::config('user/registration') == 'off' && !$edit) {
        System::site()->AddTextBox('Ошибка', '<p align="center">Извините, регистрация временно приостановлена.</p>');
        return;
    }
    //Обрабатываем данные
    $errors = array();
    // Логин
    $login = '';
    $sendlogin = '';
    if (isset($_POST['login']) && CheckLogin(SafeEnv($_POST['login'], 30, str), $errors, true, $edit ? $user_id : 0)) {
        $login = SafeEnv($_POST['login'], 30, str);
        $sendlogin = $_POST['login'];
    }
    // Пароль
    $pass = '';
    $sendpass = '';
    $pass_generate_message = '';
    if (!System::user()->isAdmin() && $_POST['pass'] != '') {
        $pass = SafeEnv($_POST['pass'], 255, str);
        $rpass = SafeEnv($_POST['rpass'], 255, str);
        $sendpass = $_POST['pass'];
        if ($edit) {
            if ($rpass != '') {
                if (!CheckPass(SafeEnv($_POST['pass'], 255, str), $errors)) {
                    $pass = '';
                } elseif ($rpass != $pass) {
                    $errors[] = 'Пароли не совпадают.';
                    $pass = '';
                }
            } else {
                $pass = '';
            }
        } else {
            if ($_POST['pass'] == '') {
                srand(time());
                $pass = GenBPass(rand(System::config('user/pass_min_length'), 15));
                $sendpass = $pass;
                $pass_generate_message = '<br>Так как Вы не указали пароль, он был сгенерирован автоматически и выслан Вам на E-mail.';
            } else {
                if (CheckPass(SafeEnv($_POST['pass'], 255, str), $errors)) {
                    if ($rpass != $pass) {
                        $errors[] = 'Пароли не совпадают.';
                    }
                }
            }
        }
        $pass2 = md5($pass);
    }
    // E-mail
    if (!System::user()->isAdmin() && isset($_POST['email']) && CheckUserEmail(SafeEnv($_POST['email'], 50, str, true), $errors, true, $edit ? $user_id : 0)) {
        $email = SafeEnv($_POST['email'], 50, str, true);
    } else {
        $email = '';
    }
    // Скрыть E-mail
    if (isset($_POST['hideemail'])) {
        $hide_email = '1';
    } else {
        $hide_email = '0';
    }
    // Имя пользователя
    if (isset($_POST['nikname']) && CheckNikname(SafeEnv($_POST['nikname'], 50, str, true), $errors, true, $edit ? $user_id : 0)) {
        $nik_name = SafeEnv($_POST['nikname'], 50, str, true);
    } else {
        $nik_name = '';
    }
    // Настоящее имя
    if (isset($_POST['realname'])) {
        $real_name = SafeEnv($_POST['realname'], 250, str, true);
    } else {
        $real_name = '';
    }
    // Возраст лет
    if (isset($_POST['age'])) {
        if ($_POST['age'] == '' || is_numeric($_POST['age'])) {
            $age = SafeEnv($_POST['age'], 3, int);
        } else {
            $errors[] = 'Ваш возраст должен быть числом!';
        }
    } else {
        $age = '';
    }
    // Адрес домашней страницы
    if (isset($_POST['homepage'])) {
        $homepage = SafeEnv(Url($_POST['homepage']), 250, str, true);
    } else {
        $homepage = '';
    }
    // Номер ICQ
    if (isset($_POST['icq'])) {
        if ($_POST['icq'] == '' || is_numeric($_POST['icq'])) {
            $icq = SafeEnv($_POST['icq'], 15, str, true);
        } else {
            $errors[] = 'Номер ICQ должен содержать только числа!';
        }
    } else {
        $icq = '';
    }
    // Город
    if (isset($_POST['city'])) {
        $city = SafeEnv($_POST['city'], 100, str, true);
    } else {
        $city = '';
    }
    // Часовой пояс
    if (isset($_POST['gmt'])) {
        $gmt = SafeEnv($_POST['gmt'], 255, str);
    } else {
        $gmt = System::config('general/default_timezone');
    }
    // О себе
    if (isset($_POST['about'])) {
        $about = SafeEnv($_POST['about'], System::config('user/about_max_length'), str, true);
    } else {
        $about = '';
    }
    // Подписка на рассылку
    if (isset($_POST['snews'])) {
        $server_news = '1';
    } else {
        $server_news = '0';
    }
    if (!$edit && (!System::user()->Auth && !System::user()->isDef('captcha_keystring') || System::user()->Get('captcha_keystring') != $_POST['keystr'])) {
        $errors[] = 'Вы ошиблись при вводе кода с картинки.';
    }
    // Аватар
    $updateAvatar = true;
    if (isset($_POST['avatar'])) {
        if (System::config('user/avatar_transfer') == '1' && isset($_FILES['upavatar']) && file_exists($_FILES['upavatar']['tmp_name'])) {
            UserLoadAvatar($errors, $avatar, $a_personal, $user['avatar'], $user['a_personal'] == '1', $edit);
        } elseif ($_POST['avatar'] == '') {
            $updateAvatar = false;
        } elseif (file_exists(RealPath2(System::config('general/avatars_dir') . $_POST['avatar']))) {
            if ($edit) {
                if ($user['a_personal'] == '1') {
                    UnlinkUserAvatarFiles($user['avatar']);
                }
            }
            $a_personal = '0';
            $avatar = $_POST['avatar'];
        } else {
            $avatar = 'noavatar.gif';
            $a_personal = '0';
        }
    } else {
        $avatar = 'noavatar.gif';
        $a_personal = '0';
    }
    // Активация аккаунта
    $active = '1';
    $code = '';
    $SendActivation = false;
    $activate = '';
    if (!$edit) {
        $activate = System::config('user/activate_type');
        switch ($activate) {
            case 'manual':
                $active = '0';
                $code = '';
                $SendActivation = false;
                break;
            case 'auto':
                $active = '1';
                $code = '';
                $SendActivation = false;
                break;
            case 'mail':
                $active = '0';
                $code = GenRandomString(32);
                $SendActivation = true;
                break;
        }
    }
    $status = 2;
    $access = -1;
    $reg_date = time();
    $last_visit = time();
    $ip = getip();
    $points = 0;
    $visits = 0;
    // Сохранение
    if (count($errors) == 0) {
        if ($SendActivation) {
            UserSendActivationMail($nik_name, $email, $sendlogin, $sendpass, $code, $reg_date);
            $finish_message = Indent('
				<br>
				На указанный Вами E-Mail отправлено письмо,
				содержащее ссылку для подтверждения регистрации.
				Для активации Вашего аккаунта перейдите по данной ссылке
				и подтвердите регистрацию!
			');
        } elseif (!$edit) {
            UserSendEndRegMail($email, $nik_name, $sendlogin, $sendpass, $reg_date);
            $finish_message = '<br>На ваш E-mail отправлено письмо с данными о регистрации.';
        }
        if (!$edit) {
            // Добавление нового пользователя
            $values = Values('', $login, $pass2, $nik_name, $real_name, $age, $email, $hide_email, $city, $icq, $homepage, $gmt, $avatar, $about, $server_news, $reg_date, $last_visit, $ip, $points, $visits, $active, $code, $status, $access, $a_personal, serialize(array()));
            System::database()->Insert('users', $values);
            // Очищаем кэш пользователей
            System::cache()->Delete(system_cache, 'users');
            // Автоматический вход
            if ($activate == 'auto') {
                System::user()->Login($login, $pass, true, false);
                System::site()->InitVars();
            } elseif ($activate == 'mail') {
                System::user()->Def('activate_ps', base64_encode($pass));
            }
            System::site()->AddTextBox('Регистрация', '<p align="center">Поздравляем! Вы успешно зарегистрированы на сайте.' . $pass_generate_message . $finish_message . '<br>С уважением, администрация сайта <strong>' . System::config('general/site_name') . '.</strong></p>');
        } else {
            // Сохранение изменений
            $set = "`login`='{$login}',`hideemail`='{$hide_email}',`name`='{$nik_name}'," . "`truename`='{$real_name}',`age`='{$age}',`url`='{$homepage}',`icq`='{$icq}',`city`='{$city}',`timezone`='{$gmt}'" . ($updateAvatar == true ? ",`avatar`='{$avatar}',`a_personal`='{$a_personal}'" : '') . ",`about`='{$about}'," . "`servernews`='{$server_news}'" . ($pass != '' ? ",`pass`='{$pass2}'" : '') . ($email != '' ? ",`email`='{$email}'" : '');
            System::database()->Update('users', $set, "`id`='" . System::user()->Get('u_id') . "'");
            System::user()->UpdateMemberSession();
            UpdateUserComments(System::user()->Get('u_id'), System::user()->Get('u_id'), $nik_name, $email, $hide_email, $homepage, getip());
            // Очищаем кэш пользователей
            System::cache()->Delete(system_cache, 'users');
            GO(GetSiteUrl() . Ufu('index.php?name=user&op=userinfo', 'user/{op}/'));
        }
    } else {
        // Ошибка
        $text = 'Ваш аккаунт не ' . ($edit ? 'сохранен' : 'добавлен') . ', произошли следующие ошибки:<br><ul>';
        foreach ($errors as $error) {
            $text .= '<li>' . $error;
        }
        $text .= '</ul>';
        // Удаляем аватар
        if ($a_personal == '1' && !$edit) {
            unlink(System::config('general/personal_avatars_dir') . $avatar);
        }
        System::site()->AddTextBox('Ошибка', $text);
        IndexUserRegistration(true, $edit);
    }
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
//«десь нужно получить данные формы и сохранить их в переменную $block_config
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
if (isset($_POST['topic'])) {
    $block_config = SafeEnv($_POST['topic'], 11, int);
} else {
    $block_config = 0;
}
System::cache()->Delete('block', 'mail');
    // Тема новостей
    $max_news = SafeDB($block_config['count'], 11, int);
    // Количество новостей в блоке
    if ($topic != 0) {
        $where = "`enabled`='1' and `topic_id`='{$topic}'";
    } else {
        $where = "`enabled`='1'";
    }
    $newsdb = System::database()->Select('news', GetWhereByAccess('view', $where), $max_news, 'date', true);
    $news = array();
    foreach ($newsdb as $new) {
        $news[] = array('title' => SafeDB($new['title'], 255, str), 'text' => substr(SafeDB($new['start_text'], 0, str, true, false), 0, 255), 'date' => $new['date'], 'url' => Ufu('index.php?name=news&op=readfull&news=' . SafeDB($new['id'], 11, int) . '&topic=' . SafeDB($new['topic_id'], 11, int), 'news/{topic}/{news}/'));
    }
    System::cache()->Write('block', $bcache_name, $news);
} else {
    $news = System::cache()->Get('block', $bcache_name);
}
$count = count($news);
$en = !($count == 0);
$tempvars['content'] = 'block/content/news.html';
System::site()->AddBlock('no_news', !$en);
System::site()->AddBlock('block_news', $en);
System::site()->AddBlock('block_news_news', true, true, 'news');
foreach ($news as $new) {
    $text = $new['text'];
    $pp = strpos($text, '. ');
    if ($pp !== false) {
        $text = substr($text, 0, $pp + 1);
    } else {
        $text = substr($text, 0, 128) . ' ...';
    }
 /**
  * Удаление категории
  * @param $Id
  * @return bool
  */
 public function DeleteCat($Id)
 {
     $cat = System::database()->SelectOne($this->Table, "`id`='{$Id}'");
     $childs = $this->GetAllChildId($Id);
     for ($i = 0, $c = count($childs); $i < $c; $i++) {
         System::database()->Delete($this->obj_table, "`{$this->obj_cat_coll}`='" . $childs[$i] . "'");
         System::database()->Delete($this->Table, "`id`='" . $childs[$i] . "'");
     }
     Audit('Категории: Удаление категории "' . $this->Table . '"/"' . $cat['title'] . '"');
     $this->CalcCatCounter($cat['parent'], false);
     System::cache()->Delete('tree', $this->Table);
     return true;
 }
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
System::cache()->Delete('block', 'menu1');
System::cache()->Delete('block', 'menu2');
System::cache()->Delete('block', 'menu3');
System::cache()->Delete('block', 'menu4');
function AdminNewsClearBlockCache()
{
    System::cache()->Delete('block', array('news1', 'news2', 'news3', 'news4'));
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$vars['title'] = $title;
if (System::cache()->HasCache('block', 'forum_last_topics')) {
    $topics = System::cache()->Get('block', 'forum_last_topics');
} else {
    $count = SafeEnv($block_config, 11, int);
    $topics = System::database()->Select('forum_topics', "`delete` = '0'", $count, 'start_date', true);
    // TODO: надо бы сделать проверку видимости
    System::cache()->Write('block', 'forum_last_topics', $topics, Min2Sec * 10);
}
$en = !(count($topics) == 0);
$tempvars['content'] = 'block/content/forum_last_topics.html';
System::site()->AddBlock('no_topics', !$en);
System::site()->AddBlock('last_topics', $en);
System::site()->AddBlock('last_topic', true, true, 't');
foreach ($topics as $topic) {
    $forum_vars = array();
    $forum_vars['title'] = SafeDB($topic['title'], 255, str);
    $forum_vars['link'] = Ufu('index.php?name=forum&op=showtopic&topic=' . $topic['id'] . '&view=lastpost', 'forum/topic{topic}-new.html');
    System::site()->AddSubBlock('last_topic', true, $forum_vars);
}
/**
 * Сохраняет данные формы сгенерированной фукцией AdminUserEditor
 *
 * @param  $back_link
 * @param string $a
 * @param int $id
 * @param bool $IsAdmin
 * @return void
 */
function AdminUserEditSave($back_link, $a = 'insert', $id = 0, $IsAdmin = false)
{
    $SystemAdmin = System::user()->isSuperUser();
    $edit = $a == 'update';
    $editProfile = $edit && !$SystemAdmin && $id == System::user()->Get('u_id');
    // Администратор редактирует свой профиль
    $editStatus = false;
    // Разрешено редактирование статуса
    $editType = false;
    // Разрешено редактировать тип пользователя
    // Загружаем данные пользователя из БД
    if ($edit) {
        $user = System::database()->SelectOne('users', "`id`='{$id}'" . ($IsAdmin ? " and `type`='1'" : " and `type`='2'"));
        if (!$user) {
            AddTextBox('Ошибка', '<p align="center">Пользователь не найден, либо у вас не достаточно прав для редактирования администраторов.</p>');
            return;
        }
    }
    // Устанавливаем ограничения доступа
    if ($IsAdmin) {
        // Редактируем администратора
        if ($SystemAdmin) {
            // Только системные администраторы могут редактировать статус и тип администраторов
            if (!$edit) {
                $editStatus = true;
            } elseif (!(groupIsSystem(SafeEnv($user['access'], 11, int)) && GetSystemAdminsCount() <= 1)) {
                // Если он не системный или системных больше 1
                $editStatus = true;
            }
            $editType = $editStatus;
        }
    } else {
        // Если пользователь
        $editStatus = true;
        // Все администраторы с доступом могут редактировать статус пользователя
        $editType = $SystemAdmin;
        // Только системные администраторы могут создавать администраторов
    }
    // Обрабатываем данные
    $errors = array();
    // Логин
    if (isset($_POST['login']) && CheckLogin($_POST['login'], $errors, !$edit)) {
        $login = SafeEnv($_POST['login'], 30, str);
    } else {
        $login = '';
    }
    // Пароль
    $pass = '';
    if (!$edit || $_POST['pass'] != '') {
        $pass_generate_message = '';
        if (isset($_POST['pass']) && CheckPass($_POST['pass'], $errors)) {
            $pass = SafeEnv($_POST['pass'], 30, str);
            if (!isset($_POST['rpass']) || SafeEnv($_POST['rpass'], 30, str) != $pass) {
                $errors[] = 'Пароли не совпадают.';
            }
        } else {
            $pass = '';
        }
        if (isset($_POST['pass']) && $_POST['pass'] == '') {
            srand(time());
            $pass = GenBPass(rand(System::config('user/pass_min_length'), 15));
            $pass_generate_message = '<br />Так как вы не указали пароль, он был сгенерирован автоматически и выслан на указанный E-mail пользователя.';
        }
        $pass2 = md5($pass);
    }
    // e-mail
    if (isset($_POST['email']) && $_POST['email'] != '') {
        if (!CheckEmail($_POST['email'])) {
            $errors[] = 'Не правильный формат E-mail. Он должен быть вида: <b>domain@host.ru</b> .';
        }
        $email = SafeEnv($_POST['email'], 50, str, true);
    } else {
        $email = '';
        $errors[] = 'Вы не ввели E-mail.';
    }
    // Скрыть e-mail
    if (isset($_POST['hideemail'])) {
        $hide_email = '1';
    } else {
        $hide_email = '0';
    }
    // Имя пользователя на сайте
    if (isset($_POST['nikname']) && CheckNikname($_POST['nikname'], $errors, !$edit)) {
        $nik_name = SafeEnv($_POST['nikname'], 50, str, true);
    } else {
        $nik_name = '';
    }
    // Полное имя
    if (isset($_POST['realname'])) {
        $real_name = SafeEnv($_POST['realname'], 250, str, true);
    } else {
        $real_name = '';
    }
    // Возраст
    if (isset($_POST['age'])) {
        if ($_POST['age'] == '' || is_numeric($_POST['age'])) {
            $age = SafeEnv($_POST['age'], 3, int);
        } else {
            $errors[] = 'Ваш возраст должен быть числом!';
        }
    } else {
        $age = '';
    }
    // Домашняя страница
    if (isset($_POST['homepage'])) {
        if ($_POST['homepage'] != '' && substr($_POST['homepage'], 0, 7) == 'http://') {
            $_POST['homepage'] = substr($_POST['homepage'], 7);
        }
        $homepage = SafeEnv($_POST['homepage'], 250, str, true);
    } else {
        $homepage = '';
    }
    // Номер ICQ
    if (isset($_POST['icq'])) {
        if ($_POST['icq'] == '' || is_numeric($_POST['icq'])) {
            $icq = SafeEnv($_POST['icq'], 15, str, true);
        } else {
            $errors[] = 'Номер ICQ должен содержать только числа!';
        }
    } else {
        $icq = '';
    }
    // Город
    if (isset($_POST['city'])) {
        $city = SafeEnv($_POST['city'], 100, str, true);
    } else {
        $city = '';
    }
    // Часовой пояс
    if (isset($_POST['gmt'])) {
        $gmt = SafeEnv($_POST['gmt'], 255, str);
    } else {
        $gmt = System::config('general/default_timezone');
    }
    // О себе
    if (isset($_POST['about'])) {
        $about = SafeEnv($_POST['about'], System::config('user/about_max_length'), str, true);
    } else {
        $about = '';
    }
    // Подписка на новости
    if (isset($_POST['snews'])) {
        $server_news = '1';
    } else {
        $server_news = '0';
    }
    //Обрабатываем аватар
    $updateAvatar = true;
    if (isset($_POST['avatar'])) {
        if (System::config('user/avatar_transfer') == '1' && isset($_FILES['upavatar']) && file_exists($_FILES['upavatar']['tmp_name'])) {
            if ($edit) {
                $avatar = $user['avatar'];
                $a_personal = $user['a_personal'];
            } else {
                $avatar = '';
                $a_personal = '0';
            }
            UserLoadAvatar($errors, $avatar, $a_personal, $avatar, $a_personal, $edit);
        } elseif ($_POST['avatar'] == '') {
            $updateAvatar = false;
        } elseif (file_exists(RealPath2(System::config('general/avatars_dir') . $_POST['avatar']))) {
            if ($edit) {
                if ($user['a_personal'] == '1') {
                    UnlinkUserAvatarFiles($user['avatar']);
                }
            }
            $a_personal = '0';
            $avatar = $_POST['avatar'];
        } else {
            $avatar = '';
            $a_personal = '0';
        }
    } else {
        $avatar = '';
        $a_personal = '0';
    }
    $SendActivation = false;
    if ($edit) {
        $active = SafeEnv($user['active'], 11, int);
        $code = SafeEnv($user['activate'], 11, int);
    } else {
        $active = '1';
        $code = '';
    }
    if ($editStatus) {
        $activate = $_POST['activate'];
        $lastactivate = 'manual';
        if ($active == '0' && $code != '') {
            $lastactivate = 'mail';
        } elseif ($active == '1' && $code == '') {
            $lastactivate = 'auto';
        }
        if ($activate != $lastactivate) {
            switch ($activate) {
                case 'manual':
                    $active = '0';
                    $code = '';
                    $SendActivation = false;
                    break;
                case 'auto':
                    $active = '1';
                    $code = '';
                    $SendActivation = false;
                    break;
                case 'mail':
                    $active = '0';
                    $code = GenRandomString(8, 'qwertyuiopasdfghjklzxcvbnm');
                    $SendActivation = true;
                    break;
            }
        }
    }
    if ($edit) {
        $access = SafeEnv($user['type'], 11, int);
        $user_type = SafeEnv($user['access'], 11, int);
    } else {
        $access = '2';
        $user_type = '-1';
    }
    if ($editType && $_POST['status'] != 'member') {
        $access = '1';
        $user_type = SafeEnv($_POST['status'], 11, int);
    }
    $reg_date = time();
    $last_visit = time();
    $ip = getip();
    $points = 0;
    $visits = 0;
    if ($SendActivation) {
        UserSendActivationMail($nik_name, $email, $login, $pass, $code, $reg_date);
    } elseif (!$edit) {
        UserSendEndRegMail($email, $nik_name, $login, $pass, $reg_date);
    }
    if (!$edit) {
        $values = Values('', $login, $pass2, $nik_name, $real_name, $age, $email, $hide_email, $city, $icq, $homepage, $gmt, $avatar, $about, $server_news, $reg_date, $last_visit, $ip, $points, $visits, $active, $code, $access, $user_type, $a_personal, serialize(array()));
        System::database()->Insert('users', $values);
    } else {
        $set = "`login`='{$login}',`email`='{$email}',`hideemail`='{$hide_email}',`name`='{$nik_name}'," . "`truename`='{$real_name}',`age`='{$age}',`url`='{$homepage}',`icq`='{$icq}',`city`='{$city}'," . "`timezone`='{$gmt}'" . ($updateAvatar == true ? ",`avatar`='{$avatar}',`a_personal`='{$a_personal}'" : '') . "," . "`about`='{$about}',`servernews`='{$server_news}'" . ($pass != '' ? ",`pass`='{$pass2}'" : '') . ",`type`='{$access}'," . "`access`='{$user_type}',`active`='{$active}',`activate`='{$code}'";
        System::database()->Update('users', $set, "`id`='" . $id . "'");
        System::user()->UpdateMemberSession();
        UpdateUserComments($id, $id, $nik_name, $email, $hide_email, $homepage);
    }
    if (count($errors) > 0) {
        $text = 'Аккаунт сохранен, но имели место следующие ошибки:<br /><ul>';
        foreach ($errors as $error) {
            $text .= '<li>' . $error;
        }
        $text .= '</ul>';
        AddTextBox('Внимание', $text);
    } else {
        // Очищаем кэш пользователей
        System::cache()->Delete(system_cache, 'users');
        if (!$editProfile) {
            GO(ADMIN_FILE . '?exe=' . $back_link);
        } else {
            System::admin()->AddCenterBox('Редактирование профиля');
            System::admin()->Highlight('Ваш профиль сохранён, обновите страницу.');
        }
    }
}
/**
 * Сохраняет конфигурацию в базе данных
 * @param $Exe
 * @param string $Group
 * @param bool $ShowHidden
 * @return void
 */
function AdminConfigurationSave($Exe, $Group = '', $ShowHidden = false)
{
    global $config, $conf_config_table, $conf_config_groups_table;
    // Вытаскиваем настройки и отсортировываем по группам
    $temp = System::database()->Select($conf_config_table, '');
    for ($i = 0, $cnt = count($temp); $i < $cnt; $i++) {
        $configs[$temp[$i]['group_id']][] = $temp[$i];
    }
    unset($temp);
    // Вытаскиваем группы настроек
    if ($Group == '') {
        $q = '';
    } else {
        $q = "`name`='" . $Group . "'";
    }
    $cfg_grps = System::database()->Select($conf_config_groups_table, $q);
    for ($i = 0, $cnt = count($cfg_grps); $i < $cnt; $i++) {
        // Если эта группа невидима то пропускаем её
        if ($Group == '') {
            if ($cfg_grps[$i]['visible'] == 0) {
                continue;
            }
        }
        // Или если в ней нет настроек
        if (!isset($configs[$cfg_grps[$i]['id']])) {
            continue;
        }
        for ($j = 0, $jcnt = count($configs[$cfg_grps[$i]['id']]); $j < $jcnt; $j++) {
            // Если настройка невидима то пропускаем её
            if ($configs[$cfg_grps[$i]['id']][$j]['visible'] == 0 && !$ShowHidden) {
                continue;
            }
            $name = $configs[$cfg_grps[$i]['id']][$j]['name'];
            $kind = explode(':', $configs[$cfg_grps[$i]['id']][$j]['kind']);
            $kind = trim(strtolower($kind[0]));
            $savefunc = trim($configs[$cfg_grps[$i]['id']][$j]['savefunc']);
            $type = trim($configs[$cfg_grps[$i]['id']][$j]['type']);
            if ($type != '') {
                $type = explode(',', $type);
            } else {
                $type = array(255, str, false);
            }
            $where = "`name`='{$name}' and `group_id`='" . $cfg_grps[$i]['id'] . "'";
            if (isset($_POST[$name])) {
                switch ($kind) {
                    case 'edit':
                    case 'radio':
                    case 'combo':
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            $value = FormsCheckType($_POST[$name], $type);
                        }
                        break;
                    case 'text':
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            $value = FormsCheckType($_POST[$name], $type);
                        }
                        break;
                    case 'check':
                    case 'list':
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            if (isset($_POST[$name])) {
                                $c = count($_POST[$name]);
                            } else {
                                $c = 0;
                            }
                            $value = '';
                            for ($k = 0; $k < $c; $k++) {
                                $value .= ',';
                                $value .= FormsCheckType($_POST[$name][$k], $type);
                            }
                            $value = substr($value, 1);
                        }
                        break;
                    default:
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            $value = FormsCheckType($_POST[$name], $type);
                        }
                }
                System::database()->Update($conf_config_table, 'value=\'' . $value . '\'', $where);
                // FIXME: Использовать транзакцию
            }
        }
    }
    // Очищаем кэш настроек
    System::cache()->Clear('config');
    GO(ADMIN_FILE . '?exe=' . $Exe);
}
        $id = SafeEnv($r['id'], 11, int);
        System::database()->Update('forms', "`link`='{$link}'", "`id`='{$id}'");
    }
    // Обновление таблицы rewrite_rules
    System::database()->Truncate('rewrite_rules');
    System::database()->InsertColl('rewrite_rules', Unserialize('a:4:{s:4:"name";s:4:"name";s:4:"type";s:7:"varchar";s:6:"length";i:255;s:7:"notnull";b:1;}'), 0);
    System::database()->InsertColl('rewrite_rules', Unserialize('a:4:{s:4:"name";s:6:"module";s:4:"type";s:7:"varchar";s:6:"length";i:255;s:7:"notnull";b:1;}'), 1);
    System::database()->InsertColl('rewrite_rules', Unserialize('a:4:{s:4:"name";s:11:"description";s:4:"type";s:7:"varchar";s:6:"length";i:255;s:7:"notnull";b:1;}'), 2);
    System::database()->InsertColl('rewrite_rules', Unserialize('a:4:{s:4:"name";s:5:"order";s:4:"type";s:3:"int";s:6:"length";i:11;s:7:"notnull";b:1;}'), 6);
    // Системные правила
    UfuAddRuleByTemplate('system', 'mod', 'Ссылка на модуль', 'name={str}', '{name}/', 1000);
    // Правила для страниц
    UfuAddRuleByTemplate('pages', 'page', 'Ссылка на страницу', 'name=pages&file={ustr}', '{file}.html');
    // Правила для модуля веб форм
    UfuAddRuleByTemplate('forms', 'form', 'Страница с формой', 'name=forms&formlink={ustr}', 'forms/{formlink}.html');
    Ufu('index.php?name=forms&form={num}', 'forms/{form}/');
    Ufu('index.php?name=news&op=topics', 'news/{op}/', 15000);
    // Обновление шаблона
    $template = System::config('general/site_template');
    if ($template != 'default' && $template != 'IgrimTheme') {
        $file_name = System::config('tpl_dir') . $template . '/module/user_list.html';
        $temp_content = file_get_contents($file_name);
        $temp_content = str_replace('{title.last}', '{title.last_visit}', $temp_content);
        file_put_contents($file_name, $temp_content);
    }
    // Пересборка ядра
    if (is_file('config/system_build.php')) {
        unlink('config/system_build.php');
    }
    System::cache()->ClearAll();
}
        } elseif ($Icon == 'folder') {
            $Icon = 'images/folder.png';
        } elseif ($Icon == 'page') {
            $Icon = 'images/page.png';
        }
    }
    $sitemap_objects[$sitemap_category][] = array('is_raw' => false, 'margin' => 20 * $Level, 'title' => SafeDB($Title, 255, str), 'url' => $Url, 'icon' => $Icon);
}
/**
 * Добавляет текст на карту сайта без обработки.
 * @param $Data
 */
function SitemapAddRawData($Data)
{
    global $sitemap_objects, $sitemap_category;
    $sitemap_objects[$sitemap_category][] = array('is_raw' => true, 'raw_output' => SafeDB($Data, 0, str, false, false), 'margin' => 0);
}
if (System::cache()->HasCache(system_cache, 'sitemap')) {
    $sitemap_objects = System::cache()->Get(system_cache, 'sitemap');
} else {
    // Подключаем плагины генерирующие карту сайта
    IncludePluginsGroup('sitemap');
    System::cache()->Write(system_cache, 'sitemap', $sitemap_objects, Day2Sec);
}
foreach ($sitemap_objects as $title => $objects) {
    $sitemap_category = $Sitemap->NewSubBlock(true, array('title' => SafeDB($title, 255, str)));
    $sitemap_objects_block = $sitemap_category->NewBlock('sitemap_objects', true, true, 'object');
    foreach ($objects as $vars) {
        $sitemap_objects_block->NewSubBlock(true, $vars);
    }
}
示例#29
0
 /**
  * Flush this static class' cache.
  *
  * @return void
  */
 public static function flushCache()
 {
     self::$cache = array();
 }
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$bconf['topic'] = SafeEnv($_POST['topic'], 11, int);
$bconf['count'] = SafeEnv($_POST['count'], 11, int);
$block_config = serialize($bconf);
System::cache()->Delete('block', 'news1');
System::cache()->Delete('block', 'news2');
System::cache()->Delete('block', 'news3');
System::cache()->Delete('block', 'news4');