/**
 * Парсер смайликов.
 * @param  $text
 * @return void
 */
function SmiliesReplace(&$text)
{
    static $codes = null;
    if (!isset($codes)) {
        $codes = array();
        $smilies_dir = System::config('general/smilies_dir');
        $smilies = System::database()->Select('smilies');
        // Пусть отключенные смайлики тоже парсятся
        foreach ($smilies as $smile) {
            $sub_codes = explode(',', $smile['code']);
            $smile_file = SafeDB($smile['file'], 255, str);
            if ($smile['desc'] != '') {
                $title = SafeDB($smile['desc'], 255, str);
            } else {
                $title = SafeDB(GetFileName($smile_file, true), 255, str);
            }
            foreach ($sub_codes as $code) {
                $code = trim($code);
                if ($code != '') {
                    $codes[$code] = '<img src="' . RealPath2($smilies_dir . $smile_file) . '" title="' . $title . '">';
                }
            }
        }
    }
    $text = strtr($text, $codes);
}
function IndexForumEditTopic()
{
    global $forum_lang;
    if (!System::user()->Auth) {
        System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $forum_lang['error_auth'] . '</p>');
        return;
    }
    $topic = SafeEnv($_GET['topic'], 11, int);
    $post = System::database()->Select('forum_posts', "`object`='{$topic}' and `delete`='0'");
    SortArray($post, 'id', false);
    System::database()->Select('forum_topics', "`id`='{$topic}'");
    $topic = System::database()->FetchRow();
    if ($topic['delete'] == 0 || System::config('forum/basket') == false) {
        $title = '';
        if (SafeDB($topic['starter_id'], 11, str) == System::user()->Get('u_id') or System::user()->IsAdmin()) {
            $title = SafeDB($topic['title'], 0, str);
        }
        if (System::user()->Get('u_id') == $post[0]['user_id'] || System::user()->isAdmin()) {
            ForumRenderPostForm(true, 0, SafeEnv($_GET['topic'], 11, int), SafeDB($post[0]['id'], 11, int), SafeDB($post[0]['message'], 0, str, false, true), $title);
        } else {
            System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $forum_lang['no_right_comment_edit'] . '</p>');
            return;
        }
    } else {
        System::site()->AddTextBox($forum_lang['topic_basket_current_post'], '<p align="center">' . $forum_lang['topic_basket_post'] . '<br><input type="button" value="' . $forum_lang['back'] . '"onclick="history.back();"></p>');
    }
}
function getconf_TemplatesList($name)
{
    $r = array();
    $templates = System::database()->Select('templates', "`admin`='0'");
    foreach ($templates as $t) {
        $r[] = array(SafeDB($t['folder'], 255, str), SafeDB($t['name'], 255, str));
    }
    return $r;
}
function IndexForumMarkRead()
{
    $mark_forums = array();
    // Форумы на которых устанавливать метки
    $forums_tree = ForumTree::Instance();
    if (isset($_GET['forum'])) {
        // Только внутри определённого форума
        $forum = SafeDB($_GET['forum'], 11, int);
        $mark_forums = $forums_tree->GetAllAccessForumId($forum);
    } else {
        // На всех форумах
        $mark_forums = $forums_tree->GetAllAccessForumId();
    }
    $user_id = System::user()->Get('u_id');
    if (System::user()->Auth) {
        // Загружаем данные о прочтении тем пользователем
        $read_data = Forum_Marker_GetReadData();
        // Загружаем топики (агрегированы по forum_id)
        $topics = ForumCacheGetTopics();
        $del_where = '';
        $insert_values = array();
        $time = time();
        foreach ($mark_forums as $forum_id) {
            if (!isset($topics[$forum_id])) {
                continue;
            }
            foreach ($topics[$forum_id] as $topic) {
                $tid = SafeEnv($topic['id'], 11, int);
                // Не прочитана или метка устарела
                if (!isset($read_data[$topic['id']])) {
                    $insert_values[] = "'{$user_id}','{$tid}','{$time}'";
                    // Добавить новую метку
                } elseif ($read_data[$topic['id']]['date'] < $topic['last_post']) {
                    $del_where .= "(`tid`='{$tid}' and `mid`= '{$user_id}') or ";
                    // Удалить текущую метку
                    $insert_values[] = "'{$user_id}','{$tid}','{$time}'";
                    // Добавить новую метку
                }
            }
        }
        // Удаляем устаревшие метки
        if ($del_where != '') {
            $del_where = substr($del_where, 0, -4);
            // Удаляем .or.
            System::database()->Delete('forum_topics_read', $del_where);
        }
        // Добавляем новые метки
        // TODO: В будущем нужно перейти на InnoDB и использовать транзакции как в MySQL так и в FilesDB.
        if (count($insert_values) > 0) {
            foreach ($insert_values as $vals) {
                System::database()->Insert('forum_topics_read', $vals);
            }
        }
    }
    GO(GetSiteUrl() . Ufu('index.php?name=forum' . (isset($forum) ? '&op=showforum&forum=' . $forum : ''), 'forum/' . (isset($forum) ? '{forum}/' : '')));
}
function getconf_Polls_list($name)
{
    $polls = System::database()->Select('polls', "`showinblock`='1'");
    $polls_cnt = count($polls);
    $polls_data = array();
    for ($i = 0; $i < $polls_cnt; $i++) {
        $polls_data[] = array($polls[$i]['id'], $polls[$i]['question']);
    }
    return $polls_data;
}
Ejemplo n.º 6
0
 /**
  * Initialises the system
  * @static
  */
 public static function init()
 {
     self::redirectHTTPS();
     Router::getInstance()->init(HOST_PATH, MOD_REWRITE);
     self::$database = new Database('mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST, DATABASE_USER, DATABASE_PASS);
     self::$session = new Session();
     self::$user = System::getSession()->getUID() != NULL ? User::find('_id', System::getSession()->getUID()) : NULL;
     self::$language = new L10N(System::getUser() != NULL ? System::getUser()->lang : LANGUAGE);
     self::buildNavigation();
 }
function getconf_Pages($name)
{
    global $config;
    $pages = System::database()->Select('pages', "`enabled`='1' and `type`='page'");
    $r = array();
    foreach ($pages as $page) {
        $r[] = array(SafeEnv($page['link'], 255, str), SafeEnv($page['title'], 255, str));
    }
    return $r;
}
/**
 * Загружает информацию об установленных подключаемых плагинах из базы данных и возвращает результат.
 * Кэшируется.
 * @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;
}
function CalcMailCounter($topic_id, $inc)
{
    System::database()->Select('mail_topics', "`id`='" . $topic_id . "'");
    $topic = System::database()->FetchRow();
    if ($inc == true) {
        $counter_val = $topic['send_count'] + 1;
        $date = ",last_send='" . time() . "'";
    } else {
        $counter_val = $topic['send_count'] - 1;
        $date = '';
    }
    System::database()->Update('mail_topics', "send_count='" . $counter_val . "'" . $date, "`id`='" . $topic_id . "'");
}
function getconf_MainModules($name)
{
    // В $name имя элемента настройки вызвавшей функцию для своего заполнения.
    global $config;
    $mods = System::database()->Select('modules', "`isindex`='1'");
    $r = array();
    for ($i = 0, $cnt = count($mods); $i < $cnt; $i++) {
        // 1 значение,
        // 2 надпись которую будет видеть пользователь
        $r[] = array($mods[$i]['folder'], $mods[$i]['name']);
    }
    return $r;
}
function IndexForumSubscription()
{
    global $forum_lang;
    $forums_tree = ForumTree::Instance();
    // Проверки на доступ
    if (CheckGet('topic')) {
        // Тема
        $topic_id = SafeEnv($_GET['topic'], 11, int);
        System::database()->Select('forum_topics', "`id`='{$topic_id}'");
        if (System::database()->NumRows() > 0) {
            $topic = System::database()->FetchRow();
        } else {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_access_category']);
            return;
        }
        if ($topic['delete'] == '1') {
            // Тема на удалении
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_basket'] . '.' . $forum_lang['no_topic_basket_edit']);
            return;
        }
        if ($topic['close_topics'] == '1') {
            // Тема закрыта
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_close_for_discussion'] . '.' . $forum_lang['no_create_new_message_current_topic_add']);
            return;
        }
        // Форум
        $forum_id = SafeEnv($topic['forum_id'], 11, int);
        if (!isset($forums_tree->IdCats[$forum_id])) {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
            return;
        }
        $forum_config = $forums_tree->GetForumConfigRecursive($forum_id);
        if (!$forum_config['access']) {
            // Доступ
            System::site()->AddTextBox($forum_lang['error'], $forum_config['access_reason']);
            return;
        } elseif (!$forum_config['new_message_email']) {
            // Разрешено ли подписываться на новые сообщения (+ защита от гостей)
            System::site()->AddTextBox($forum_lang['error'], $forum_config['add_post_reason']);
            return;
        }
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    Forum_Subscription($topic_id);
    // Подписка (обратное действие, если пользователь уже подписан)
    GO(Ufu('index.php?name=forum&op=showtopic&topic=' . $topic_id . '&view=lastpost', 'forum/topic{topic}-new.html'));
}
/**
 * Записывает реферал в базу данных.
 * @param $referer
 */
function AuditWriteReferer($referer)
{
    if (trim($referer) != '' && !IsMainHost($referer)) {
        $referer = SafeEnv(Url($referer), 255, str);
        $count = 1;
        System::database()->Select('referers', "`referer`='{$referer}'");
        if (System::database()->NumRows() > 0) {
            $ref = System::database()->FetchRow();
            $count = SafeDB($ref['count'], 11, int);
            $count++;
            System::database()->Update('referers', "count='{$count}'", "`referer`='{$referer}'");
        } else {
            $values = Values('', $referer, $count);
            System::database()->Insert('referers', $values);
        }
    }
}
function IndexForumCloseTopic()
{
    if (!System::user()->isAdmin()) {
        HackOff();
        return;
    }
    if (CheckGet('topic')) {
        $topic_id = SafeEnv($_GET['topic'], 11, int);
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    System::database()->Select('forum_topics', "`id`='{$topic_id}'");
    $topic = System::database()->FetchRow();
    $forum_id = SafeDB($topic['forum_id'], 11, int);
    System::database()->Update('forum_topics', "`close_topics`='1'", "`id`='{$topic_id}'");
    GO(Ufu('index.php?name=forum&op=showforum&forum=' . $forum_id, 'forum/{forum}/'));
}
 public function LoadOnline($MainPage = false)
 {
     if (!$this->online_load) {
         $onlinerows = System::database()->Select('forum_online');
         $this->OnlineCount = count($onlinerows);
         $this->MainPage = $MainPage;
         if ($MainPage) {
             $levels = array(1 => 'admins', 2 => 'members', 3 => 'guests');
             $this->AllOnline = array('admins' => array(), 'members' => array(), 'guests' => array(), 'count' => $this->OnlineCount);
         }
         $online_cat = array();
         // Онлайн пользователи агрегированные по категориям
         $online_topic = array();
         // Онлайн пользователи агнегированные по топикам
         $cat_topics_id = array();
         foreach ($onlinerows as $row) {
             if ($MainPage) {
                 $this->AllOnline[$levels[$row['user_level']]][] = $row;
             }
             if ($row['forum_topic'] != '0') {
                 // Пользователь читает топик
                 $online_topic[$row['forum_topic']]['u'][] = $row;
                 if (!isset($online_topic[$row['forum_topic']]['c'])) {
                     $online_topic[$row['forum_topic']]['c'] = 0;
                 }
                 $online_topic[$row['forum_topic']]['c']++;
                 if (!in_array($row['forum_topic'], $cat_topics_id)) {
                     $cat_topics_id[$row['forum_cat']][] = $row['forum_topic'];
                 }
             } else {
                 $online_cat[$row['forum_cat']]['u'][] = $row;
                 if (!isset($online_cat[$row['forum_cat']]['c'])) {
                     $online_cat[$row['forum_cat']]['c'] = 0;
                 }
                 $online_cat[$row['forum_cat']]['c']++;
             }
         }
         $this->online_cat = $online_cat;
         $this->online_topic = $online_topic;
         $this->cat_topics_id = $cat_topics_id;
         $this->online_load = true;
     }
 }
                $vt = 'Неограниченно';
            }
            $adin = '(Просматривают: ' . ViewLevelToStr($msg['view'], 'Только администраторы', 'Только пользователи', 'Только анонимные пользователи', 'Все посетители') . ' - ' . $vt . ' - <a href="' . ADMIN_FILE . '?exe=messages&a=msgeditor&id=' . $msg['id'] . '">Редактировать</a>)';
        }
        if ($msg['view_title'] == 1) {
            // Показывать заголовок
            $title = $msg['title'];
        } else {
            $title = '';
        }
        System::site()->AddMessage($title, $msg['text'], $adin);
    }
}
foreach ($msgs as $a) {
    if ($a['position'] == '1') {
        MessagesRender($a);
    } else {
        $bottomMessages[] = $a;
    }
}
if ($disableMsg !== false) {
    $disableMsg = substr($disableMsg, 4);
    System::database()->Update('messages', "active='0'", $disableMsg);
}
function BottomMessages()
{
    global $bottomMessages;
    foreach ($bottomMessages as $a) {
        MessagesRender($a);
    }
}
    exit;
}
$table = SafeEnv($_GET['name'], 255, str);
$index = SafeEnv($_GET['index'], 255, int);
$where = '';
$where_url = '';
if (isset($_GET['where'])) {
    $where = $_GET['where'];
    $where_url = '&where=' . $_GET['where'];
}
$rows = System::database()->Select($table, $where);
$row = $rows[$index];
$columns = System::database()->GetTableColumns($table);
$names = array();
foreach ($columns as $col) {
    $names[$col['name']] = $row[$col['name']];
}
$sql = '';
foreach ($row as $key => $value) {
    if (isset($names[$key])) {
        $sql .= "`" . $key . "`='" . System::database()->EscapeString($value) . "' and ";
    }
}
$sql = substr($sql, 0, strlen($sql) - 4);
System::database()->Delete($table, $sql);
Audit('Управление БД: Удаление строки из таблицы "' . $table . '"');
if (isset($_REQUEST['back'])) {
    GoRefererUrl($_REQUEST['back']);
} else {
    GO(ADMIN_FILE . '?exe=dbadmin&a=review&name=' . SafeDB($_GET['name'], 255, str) . $where_url);
}
function AdminExtensionsConfigSave()
{
    $post = SafeR('view', 255, str) + SafeR('name, theme', 255, str) + SafeR('enabled', 3, onoff);
    $post['view'] = ViewLevelToInt($post['view']);
    System::database()->Update('modules', MakeSet($post), "`folder`='" . SafeEnv($_GET['name'], 255, str) . "'");
    Audit('Расширения: Изменение настроек модуля "' . $_GET['name'] . '"');
    GO(ADMIN_FILE . '?exe=extensions');
}
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$table = SafeEnv($_GET['name'], 255, str);
$index = SafeEnv($_GET['index'], 11, int);
$where = '';
if (isset($_GET['where'])) {
    $where = $_GET['where'];
}
$rows = System::database()->Select($table, $where);
$row = $rows[$index];
$row2 = array();
$columns = System::database()->GetTableColumns($table);
foreach ($columns as $col) {
    $row2[] = $row[$col['name']];
}
$row2 = SafeEnv($row2, 0, str);
$code_vals = Values($row2);
$install_code = "System::database()->Insert('{$table}',\"{$code_vals}\");" . EOL;
System::admin()->AddCenterBox('PHP код вставки');
System::admin()->FormRow('Установка', $site->TextArea('code', $install_code, 'style="width: 800px; height: 200px;" class="autofocus selectall"'));
System::admin()->AddForm('', $site->Button('Назад', 'onclick="history.go(-1);"'));
AdminFdbAdminGenTableMenu(SafeDB($table, 255, str));
/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
define('RSS_SCRIPT', true);
define('VALID_RUN', true);
require 'config/init.php';
// Конфигурация и инициализация
@header("Content-Type: text/xml");
@header("Cache-Control: no-cache");
@header("Pragma: no-cache");
$rss_title = 'Новости на ' . System::config('general/site_url');
$rss_link = System::config('general/site_url');
$rss_description = 'RSS канал сайта ' . System::config('general/site_url') . '.';
$rss = new RssChannel($rss_title, $rss_link, $rss_description);
$rss->pubDate = gmdate('D, d M Y H:i:s') . ' GMT';
$rss->generator = CMS_NAME . ' ' . CMS_VERSION;
$rss->managingEditor = '*****@*****.**';
$rss->webMaster = System::config('general/site_email');
$num = 10;
// Пока максимум 10 заголовков по умолчанию
$news = System::database()->Select('news', "`enabled`='1'", $num, 'date', true);
foreach ($news as $s) {
    $title = SafeDB($s['title'], 255, str);
    $description = SafeDB($s['start_text'], 4048, str);
    $link = HtmlChars(GetSiteUrl() . Ufu('index.php?name=news&op=readfull&news=' . $s['id'] . '&topic=' . $s['topic_id'], 'news/{topic}/{news}/'));
    $pubDate = gmdate('D, d M Y H:i:s', $s['date']) . ' GMT';
    $rss->AddItem($title, $description, $link, $pubDate, $link);
}
echo $rss->Generate();
    public function DeletePost($post_id = null, $first = true)
    {
        if ($post_id == null) {
            if (isset($_GET['post_id'])) {
                $post_id = $_GET['post_id'];
            }
        }
        if ($post_id != null) {
            System::database()->Select($this->PostsTable, "`id`='{$post_id}'");
            $post = System::database()->FetchRow();
        } else {
            $text = 'post_id нигде не инициализирована.';
            System::site()->AddTextBox('Ошибка.', '<p align="center">' . $text . '</p>');
            return 0;
        }
        if ($first) {
            if (System::user()->Auth) {
                $editing = System::user()->Get('u_id') == $post['user_id'] || System::user()->isAdmin();
            } else {
                $editing = $post['user_id'] == '0' && $post['user_ip'] == getip();
            }
            if (!$editing) {
                $text = 'У вас недостаточно прав для удаления этого сообщения.';
                System::site()->AddTextBox('Ошибка.', '<p align="center">' . $text . '</p>');
                return 0;
            }
        }
        if (!$first || isset($_GET['ok'])) {
            $del_count = 1;
            $parent_posts = System::database()->Select($this->PostsTable, "`post_parent_id`='{$post_id}'");
            foreach ($parent_posts as $post) {
                $del_count += $this->DeletePost(SafeDB($post['id'], 11, int), false);
            }
            System::database()->Delete($this->PostsTable, "`id`='{$post_id}'");
            if (System::user()->isAdmin()) {
                Audit('Posts: Удаление комментария "' . $this->PostsTable . '"/"' . "(user: {$post['user_name']}, object_id: {$post['object_id']})" . '"');
            }
            return $del_count;
        } else {
            $text = '<br />Удалить сообщение?<br /><br />' . '<a href="' . $this->DeletePageUrl . '&amp;post_id=' . $post_id . '&amp;ok=1">Да</a> &nbsp;
			&nbsp;&nbsp;&nbsp;&nbsp; <a href="javascript:history.go(-1)">Нет</a><br /><br />';
            System::site()->AddTextBox('', '<p align="center">' . $text . '</p>');
            return 0;
        }
    }
function AdminBlocksMove()
{
    $move = SafeEnv($_GET['to'], 4, str);
    $id = SafeEnv($_GET['id'], 11, int);
    System::database()->Select('blocks', "`id`='" . $id . "'");
    if (System::database()->NumRows() > 0) {
        $block = System::database()->FetchRow();
        $pos = SafeDB($block['place'], 255, str);
        $blocks = System::database()->Select('blocks', "`position`='" . SafeDB($block['position'], 1, str) . "'");
        usort($blocks, 'AdminBlocksSort');
        $c = count($blocks);
        $cur_pos = 0;
        for ($i = 0; $i < $c; $i++) {
            $blocks[$i]['place'] = $i;
            if ($blocks[$i]['id'] == $id) {
                $cur_pos = $i;
            }
        }
        //Индекс перемещения
        $rep_pos = $cur_pos;
        if ($move == 'up') {
            $rep_pos = $cur_pos - 1;
        } elseif ($move == 'down') {
            $rep_pos = $cur_pos + 1;
        } else {
            $rep_pos = $cur_pos;
        }
        if ($rep_pos < 0 || $rep_pos >= $c) {
            $rep_pos = $cur_pos;
        }
        $temp = intval($blocks[$cur_pos]['place']);
        $blocks[$cur_pos]['place'] = intval($blocks[$rep_pos]['place']);
        $blocks[$rep_pos]['place'] = intval($temp);
        //Обновляем данные
        for ($i = 0; $i < $c; $i++) {
            System::database()->Update('blocks', "place='" . SafeDB($blocks[$i]['place'], 11, int) . "'", "`id`='" . SafeDB($blocks[$i]['id'], 11, int) . "'");
        }
    }
    Audit('Блока: Перемещение блока ' . ($move == 'up' ? 'вверх' : 'вниз') . ' "' . $block['title'] . '"');
    GO(ADMIN_FILE . '?exe=blocks');
}
/**
 * Функция пересчитывает инкремент поля таблицы и сбрасывает counter на количество записей в таблице.
 */
function AdminDbRepairResetId()
{
    if (System::database()->Name != 'FilesDB') {
        return;
    }
    $table = $_GET['table'];
    $columns = System::database()->GetTableColumns($table);
    $increment_columns = array();
    foreach ($columns as $c) {
        if (isset($c['auto_increment']) && $c['auto_increment'] == true) {
            $increment_columns[] = $c['name'];
        }
    }
    $data = System::database()->Select($table);
    System::database()->Truncate($table);
    foreach ($data as $row) {
        foreach ($increment_columns as $name) {
            $row[$name] = '';
        }
        $row = SafeEnv($row, 0, str, false, true, false);
        System::database()->Insert($table, Values($row));
    }
}
 RemoveConfig('news', 'thumb_max_width');
 RemoveConfig('news', 'thumb_max_height');
 // Обновление таблицы forms (добавление текстовой ссылки)
 System::database()->InsertColl('forms', Unserialize('a:5:{s:4:"name";s:4:"link";s:4:"type";s:7:"varchar";s:6:"length";i:255;s:7:"notnull";b:1;s:5:"index";b:1;}'), 2);
 $rows = System::database()->Select('forms');
 foreach ($rows as $r) {
     $link = SafeEnv(UfuLink($r['hname']), 255, str);
     $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);
function IndexForumAddPost()
{
    global $forum_lang;
    $forums_tree = ForumTree::Instance();
    // Проверки на доступ
    if (CheckGet('topic')) {
        // Тема
        $topic_id = SafeEnv($_GET['topic'], 11, int);
        System::database()->Select('forum_topics', "`id`='{$topic_id}'");
        if (System::database()->NumRows() > 0) {
            $topic = System::database()->FetchRow();
        } else {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_access_category']);
            return;
        }
        if ($topic['delete'] == '1') {
            // Тема на удалении
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_basket'] . '.' . $forum_lang['no_topic_basket_edit']);
            return;
        }
        if ($topic['close_topics'] == '1') {
            // Тема закрыта
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_close_for_discussion'] . '.' . $forum_lang['no_create_new_message_current_topic_add']);
            return;
        }
        // Форум
        $forum_id = SafeEnv($topic['forum_id'], 11, int);
        if (!isset($forums_tree->IdCats[$forum_id])) {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
            return;
        }
        $forum = $forums_tree->IdCats[$forum_id];
        $forum_config = $forums_tree->GetForumConfigRecursive($forum_id);
        if (!$forum_config['access']) {
            // Доступ
            System::site()->AddTextBox($forum_lang['error'], $forum_config['access_reason']);
            return;
        } elseif (!$forum_config['add_post']) {
            // Разрешено ли добавлять новые сообщения (+ защита от гостей)
            System::site()->AddTextBox($forum_lang['error'], $forum_config['add_post_reason']);
            return;
        }
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    // Добавляем сообщение
    if (!CheckPost('text') || strlen($_POST['text']) == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    $name = System::user()->Get('u_name');
    $email = System::user()->Get('u_email');
    $hideemail = System::user()->Get('u_hideemail');
    $site = System::user()->Get('u_homepage');
    $icq = System::user()->Get('u_icq');
    $uid = System::user()->Get('u_id');
    $text = SafeEnv($_POST['text'], 0, str);
    $vals = Values('', $topic_id, $uid, time(), $name, $site, $email, $hideemail, $icq, $text, getip(), 0);
    System::database()->Insert('forum_posts', $vals);
    // Обновляем время прочтения темы автором сообщения
    $user_id = System::user()->Get('u_id');
    System::database()->Delete('forum_topics_read', "`tid`='{$topic_id}' and `mid`='{$user_id}'");
    $time = time();
    $vals = "'{$user_id}','{$topic_id}','{$time}'";
    System::database()->Insert('forum_topics_read', $vals);
    // Информация о последнем сообщении в теме и форуме
    $forum['posts'] = (int) $forum['posts'] + 1;
    $topic['posts'] = (int) $topic['posts'] + 1;
    IndexForumSetLastPostInfo($forum, $topic);
    // Добавляем очков пользователю
    System::user()->ChargePoints(System::config('points/forum_post'));
    // Увеличиваем счётчик сообщений пользователя
    ForumCalcUserCounters(1);
    // Делаем рассылку подписчикам на эту тему
    Forum_Subscription_Send($topic_id);
    // Очищаем кэш форума
    ForumCacheClear();
    GO(Ufu('index.php?name=forum&op=showtopic&topic=' . $topic_id . '&view=lastpost#last', 'forum/topic{topic}-new.html'));
}
<?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 = 'Настройка блока рассылки';
$columns = System::database()->GetTableColumns($table);
$back = '';
if (isset($_REQUEST['back'])) {
    $back = '&back=' . SafeDB($_REQUEST['back'], 255, str);
}
$edit = false;
$where = '';
$where_url = '';
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"' : '')));
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
/*
 * Плагин вывода карты архива статей
 * Автор: Мартин
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
global $sitemap_show_objects, $sitemap_articles;
$sitemap_show_objects = System::config('general/sitemap_show_objects') ? '___SitemapPluginArticles2' : null;
$sitemap_articles = array();
if (isset($sitemap_show_objects)) {
    $articles = System::database()->Select('articles', "`active` = '1' and `view` = '4'", null, 'public');
    // Только включенные и доступные гостям
    foreach ($articles as $art) {
        $sitemap_articles[$art['cat_id']][] = array($art['title'], Ufu('index.php?name=articles&op=read&art=' . SafeDB($art['id'], 11, int) . '&cat=' . SafeDB($art['cat_id'], 11, int), 'articles/{cat}/{art}/'));
    }
    unset($articles);
}
function ___SitemapPluginArticles($Cat, $Level)
{
    SitemapAddObject($Level, $Cat['title'], Ufu('index.php?name=articles&cat=' . SafeDB($Cat['id'], 11, int), 'articles/{cat}'));
}
function ___SitemapPluginArticles2($CatId, $Level)
{
    global $sitemap_articles;
    if (isset($sitemap_articles[$CatId])) {
        foreach ($sitemap_articles[$CatId] as $art) {
/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
/*
 * Плагин вывода карты страниц
 * Автор: Мартин
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
global $pages, $pages_tree;
$pages = array();
$pages_db = System::database()->Select('pages', "`enabled` = '1' and `view` = '4'", null, 'order');
foreach ($pages_db as $p) {
    $link = false;
    if ($p['type'] == 'page') {
        $link = Ufu('index.php?name=pages&file=' . SafeDB($p['link'], 255, str), 'pages:page');
    }
    //	elseif($p['type'] == 'link'){
    //		$link = SafeDB($p['text'], 255, str);
    //		if(substr($link, 0, 6) == 'mod://'){
    //			$link = Ufu('index.php?name='.substr($link, 6), '{name}/');
    //		}
    //	}
    $p['link'] = $link;
    $pages[] = $p;
}
function ___SitemapPagesPlugin($Page, $Level)
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (System::database()->Name != 'MySQL') {
    echo "Только базы данных с поддержкой SQL.";
    exit;
}
if (isset($_POST['code'])) {
    $sql = Utf8ToCp1251($_POST['code']);
} else {
    echo "Code is Empty";
    exit;
}
$result = '';
$sql = explode(";", $sql);
foreach ($sql as $query) {
    if (trim($query) == '') {
        continue;
    }
    $qr = System::database()->MySQLQueryResult($query);
    Audit('Управление БД: Perform SQL:' . "\n" . $query);
    if ($qr === false) {
        echo System::database()->MySQLGetErrNo() . ': ' . System::database()->MySQLGetErrMsg() . "\n";
    } elseif (count($qr) > 0) {
        print_r($qr);
        echo "\n";
    } else {
        echo "Запрос успешно выполнен.";
    }
}
exit;
<?php

/*
 * LinkorCMS 1.4
 * © 2012 LinkorCMS Development Group
 */
if (!defined('VALID_RUN')) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
global $search_results, $searchstr;
$objects = System::database()->Select('articles', GetWhereByAccess('view', "`active`='1'"));
foreach ($objects as $object) {
    $result = array();
    $result['mod'] = $plugin_info['mod_title'];
    // Имя модуля
    $result['coincidence'] = '';
    // Показывает где было совпадение
    $result['title'] = SafeDB($object['title'], 255, str);
    $result['public'] = TimeRender(SafeDB($object['public'], 11, int));
    // Дата публикации
    $result['link'] = Ufu('index.php?name=articles&op=read&art=' . SafeDB($object['id'], 11, int) . '&cat=' . SafeDB($object['cat_id'], 11, int), 'articles/{cat}/{art}/');
    $result['text'] = SafeDB($object['description'], 0, str);
    if (strlen($result['text']) > 255) {
        $result['text'] = substr($result['text'], 0, 255) . '&nbsp; ...';
    }
    if (SSearch($object['seo_keywords'], $searchstr) != false) {
        $result['coincidence'] = 'Ключевые слова статьи';
        $search_results[] = $result;
    } elseif (SSearch($object['seo_description'], $searchstr) != false) {
        $result['coincidence'] = 'Описание статьи';