Beispiel #1
0
function content()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    $model = new cms_model_content();
    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) {
        cmsCore::loadClass('billing');
    }
    global $_LANG;
    $id = cmsCore::request('id', 'int', 0);
    $do = $inCore->do;
    $seolink = cmsCore::strClear(urldecode(cmsCore::request('seolink', 'html', '')));
    if (is_numeric($seolink)) {
        cmsCore::error404();
    }
    $page = cmsCore::request('page', 'int', 1);
    ///////////////////////////////////// VIEW CATEGORY ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'view') {
        $cat = $inDB->getNsCategory('cms_category', $seolink);
        // если не найдена категория и мы не на главной, 404
        if (!$cat && $inCore->menuId() !== 1) {
            cmsCore::error404();
        }
        // языки
        $cat = translations::process(cmsConfig::getConfig('lang'), 'content_category', $cat);
        // Плагины
        $cat = cmsCore::callEvent('GET_CONTENT_CAT', $cat);
        // Неопубликованные показываем только админам
        if (!$cat['published'] && !$inUser->is_admin) {
            cmsCore::error404();
        }
        // Проверяем доступ к категории
        if (!$inCore->checkUserAccess('category', $cat['id'])) {
            cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
            cmsCore::redirect('/content');
        }
        // если не корень категорий
        if ($cat['NSLevel'] > 0) {
            $inPage->setTitle($cat['pagetitle'] ? $cat['pagetitle'] : $cat['title']);
            $pagetitle = $cat['title'];
            $showdate = $cat['showdate'];
            $showcomm = $cat['showcomm'];
            $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . htmlspecialchars($cat['title']) . '" href="' . HOST . '/rss/content/' . $cat['id'] . '/feed.rss">');
        }
        // Если корневая категория
        if ($cat['NSLevel'] == 0) {
            if ($model->config['hide_root']) {
                cmsCore::error404();
            }
            $inPage->setTitle($_LANG['CATALOG_ARTICLES']);
            $pagetitle = $_LANG['CATALOG_ARTICLES'];
            $showdate = 1;
            $showcomm = 1;
        }
        // Получаем дерево категорий
        $path_list = $inDB->getNsCategoryPath('cms_category', $cat['NSLeft'], $cat['NSRight'], 'id, title, NSLevel, seolink, url');
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'content_category', $path_list);
            foreach ($path_list as $pcat) {
                if (!$inCore->checkUserAccess('category', $pcat['id'])) {
                    cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
                    cmsCore::redirect('/content');
                }
                $inPage->addPathway($pcat['title'], $model->getCategoryURL(null, $pcat['seolink']));
            }
        }
        // Получаем подкатегории
        $subcats_list = $model->getSubCats($cat['id']);
        // Привязанный фотоальбом
        $cat_photos = $model->getCatPhotoAlbum($cat['photoalbum']);
        // Получаем статьи
        // Редактор/администратор
        $is_editor = $cat['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd') || $inUser->is_admin;
        // Условия
        $model->whereCatIs($cat['id']);
        // Общее количество статей
        $total = $model->getArticlesCount($is_editor);
        // Сортировка и разбивка на страницы
        $inDB->orderBy($cat['orderby'], $cat['orderto']);
        $inDB->limitPage($page, $model->config['perpage']);
        // Получаем статьи
        $content_list = $total ? $model->getArticlesList(!$is_editor) : array();
        $inDB->resetConditions();
        if (!$content_list && $page > 1) {
            cmsCore::error404();
        }
        $pagebar = cmsPage::getPagebar($total, $page, $model->config['perpage'], $model->getCategoryURL(null, $cat['seolink'], 0, true));
        $template = $cat['tpl'] ? $cat['tpl'] : 'com_content_view.tpl';
        if ($cat['NSLevel'] > 0) {
            // meta description
            if ($cat['meta_desc']) {
                $meta_desc = $cat['meta_desc'];
            } elseif (mb_strlen(strip_tags($cat['description'])) >= 250) {
                $meta_desc = crop($cat['description']);
            } else {
                $meta_desc = $cat['title'];
            }
            $inPage->setDescription($meta_desc);
            // meta keywords
            if ($cat['meta_keys']) {
                $meta_keys = $cat['meta_keys'];
            } elseif ($content_list) {
                foreach ($content_list as $c) {
                    $k[] = $c['title'];
                }
                $meta_keys = implode(', ', $k);
            } else {
                $meta_keys = $cat['title'];
            }
            $inPage->setKeywords($meta_keys);
        }
        cmsPage::initTemplate('components', $template)->assign('cat', $cat)->assign('is_homepage', (bool) ($inCore->menuId() == 1))->assign('showdate', $showdate)->assign('showcomm', $showcomm)->assign('pagetitle', $pagetitle)->assign('subcats', $subcats_list)->assign('cat_photos', $cat_photos)->assign('articles', $content_list)->assign('pagebar', $pagebar)->display($template);
    }
    ///////////////////////////////////// READ ARTICLE ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'read') {
        // Получаем статью
        $article = $model->getArticle($seolink);
        if (!$article) {
            cmsCore::error404();
        }
        $article = translations::process(cmsConfig::getConfig('lang'), 'content_content', $article);
        $article = cmsCore::callEvent('GET_ARTICLE', $article);
        $is_admin = $inUser->is_admin;
        $is_author = $inUser->id == $article['user_id'];
        $is_author_del = cmsUser::isUserCan('content/delete');
        $is_editor = $article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd');
        // если статья не опубликована или дата публикации позже, 404
        if ((!$article['published'] || strtotime($article['pubdate']) > time()) && !$is_admin && !$is_editor && !$is_author) {
            cmsCore::error404();
        }
        if (!$inCore->checkUserAccess('material', $article['id'])) {
            cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
            cmsCore::redirect($model->getCategoryURL(null, $article['catseolink']));
        }
        // увеличиваем кол-во просмотров
        if (@(!$is_author)) {
            $inDB->setFlag('cms_content', $article['id'], 'hits', $article['hits'] + 1);
        }
        // Картинка статьи
        $article['image'] = file_exists(PATH . '/images/photos/medium/article' . $article['id'] . '.jpg') ? 'article' . $article['id'] . '.jpg' : '';
        // Заголовок страницы
        $article['pagetitle'] = $article['pagetitle'] ? $article['pagetitle'] : $article['title'];
        // Тело статьи в зависимости от настроек
        $article['content'] = $model->config['readdesc'] ? $article['description'] . $article['content'] : $article['content'];
        // Дата публикации
        $article['pubdate'] = cmsCore::dateFormat($article['pubdate']);
        // Шаблон статьи
        $article['tpl'] = $article['tpl'] ? $article['tpl'] : 'com_content_read.tpl';
        $inPage->setTitle($article['pagetitle']);
        // Получаем дерево категорий
        $path_list = $article['showpath'] ? $inDB->getNsCategoryPath('cms_category', $article['leftkey'], $article['rightkey'], 'id, title, NSLevel, seolink, url') : array();
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'content_category', $path_list);
            foreach ($path_list as $pcat) {
                if (!$inCore->checkUserAccess('category', $pcat['id'])) {
                    cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
                    cmsCore::redirect('/content');
                }
                $inPage->addPathway($pcat['title'], $model->getCategoryURL(null, $pcat['seolink']));
            }
        }
        $inPage->addPathway($article['title']);
        // Мета теги KEYWORDS и DESCRIPTION
        if ($article['meta_keys']) {
            $inPage->setKeywords($article['meta_keys']);
        } else {
            if (mb_strlen($article['content']) > 30) {
                $inPage->setKeywords(cmsCore::getKeywords(cmsCore::strClear($article['content'])));
            }
        }
        if (mb_strlen($article['meta_desc'])) {
            $inPage->setDescription($article['meta_desc']);
        }
        // Выполняем фильтры
        $article['content'] = cmsCore::processFilters($article['content']);
        // Разбивка статей на страницы
        $pt_pages = array();
        if (!empty($GLOBALS['pt'])) {
            foreach ($GLOBALS['pt'] as $num => $page_title) {
                $pt_pages[$num]['title'] = $page_title;
                $pt_pages[$num]['url'] = $model->getArticleURL(null, $article['seolink'], $num + 1);
            }
        }
        // Рейтинг статьи
        if ($model->config['rating'] && $article['canrate']) {
            $karma = cmsKarma('content', $article['id']);
            $karma_points = cmsKarmaFormatSmall($karma['points']);
            $btns = cmsKarmaButtonsText('content', $article['id'], $karma['points'], $is_author);
        }
        cmsPage::initTemplate('components', $article['tpl'])->assign('article', $article)->assign('cfg', $model->config)->assign('page', $page)->assign('is_pages', !empty($GLOBALS['pt']))->assign('pt_pages', $pt_pages)->assign('is_admin', $is_admin)->assign('is_editor', $is_editor)->assign('is_author', $is_author)->assign('is_author_del', $is_author_del)->assign('tagbar', cmsTagBar('content', $article['id']))->assign('karma_points', @$karma_points)->assign('karma_votes', @$karma['votes'])->assign('karma_buttons', @$btns)->display($article['tpl']);
        // Комментарии статьи
        if ($article['published'] && $article['comments'] && $inCore->isComponentInstalled('comments')) {
            cmsCore::includeComments();
            comments('article', $article['id'], array(), $is_author);
        }
    }
    ///////////////////////////////////// ADD ARTICLE //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'addarticle' || $do == 'editarticle') {
        $is_add = cmsUser::isUserCan('content/add');
        // может добавлять статьи
        $is_auto_add = cmsUser::isUserCan('content/autoadd');
        // добавлять статьи без модерации
        if (!$is_add && !$is_auto_add) {
            cmsCore::error404();
        }
        // Для редактирования получаем статью и проверяем доступ
        if ($do == 'editarticle') {
            // Получаем статью
            $item = $model->getArticle($id);
            if (!$item) {
                cmsCore::error404();
            }
            $pubcats = array();
            // доступ к редактированию админам, авторам и редакторам
            if (!$inUser->is_admin && $item['user_id'] != $inUser->id && !($item['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd'))) {
                cmsCore::error404();
            }
        }
        // Для добавления проверяем не вводили ли мы данные ранее
        if ($do == 'addarticle') {
            $item = cmsUser::sessionGet('article');
            if ($item) {
                cmsUser::sessionDel('article');
            }
            // Категории, в которые разрешено публиковать
            $pubcats = $model->getPublicCats();
            if (!$pubcats) {
                cmsCore::addSessionMessage($_LANG['ADD_ARTICLE_ERR_CAT'], 'error');
                cmsCore::redirectBack();
            }
        }
        // не было запроса на сохранение, показываем форму
        if (!cmsCore::inRequest('add_mod')) {
            $dynamic_cost = false;
            // Если добавляем статью
            if ($do == 'addarticle') {
                $pagetitle = $_LANG['ADD_ARTICLE'];
                $inPage->setTitle($pagetitle);
                $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
                $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
                $inPage->addPathway($_LANG['MY_ARTICLES'], '/content/my.html');
                $inPage->addPathway($pagetitle);
                // поддержка биллинга
                if (IS_BILLING) {
                    $action = cmsBilling::getAction('content', 'add_content');
                    foreach ($pubcats as $p => $pubcat) {
                        if ($pubcat['cost']) {
                            $dynamic_cost = true;
                        } else {
                            $pubcats[$p]['cost'] = $action['point_cost'][$inUser->group_id];
                        }
                    }
                    cmsBilling::checkBalance('content', 'add_content', $dynamic_cost);
                }
            }
            // Если редактируем статью
            if ($do == 'editarticle') {
                $pagetitle = $_LANG['EDIT_ARTICLE'];
                $inPage->setTitle($pagetitle);
                $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
                if ($item['user_id'] != $inUser->id) {
                    $user = $inDB->get_fields('cms_users', "id='{$item['user_id']}'", 'login, nickname');
                    $inPage->addPathway($user['nickname'], cmsUser::getProfileURL($user['login']));
                } else {
                    $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
                }
                $inPage->addPathway($_LANG['MY_ARTICLES'], '/content/my.html');
                $inPage->addPathway($pagetitle);
                $item['tags'] = cmsTagLine('content', $item['id'], false);
                $item['image'] = file_exists(PATH . '/images/photos/small/article' . $item['id'] . '.jpg') ? 'article' . $item['id'] . '.jpg' : '';
                if (!$is_auto_add) {
                    cmsCore::addSessionMessage($_LANG['ATTENTION'] . ': ' . $_LANG['EDIT_ARTICLE_PREMODER'], 'info');
                }
            }
            $inPage->initAutocomplete();
            $autocomplete_js = $inPage->getAutocompleteJS('tagsearch', 'tags');
            $item = cmsCore::callEvent('PRE_EDIT_ARTICLE', @$item ? $item : array());
            cmsPage::initTemplate('components', 'com_content_edit')->assign('mod', $item)->assign('do', $do)->assign('cfg', $model->config)->assign('pubcats', $pubcats)->assign('pagetitle', $pagetitle)->assign('is_admin', $inUser->is_admin)->assign('is_billing', IS_BILLING)->assign('dynamic_cost', $dynamic_cost)->assign('autocomplete_js', $autocomplete_js)->display('com_content_edit.tpl');
        }
        // Пришел запрос на сохранение статьи
        if (cmsCore::inRequest('add_mod')) {
            $errors = false;
            $article['category_id'] = cmsCore::request('category_id', 'int', 1);
            $article['user_id'] = $item['user_id'] ? $item['user_id'] : $inUser->id;
            $article['title'] = cmsCore::request('title', 'str', '');
            $article['tags'] = cmsCore::request('tags', 'str', '');
            $article['description'] = cmsCore::request('description', 'html', '');
            $article['content'] = cmsCore::request('content', 'html', '');
            $article['description'] = cmsCore::badTagClear($article['description']);
            $article['content'] = cmsCore::badTagClear($article['content']);
            $article['published'] = $is_auto_add ? 1 : 0;
            if ($do == 'editarticle') {
                $article['published'] = $item['published'] == 0 ? $item['published'] : $article['published'];
            }
            $article['pubdate'] = $do == 'editarticle' ? $item['pubdate'] : date('Y-m-d H:i');
            $article['enddate'] = $do == 'editarticle' ? $item['enddate'] : $article['pubdate'];
            $article['is_end'] = $do == 'editarticle' ? $item['is_end'] : 0;
            $article['showtitle'] = $do == 'editarticle' ? $item['showtitle'] : 1;
            $article['meta_desc'] = $do == 'addarticle' ? mb_strtolower($article['title']) : $inDB->escape_string($item['meta_desc']);
            $article['meta_keys'] = $do == 'addarticle' ? $inCore->getKeywords($article['content']) : $inDB->escape_string($item['meta_keys']);
            $article['showdate'] = $do == 'editarticle' ? $item['showdate'] : 1;
            $article['showlatest'] = $do == 'editarticle' ? $item['showlatest'] : 1;
            $article['showpath'] = $do == 'editarticle' ? $item['showpath'] : 1;
            $article['comments'] = $do == 'editarticle' ? $item['comments'] : 1;
            $article['canrate'] = $do == 'editarticle' ? $item['canrate'] : 1;
            $article['pagetitle'] = '';
            if ($do == 'editarticle') {
                $article['tpl'] = $item['tpl'];
            }
            if (mb_strlen($article['title']) < 2) {
                cmsCore::addSessionMessage($_LANG['REQ_TITLE'], 'error');
                $errors = true;
            }
            if (mb_strlen($article['content']) < 10) {
                cmsCore::addSessionMessage($_LANG['REQ_CONTENT'], 'error');
                $errors = true;
            }
            if ($errors) {
                // При добавлении статьи при ошибках сохраняем введенные поля
                if ($do == 'addarticle') {
                    cmsUser::sessionPut('article', $article);
                }
                cmsCore::redirectBack();
            }
            $article['description'] = $inDB->escape_string($article['description']);
            $article['content'] = $inDB->escape_string($article['content']);
            $article = cmsCore::callEvent('AFTER_EDIT_ARTICLE', $article);
            // добавление статьи
            if ($do == 'addarticle') {
                $article_id = $model->addArticle($article);
            }
            // загрузка фото
            $file = 'article' . (@$article_id ? $article_id : $item['id']) . '.jpg';
            if (cmsCore::request('delete_image', 'int', 0)) {
                @unlink(PATH . "/images/photos/small/{$file}");
                @unlink(PATH . "/images/photos/medium/{$file}");
            }
            // Загружаем класс загрузки фото
            cmsCore::loadClass('upload_photo');
            $inUploadPhoto = cmsUploadPhoto::getInstance();
            // Выставляем конфигурационные параметры
            $inUploadPhoto->upload_dir = PATH . '/images/photos/';
            $inUploadPhoto->small_size_w = $model->config['img_small_w'];
            $inUploadPhoto->medium_size_w = $model->config['img_big_w'];
            $inUploadPhoto->thumbsqr = $model->config['img_sqr'];
            $inUploadPhoto->is_watermark = $model->config['watermark'];
            $inUploadPhoto->input_name = 'picture';
            $inUploadPhoto->filename = $file;
            // Процесс загрузки фото
            $inUploadPhoto->uploadPhoto();
            // операции после добавления/редактирования статьи
            // добавление статьи
            if ($do == 'addarticle') {
                // Получаем добавленную статью
                $article = $model->getArticle($article_id);
                if (!$article['published']) {
                    cmsCore::addSessionMessage($_LANG['ARTICLE_PREMODER_TEXT'], 'info');
                    // отсылаем уведомление администраторам
                    $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_ARTICLE_SUBMIT']);
                    $message = str_replace('%link%', $link, $message);
                    cmsUser::sendMessageToGroup(USER_UPDATER, cmsUser::getAdminGroups(), $message);
                } else {
                    //регистрируем событие
                    cmsActions::log('add_article', array('object' => $article['title'], 'object_url' => $model->getArticleURL(null, $article['seolink']), 'object_id' => $article['id'], 'target' => $article['cat_title'], 'target_url' => $model->getCategoryURL(null, $article['catseolink']), 'target_id' => $article['category_id'], 'description' => ''));
                    if (IS_BILLING) {
                        $category_cost = $article['cost'] === '' ? false : (int) $article['cost'];
                        cmsBilling::process('content', 'add_content', $category_cost);
                    }
                    cmsUser::checkAwards($inUser->id);
                }
                cmsCore::addSessionMessage($_LANG['ARTICLE_SAVE'], 'info');
                cmsCore::redirect('/my.html');
            }
            // Редактирование статьи
            if ($do == 'editarticle') {
                $model->updateArticle($item['id'], $article, true);
                cmsActions::updateLog('add_article', array('object' => $article['title']), $item['id']);
                if (!$article['published']) {
                    $link = '<a href="' . $model->getArticleURL(null, $item['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_ARTICLE_EDITED']);
                    $message = str_replace('%link%', $link, $message);
                    cmsUser::sendMessageToGroup(USER_UPDATER, cmsUser::getAdminGroups(), $message);
                }
                $mess = $article['published'] ? $_LANG['ARTICLE_SAVE'] : $_LANG['ARTICLE_SAVE'] . ' ' . $_LANG['ARTICLE_PREMODER_TEXT'];
                cmsCore::addSessionMessage($mess, 'info');
                cmsCore::redirect($model->getArticleURL(null, $item['seolink']));
            }
        }
    }
    ///////////////////////// PUBLISH ARTICLE /////////////////////////////////////////////////////////////////////////////
    if ($do == 'publisharticle') {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $article = $model->getArticle($id);
        if (!$article) {
            cmsCore::error404();
        }
        // Редактор с правами на добавление без модерации или администраторы могут публиковать
        if (!($article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd')) && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $inDB->setFlag('cms_content', $article['id'], 'published', 1);
        cmsCore::callEvent('ADD_ARTICLE_DONE', $article);
        if (IS_BILLING) {
            $author = $inDB->get_fields('cms_users', "id='{$article['user_id']}'", '*');
            $category_cost = $article['cost'] === '' ? false : (int) $article['cost'];
            cmsBilling::process('content', 'add_content', $category_cost, $author);
        }
        //регистрируем событие
        cmsActions::log('add_article', array('object' => $article['title'], 'user_id' => $article['user_id'], 'object_url' => $model->getArticleURL(null, $article['seolink']), 'object_id' => $article['id'], 'target' => $article['cat_title'], 'target_url' => $model->getCategoryURL(null, $article['catseolink']), 'target_id' => $article['cat_id'], 'description' => ''));
        $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
        $message = str_replace('%link%', $link, $_LANG['MSG_ARTICLE_ACCEPTED']);
        cmsUser::sendMessage(USER_UPDATER, $article['user_id'], $message);
        cmsUser::checkAwards($article['user_id']);
        cmsCore::redirectBack();
    }
    ///////////////////////////////////// DELETE ARTICLE ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'deletearticle') {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $article = $model->getArticle($id);
        if (!$article) {
            cmsCore::error404();
        }
        // права доступа
        $is_author = cmsUser::isUserCan('content/delete') && $article['user_id'] == $inUser->id;
        $is_editor = $article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd');
        if (!$is_author && !$is_editor && !$inUser->is_admin) {
            cmsCore::error404();
        }
        if (!cmsCore::inRequest('goadd')) {
            $inPage->setTitle($_LANG['ARTICLE_REMOVAL']);
            $inPage->addPathway($_LANG['ARTICLE_REMOVAL']);
            $confirm['title'] = $_LANG['ARTICLE_REMOVAL'];
            $confirm['text'] = $_LANG['ARTICLE_REMOVAL_TEXT'] . ' <a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>?';
            $confirm['action'] = $_SERVER['REQUEST_URI'];
            $confirm['yes_button'] = array();
            $confirm['yes_button']['type'] = 'submit';
            $confirm['yes_button']['name'] = 'goadd';
            cmsPage::initTemplate('components', 'action_confirm')->assign('confirm', $confirm)->display('action_confirm.tpl');
        } else {
            $model->deleteArticle($article['id']);
            if ($_SERVER['HTTP_REFERER'] == '/my.html') {
                cmsCore::addSessionMessage($_LANG['ARTICLE_DELETED'], 'info');
                cmsCore::redirectBack();
            } else {
                // если удалили как администратор или редактор и мы не авторы статьи, отсылаем сообщение автору
                if (($is_editor || $inUser->is_admin) && $article['user_id'] != $inUser->id) {
                    $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%link%', $link, $article['published'] ? $_LANG['MSG_ARTICLE_DELETED'] : $_LANG['MSG_ARTICLE_REJECTED']);
                    cmsUser::sendMessage(USER_UPDATER, $article['user_id'], $message);
                } else {
                    cmsCore::addSessionMessage($_LANG['ARTICLE_DELETED'], 'info');
                }
                cmsCore::redirect($model->getCategoryURL(null, $article['catseolink']));
            }
        }
    }
    ///////////////////////////////////// MY ARTICLES ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'my') {
        if (!cmsUser::isUserCan('content/add')) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['MY_ARTICLES']);
        $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
        $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
        $inPage->addPathway($_LANG['MY_ARTICLES']);
        $perpage = 15;
        // Условия
        $model->whereUserIs($inUser->id);
        // Общее количество статей
        $total = $model->getArticlesCount(false);
        // Сортировка и разбивка на страницы
        $inDB->orderBy('con.pubdate', 'DESC');
        $inDB->limitPage($page, $perpage);
        // Получаем статьи
        $content_list = $total ? $model->getArticlesList(false) : array();
        $inDB->resetConditions();
        cmsPage::initTemplate('components', 'com_content_my')->assign('articles', $content_list)->assign('total', $total)->assign('user_can_delete', cmsUser::isUserCan('content/delete'))->assign('pagebar', cmsPage::getPagebar($total, $page, $perpage, '/content/my%page%.html'))->display('com_content_my.tpl');
    }
    ///////////////////////////////////// BEST ARTICLES ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'best') {
        $inPage->setTitle($_LANG['ARTICLES_RATING']);
        $inPage->addPathway($_LANG['ARTICLES_RATING']);
        // Только статьи, за которые можно голосовать
        $inDB->where("con.canrate = 1");
        // Сортировка и разбивка на страницы
        $inDB->orderBy('con.rating', 'DESC');
        $inDB->limitPage(1, 30);
        // Получаем статьи
        $content_list = $model->getArticlesList();
        cmsPage::initTemplate('components', 'com_content_rating')->assign('articles', $content_list)->display('com_content_rating.tpl');
    }
}
Beispiel #2
0
function blogs() {
    $inCore = cmsCore::getInstance();
    
    cmsCore::c('blog')->owner = 'user';

    global $_LANG;

    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) { cmsCore::loadClass('billing'); }

    //Получаем параметры
    $id 	 = cmsCore::request('id', 'int', 0);
    $post_id     = cmsCore::request('post_id', 'int', 0);
    $bloglink    = cmsCore::request('bloglink', 'str', '');
    $seolink     = cmsCore::request('seolink', 'str', '');
    $page        = cmsCore::request('page', 'int', 1);
    $cat_id      = cmsCore::request('cat_id', 'int', 0);
    $ownertype   = cmsCore::request('ownertype', 'str', '');
    $on_moderate = cmsCore::request('on_moderate', 'int', 0);

    $pagetitle = $inCore->getComponentTitle();

    cmsCore::c('page')->addPathway($pagetitle, '/blogs');
    cmsCore::c('page')->setTitle($pagetitle);
    cmsCore::c('page')->setDescription(cmsCore::m('blogs')->config['meta_desc'] ? cmsCore::m('blogs')->config['meta_desc'] : $pagetitle);
    cmsCore::c('page')->setKeywords(cmsCore::m('blogs')->config['meta_keys'] ? cmsCore::m('blogs')->config['meta_keys'] : $pagetitle);
    cmsCore::c('page')->addHeadJsLang(array('CONFIG_BLOG','DEL_BLOG','YOU_REALY_DELETE_BLOG','NEW_CAT','RENAME_CAT','YOU_REALY_DELETE_CAT','YOU_REALY_DELETE_POST','NO_PUBLISHED'));

    ///////////////////////// МОЙ БЛОГ /////////////////////////////////////////
    if ($inCore->do == 'my_blog'){
        
        if(!cmsCore::c('user')->id){ cmsCore::error404(); }

	$my_blog = cmsCore::c('blog')->getBlogByUserId(cmsCore::c('user')->id);

        if (!$my_blog) {
            cmsCore::redirect('/blogs/createblog.html');
	} else {
            cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($my_blog['seolink']));
	}

    }
    ///////////////////////// ПОСЛЕДНИЕ ПОСТЫ //////////////////////////////////
    if ($inCore->do=='view'){

	cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['RSS_BLOGS'].'" href="'.HOST.'/rss/blogs/all/feed.rss">');

	// кроме админов в списке только с доступом для всех
	if(!cmsCore::c('user')->is_admin){
            cmsCore::c('blog')->whereOnlyPublic();
	}

	// ограничиваем по рейтингу если надо
	if(cmsCore::m('blogs')->config['list_min_rating']){
            cmsCore::c('blog')->ratingGreaterThan(cmsCore::m('blogs')->config['list_min_rating']);
	}

	// всего постов
	$total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin);

        //устанавливаем сортировку
        cmsCore::c('db')->orderBy('p.pubdate', 'DESC');

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage']);

	// сами посты
	$posts = cmsCore::c('blog')->getPosts(cmsCore::c('user')->is_admin, cmsCore::m('blogs'));
	if(!$posts && $page > 1){ cmsCore::error404(); }

	cmsPage::initTemplate('components', 'com_blog_view_posts')->
            assign('pagetitle', $pagetitle)->
            assign('ownertype', $ownertype)->
            assign('total', $total)->
            assign('posts', $posts)->
            assign('pagination', cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], '/blogs/latest-%page%.html'))->
            assign('cfg', cmsCore::m('blogs')->config)->
            display();
    }

    ////////// СОЗДАНИЕ БЛОГА //////////////////////////////////////////////////
    if ($inCore->do=='create'){
        //Проверяем авторизацию
        if (!cmsCore::c('user')->id){ cmsUser::goToLogin();  }

        //Если у пользователя уже есть блог, то выходим
        if (cmsCore::c('blog')->getUserBlogId(cmsCore::c('user')->id)) { cmsCore::redirectBack(); }

        cmsCore::c('page')->addPathway($_LANG['PATH_CREATING_BLOG']);
        cmsCore::c('page')->setTitle($_LANG['CREATE_BLOG']);

        if (IS_BILLING){ cmsBilling::checkBalance('blogs', 'add_blog'); }

        //Показ формы создания блога
        if (!cmsCore::inRequest('goadd')){
            cmsPage::initTemplate('components', 'com_blog_create')->
                assign('is_restrictions', (!cmsCore::c('user')->is_admin && cmsCore::m('blogs')->config['min_karma']))->
                assign('cfg', cmsCore::m('blogs')->config)->
                display();
        }

        //Сам процесс создания блога
        if (cmsCore::inRequest('goadd')){
            $title     = cmsCore::request('title', 'str');
            $allow_who = cmsCore::request('allow_who', 'str', 'all');
            $ownertype = cmsCore::request('ownertype', 'str', 'single');

            //Проверяем название
            if (mb_strlen($title)<5){
                cmsCore::addSessionMessage($_LANG['BLOG_ERR_TITLE'], 'error');
                cmsCore::redirect('/blogs/createblog.html');
            }

            //Проверяем хватает ли кармы, но только если это не админ
            if (cmsCore::m('blogs')->config['min_karma'] && !cmsCore::c('user')->is_admin){
                // если персональный блог
                if ($ownertype=='single' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_private'])){
                    cmsCore::addSessionMessage($_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_PERSON_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_private'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma, 'error');
                    cmsCore::redirect('/blogs/createblog.html');
                }

                // если коллективный блог
                if ($ownertype=='multi' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_public'])){
                    cmsCore::addSessionMessage($_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_TEAM_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_public'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma, 'error');
                    cmsCore::redirect('/blogs/createblog.html');
                }
            }

            //Добавляем блог в базу
            $blog_id   = cmsCore::c('blog')->addBlog(array('user_id'=>cmsCore::c('user')->id, 'title'=>$title, 'allow_who'=>$allow_who, 'ownertype'=>$ownertype, 'forall'=>1));
            $blog_link = cmsCore::c('db')->get_field('cms_blogs', "id='{$blog_id}'", 'seolink');
            //регистрируем событие
            cmsActions::log('add_blog', array(
                'object' => $title,
                'object_url' => cmsCore::m('blogs')->getBlogURL($blog_link),
                'object_id' => $blog_id,
                'target' => '',
                'target_url' => '',
                'target_id' => 0,
                'description' => ''
            ));

            if (IS_BILLING){ cmsBilling::process('blogs', 'add_blog'); }

            cmsCore::addSessionMessage($_LANG['BLOG_CREATED_TEXT'], 'info');
            cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($blog_link));
        }
    }
    
    ////////// НАСТРОЙКИ БЛОГА /////////////////////////////////////////////////
    if ($inCore->do=='config'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::error404(); }

        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }

        //Если нет запроса на сохранение, показываем форму настроек блога
        if (!cmsCore::inRequest('goadd')){
            //Получаем список авторов блога
            $authors = cmsCore::c('blog')->getBlogAuthors($blog['id']);

            cmsPage::initTemplate('components', 'com_blog_config')->
                assign('blog', $blog)->
                assign('form_action', '/blogs/'.$blog['id'].'/editblog.html')->
                assign('authors_list', cmsUser::getAuthorsList($authors))->
                assign('users_list', cmsUser::getUsersList(false, $authors))->
                assign('is_restrictions', (!cmsCore::c('user')->is_admin && cmsCore::m('blogs')->config['min_karma']))->
                assign('cfg', cmsCore::m('blogs')->config)->
                assign('is_admin', cmsCore::c('user')->is_admin)->
                display();

            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }

        //Если пришел запрос на сохранение
        if (cmsCore::inRequest('goadd')){
            //Получаем настройки
            $title     = cmsCore::request('title', 'str');
            $allow_who = cmsCore::request('allow_who', 'str', 'all');
            $ownertype = cmsCore::request('ownertype', 'str', 'single');
            $premod    = cmsCore::request('premod', 'int', 0);
            $forall    = cmsCore::request('forall', 'int', 1);
            $showcats  = cmsCore::request('showcats', 'int', 1);
            $authors   = cmsCore::request('authorslist', 'array_int', array());
            if (cmsCore::m('blogs')->config['seo_user_access'] || cmsCore::c('user')->is_admin) {
                $page_title = cmsCore::request('pagetitle', 'str', '');
                $meta_keys  = cmsCore::request('meta_keys', 'str', '');
                $meta_desc  = cmsCore::request('meta_desc', 'str', '');
            } else {
                $page_title = $meta_keys = $meta_desc = '';
            }
            //Проверяем настройки
            if (mb_strlen($title)<5) { $title = $blog['title']; }

            //Проверяем ограничения по карме (для смены типа блога)
            if (cmsCore::m('blogs')->config['min_karma'] && !cmsCore::c('user')->is_admin){
                // если персональный блог
                if ($ownertype=='single' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_private'])){
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_PERSON_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_private'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma));

                }
                
                // если коллективный блог
                if ($ownertype=='multi' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_public'])){
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_TEAM_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_public'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma));
                }
            }

            if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

            //сохраняем авторов
            cmsCore::c('blog')->updateBlogAuthors($blog['id'], $authors);

            //сохраняем настройки блога
            $blog['seolink_new'] = cmsCore::c('blog')->updateBlog($blog['id'], array(
                'title'     => $title,
                'pagetitle' => $page_title,
                'meta_keys' => $meta_keys,
                'meta_desc' => $meta_desc,
                'allow_who' => $allow_who,
                'showcats'  => $showcats,
                'ownertype' => $ownertype,
                'premod'    => $premod,
                'forall'    => $forall
            ), cmsCore::m('blogs')->config['update_seo_link_blog']);

            $blog['seolink'] = $blog['seolink_new'] ? $blog['seolink_new'] : $blog['seolink'];

            if(stripslashes($title) != $blog['title']){
                // обновляем записи постов
                cmsActions::updateLog('add_post', array('target' => $title, 'target_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink'])), 0, $blog['id']);
                // обновляем запись добавления блога
                cmsActions::updateLog('add_blog', array('object' => $title, 'object_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink'])), $blog['id']);
            }

            cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'])));
        }
    }
    
    ////////// СПИСОК БЛОГОВ ///////////////////////////////////////////////////
    if ($inCore->do=='view_blogs'){
        // rss в адресной строке
        cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['BLOGS'].'" href="'.HOST.'/rss/blogs/all/feed.rss">');

        // тип блога
        if($ownertype && $ownertype != 'all'){
            cmsCore::c('blog')->whereOwnerTypeIs($ownertype);
        }

        // всего блогов
        $total = cmsCore::c('blog')->getBlogsCount();

        //устанавливаем сортировку
        cmsCore::c('db')->orderBy('b.rating', 'DESC');

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage_blog']);

        //Получаем список блогов
        $blogs = cmsCore::c('blog')->getBlogs(cmsCore::m('blogs'));
        if(!$blogs && $page > 1){ cmsCore::error404(); }

        //Генерируем панель со страницами и устанавливаем заголовки страниц и глубиномера
        switch ($ownertype){
            case 'all':
                cmsCore::c('page')->setTitle($_LANG['ALL_BLOGS']);
                cmsCore::c('page')->setDescription($_LANG['BLOGS'] .' - '. $_LANG['ALL_BLOGS']);
                cmsCore::c('page')->addPathway($_LANG['ALL_BLOGS']);
                $link = '/blogs/all-%page%.html';
            break;
        
            case 'single':
                cmsCore::c('page')->setTitle($_LANG['PERSONALS']);
                cmsCore::c('page')->setDescription($_LANG['PERSONALS'] .' '. $_LANG['BLOGS']);
                cmsCore::c('page')->addPathway($_LANG['PERSONALS']);
                $link = '/blogs/single-%page%.html';
            break;
        
            case 'multi':
                cmsCore::c('page')->setTitle($_LANG['COLLECTIVES']);
                cmsCore::c('page')->setDescription($_LANG['COLLECTIVES'] .' '. $_LANG['BLOGS']);
                cmsCore::c('page')->addPathway($_LANG['COLLECTIVES']);
                $link = '/blogs/multi-%page%.html';
            break;
        }
        
        if ($blogs) {
            foreach ($blogs as $b) {
                $k[] = $b['title'];
            }
            
            cmsCore::c('page')->setKeywords(implode(', ', $k));
        }

        cmsPage::initTemplate('components', 'com_blog_view_all')->
            assign('cfg', cmsCore::m('blogs')->config)->
            assign('total', $total)->
            assign('ownertype', $ownertype)->
            assign('blogs', $blogs)->
            assign('pagination', cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage_blog'], $link))->
            display();
    }
    
    ////////// ПРОСМОТР БЛОГА //////////////////////////////////////////////////
    if ($inCore->do == 'blog'){
        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($bloglink);

        // Совместимость со старыми ссылками на клубные блоги
        // Пробуем клубный блог получить по ссылке
        if (!$blog) {
            $blog_user_id = cmsCore::c('db')->get_field('cms_blogs', "seolink = '$bloglink' AND owner = 'club'", 'user_id');
            if($blog_user_id){
                cmsCore::redirect('/clubs/'.$blog_user_id.'_blog', '301');
            }
        }

        if (!$blog) { cmsCore::error404(); }

        // Права доступа
        $myblog = (cmsCore::c('user')->id && cmsCore::c('user')->id == $blog['user_id']); // автор блога
        $is_writer = cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id); // может ли пользователь писать в блог

        cmsCore::c('page')->addPathway($blog['title'], cmsCore::m('blogs')->getBlogURL($blog['seolink']));
        // rss в адресной строке
        cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'.htmlspecialchars(strip_tags($blog['title'])).'" href="'.HOST.'/rss/blogs/'.$blog['id'].'/feed.rss">');
        if($myblog || cmsCore::c('user')->is_admin){
            cmsCore::c('page')->addHeadJS('components/blogs/js/blog.js');
        }

        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'].'<br>'.$_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blogs');
        }

        // Если показываем посты на модерации, если запрашиваем их
        if($on_moderate){
            if(!cmsCore::c('user')->is_admin && !($myblog && $blog['ownertype'] == 'multi' && $blog['premod'])){
                cmsCore::error404();
            }

            cmsCore::c('blog')->whereNotPublished();

            cmsCore::c('page')->setTitle($_LANG['POSTS_ON_MODERATE']);
            cmsCore::c('page')->addPathway($_LANG['POSTS_ON_MODERATE']);

            $blog['title'] .= ' - '.$_LANG['POSTS_ON_MODERATE'];
        }

        //Получаем html-код ссылки на автора с иконкой его пола
        $blog['author'] = cmsUser::getGenderLink($blog['user_id']);

        // посты данного блога
        cmsCore::c('blog')->whereBlogIs($blog['id']);

        // кроме админов автора в списке только с доступом для всех
        if(!cmsCore::c('user')->is_admin && !$myblog && !cmsCore::c('user')->isFriend($blog['user_id'])){
            cmsCore::c('blog')->whereOnlyPublic();
        }

        // если пришла категория
        if($cat_id){
            $all_total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin || $myblog);
            cmsCore::c('blog')->whereCatIs($cat_id);
        }

        // всего постов
        $total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin || $myblog);

        //устанавливаем сортировку
        cmsCore::c('db')->orderBy('p.pubdate', 'DESC');

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage']);

        // сами посты
        $posts = cmsCore::c('blog')->getPosts((cmsCore::c('user')->is_admin || $myblog), cmsCore::m('blogs'));
        if(!$posts && $page > 1){ cmsCore::error404(); }

        //Если нужно, получаем список рубрик (категорий) этого блога
        $blogcats = $blog['showcats'] ? cmsCore::c('blog')->getBlogCats($blog['id']) : false;

        //Считаем количество постов, ожидающих модерации
        $on_moderate = (cmsCore::c('user')->is_admin || $myblog) && !$on_moderate ? cmsCore::c('blog')->getModerationCount($blog['id']) : false;

        // админлинки
        $blog['moderate_link'] = cmsCore::m('blogs')->getBlogURL($blog['seolink']).'/moderate.html';
        $blog['blog_link']     = cmsCore::m('blogs')->getBlogURL($blog['seolink']);
        $blog['add_post_link'] = '/blogs/'.$blog['id'].'/newpost'.($cat_id ? $cat_id : '').'.html';

        //Генерируем панель со страницами
        if ($cat_id){
            $pagination = cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], $blog['blog_link'].'/page-%page%/cat-'.$cat_id);
        } else {
            $pagination = cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], $blog['blog_link'].'/page-%page%');
        }
        
        // SEO
        cmsCore::c('page')->setTitle($blog['pagetitle'] ? $blog['pagetitle'] : $blog['title']);
        cmsCore::c('page')->setDescription($blog['meta_desc'] ? $blog['meta_desc'] : $blog['title']);
        // keywords
        if ($blog['meta_keys']) {
            $meta_keys = $blog['meta_keys'];
        } else if ($posts) {
            foreach ($posts as $p) {
                $k[] = $p['title'];
            }
            $meta_keys = implode(', ', $k);
        } else {
            $meta_keys = $blog['title'];
        }
        cmsCore::c('page')->setKeywords($meta_keys);

        cmsPage::initTemplate('components', 'com_blog_view')->
            assign('myblog', $myblog)->
            assign('is_config', true)->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('is_writer', $is_writer)->
            assign('on_moderate', $on_moderate)->
            assign('cat_id', $cat_id)->
            assign('blogcats', $blogcats)->
            assign('total', $total)->
            assign('all_total', (isset($all_total) ? $all_total : 0))->
            assign('blog', $blog)->assign('posts', $posts)->
            assign('pagination', $pagination)->
            display();
    }

    ////////// НОВЫЙ ПОСТ / РЕДАКТИРОВАНИЕ ПОСТА ///////////////////////////////
    if ($inCore->do == 'newpost' || $inCore->do == 'editpost'){
        if (!cmsCore::c('user')->id){ cmsUser::goToLogin();  }

        // для редактирования сначала получаем пост
        if($inCore->do == 'editpost'){
            $post = cmsCore::c('blog')->getPost($post_id);
            
            if (!$post){ cmsCore::error404(); }
            
            $id = $post['blog_id'];
            
            $post['tags'] = cmsTagLine('blogpost', $post['id'], false);
        }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::error404(); }

        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'].'<br>'.$_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blogs');
        }

        // Права доступа
        $myblog = (cmsCore::c('user')->id && cmsCore::c('user')->id == $blog['user_id']); // автор блога
        $is_writer = cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id); // может ли пользователь писать в блог
            // если не его блог, пользователь не писатель и не админ, вне зависимости от авторства показываем 404
        if (!$myblog && !$is_writer && !cmsCore::c('user')->is_admin ) { cmsCore::error404(); }
        // проверяем является ли пользователь автором, если редактируем пост
        if (($inCore->do == 'editpost') && !cmsCore::c('user')->is_admin && $post['user_id'] != cmsCore::c('user')->id) { cmsCore::error404(); }

        //Если еще не было запроса на сохранение
        if (!cmsCore::inRequest('goadd')){
            cmsCore::c('page')->addPathway($blog['title'], cmsCore::m('blogs')->getBlogURL($blog['seolink']));

            //для нового поста
            if ($inCore->do == 'newpost'){
                if (IS_BILLING){ cmsBilling::checkBalance('blogs', 'add_post'); }

                cmsCore::c('page')->addPathway($_LANG['NEW_POST']);
                cmsCore::c('page')->setTitle($_LANG['NEW_POST']);

                $post = cmsUser::sessionGet('mod');
                if ($post){
                    cmsUser::sessionDel('mod');
                } else {
                    $post['cat_id'] = $cat_id;
                    $post['comments'] = 1;

                }
            }

            //для редактирования поста
            if ($inCore->do=='editpost'){
                cmsCore::c('page')->addPathway($post['title'], cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']));
                cmsCore::c('page')->addPathway($_LANG['EDIT_POST']);
                cmsCore::c('page')->setTitle($_LANG['EDIT_POST']);
            }

            cmsCore::c('page')->initAutocomplete();
            $autocomplete_js = cmsCore::c('page')->getAutocompleteJS('tagsearch', 'tags');

            //получаем рубрики блога
            $cat_list = cmsCore::getListItems('cms_blog_cats', $post['cat_id'], 'id', 'ASC', "blog_id = '{$blog['id']}'");

            //получаем код панелей bbcode и смайлов
            $bb_toolbar = cmsPage::getBBCodeToolbar('message',cmsCore::m('blogs')->config['img_on'], 'blogs', 'blog_post', $post_id);
            $smilies    = cmsPage::getSmilesPanel('message');

            $inCore->initAutoGrowText('#message');

            //показываем форму
            cmsPage::initTemplate('components', 'com_blog_edit_post')->
                assign('blog', $blog)->
                assign('pagetitle', ($inCore->do=='editpost' ? $_LANG['EDIT_POST'] : $_LANG['NEW_POST']))->
                assign('mod', $post)->
                assign('cat_list', $cat_list)->
                assign('bb_toolbar', $bb_toolbar)->
                assign('smilies', $smilies)->
                assign('is_admin', cmsCore::c('user')->is_admin)->
                assign('cfg', cmsCore::m('blogs')->config)->
                assign('myblog', $myblog)->
                assign('user_can_iscomments', cmsUser::isUserCan('comments/iscomments'))->
                assign('autocomplete_js', $autocomplete_js)->
                display();
        }

        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            $errors = false;

            //Получаем параметры
            $mod['title']    = cmsCore::request('title', 'str');
            $mod['content']  = cmsCore::request('content', 'html');
            $mod['feel']     = cmsCore::request('feel', 'str', '');
            $mod['music']    = cmsCore::request('music', 'str', '');
            $mod['cat_id']   = cmsCore::request('cat_id', 'int');
            $mod['allow_who']= cmsCore::request('allow_who', 'str', $blog['allow_who']);
            $mod['tags']     = cmsCore::request('tags', 'str', '');
            $mod['comments'] = cmsCore::request('comments', 'int', 1);
            
            if (cmsCore::m('blogs')->config['seo_user_access'] || cmsCore::c('user')->is_admin) {
                $mod['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
                $mod['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
                $mod['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
            }
            
            $mod['published']= ($myblog || !$blog['premod']) ? 1 : 0;
            $mod['blog_id']  = $blog['id'];

            //Проверяем их
            if (mb_strlen($mod['title'])<2) {  cmsCore::addSessionMessage($_LANG['POST_ERR_TITLE'], 'error'); $errors = true; }
            if (mb_strlen($mod['content'])<5) { cmsCore::addSessionMessage($_LANG['POST_ERR_TEXT'], 'error'); $errors = true; }

            // Если есть ошибки, возвращаемся назад
            if($errors){
                cmsUser::sessionPut('mod', $mod);
                cmsCore::redirectBack();
            }

            //Если нет ошибок
            //добавляем новый пост...
            if ($inCore->do=='newpost'){

                if (IS_BILLING){ cmsBilling::process('blogs', 'add_post'); }

                $mod['pubdate'] = date( 'Y-m-d H:i:s');
                $mod['user_id'] = cmsCore::c('user')->id;

                // добавляем пост, получая его id и seolink
                $added = cmsCore::c('blog')->addPost($mod);
    $mod = array_merge($mod, $added);

                if ($mod['published']) {
                    $mod['seolink'] = cmsCore::m('blogs')->getPostURL($blog['seolink'], $mod['seolink']);
                    
                    if ($blog['allow_who'] != 'nobody' && $mod['allow_who'] != 'nobody') {
                        cmsCore::callEvent('ADD_POST_DONE', $mod);

                        cmsActions::log('add_post', array(
                                'object' => $mod['title'],
                                'object_url' => $mod['seolink'],
                                'object_id' => $mod['id'],
                                'target' => $blog['title'],
                                'target_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink']),
                                'target_id' => $blog['id'],
                                'description' => '',
                                'is_friends_only' => (int)($blog['allow_who'] == 'friends' || $mod['allow_who'] == 'friends')
                        ));
                    }

                    cmsCore::addSessionMessage($_LANG['POST_CREATED'], 'success');

                    cmsCore::redirect($mod['seolink']);
                }

                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink(cmsCore::c('user')->login, cmsCore::c('user')->nickname), $_LANG['MSG_POST_SUBMIT']);
                    $message = str_replace('%post%', '<a href="'.cmsCore::m('blogs')->getPostURL($blog['seolink'], $added['seolink']).'">'.$mod['title'].'</a>', $message);
                    $message = str_replace('%blog%', '<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>', $message);

                    cmsUser::sendMessage(USER_UPDATER, $blog['user_id'], $message);

                    cmsCore::addSessionMessage($_LANG['POST_PREMODER_TEXT'], 'info');

                    cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($blog['seolink']));
                }
            }

            //...или сохраняем пост после редактирования
            if ($inCore->do=='editpost') {
                if (cmsCore::m('blogs')->config['update_date']){
                    $mod['pubdate'] = date( 'Y-m-d H:i:s');
                }

                $mod['edit_times'] = (int)$post['edit_times']+1;

                $new_post_seolink = cmsCore::c('blog')->updatePost($post['id'], $mod, cmsCore::m('blogs')->config['update_seo_link']);

                $post['seolink'] = is_string($new_post_seolink) ? $new_post_seolink : $post['seolink'];

                cmsActions::updateLog(
                    'add_post',
                    array(
                        'object' => $mod['title'],
                        'pubdate' => cmsCore::m('blogs')->config['update_date'] ? $mod['pubdate'] : $post['pubdate'],
                        'object_url' => cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink'])
                    ),
                    $post['id']
                );

                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink(cmsCore::c('user')->login, cmsCore::c('user')->nickname), $_LANG['MSG_POST_UPDATE']);
                    $message = str_replace('%post%', '<a href="'.cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']).'">'.$mod['title'].'</a>', $message);
                    $message = str_replace('%blog%', '<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>', $message);

                    cmsUser::sendMessage(USER_UPDATER, $blog['user_id'], $message);

                    cmsCore::addSessionMessage($_LANG['POST_PREMODER_TEXT'], 'info');
                } else {
                    cmsCore::addSessionMessage($_LANG['POST_UPDATED'], 'success');
                }

                cmsCore::redirect(cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']));
            }
        }
    }
    
    ////////// НОВАЯ РУБРИКА / РЕДАКТИРОВАНИЕ РУБРИКИ //////////////////////////
    if ($inCore->do == 'newcat' || $inCore->do == 'editcat'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        $cat = array();

        // Для редактирования сначала получаем рубрику
        if ($inCore->do == 'editcat'){
            $cat = cmsCore::c('blog')->getBlogCategory($cat_id);
            if (!$cat) { cmsCore::halt(); }
            $id = $cat['blog_id'];
        }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::halt(); }

        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }

        //Если нет запроса на сохранение
        if (!cmsCore::inRequest('goadd')){
            cmsPage::initTemplate('components', 'com_blog_edit_cat')->
                assign('mod', $cat)->
                assign('form_action', ($inCore->do=='newcat' ? '/blogs/'.$blog['id'].'/newcat.html' : '/blogs/editcat'.$cat['id'].'.html'))->
                display();

            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }

        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')){
            $new_cat['title']       = cmsCore::request('title', 'str', '');
            $new_cat['description'] = cmsCore::request('description', 'str', '');
            $new_cat['blog_id']     = $blog['id'];
            if (mb_strlen($new_cat['title'])<3) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CAT_ERR_TITLE'])); }

            if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

            //новая рубрика
            if ($inCore->do=='newcat'){
                    $cat['id'] = cmsCore::c('blog')->addBlogCategory($new_cat);
                    cmsCore::addSessionMessage($_LANG['CAT_IS_ADDED'], 'success');
            }
            //редактирование рубрики
            if ($inCore->do=='editcat'){
                    cmsCore::c('blog')->updateBlogCategory($cat['id'], $new_cat);
                    cmsCore::addSessionMessage($_LANG['CAT_IS_UPDATED'], 'success');
            }

            cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'], 1, $cat['id'])));
        }

    }
    
    ///////////////////////// УДАЛЕНИЕ РУБРИКИ /////////////////////////////////
    if ($inCore->do == 'delcat'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        $cat = cmsCore::c('blog')->getBlogCategory($cat_id);
        if (!$cat) { cmsCore::halt(); }

        $blog = cmsCore::c('blog')->getBlog($cat['blog_id']);
        if (!$blog) { cmsCore::halt(); }

        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin) { cmsCore::halt(); }

        if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

        cmsCore::c('blog')->deleteBlogCategory($cat['id']);

        cmsCore::addSessionMessage($_LANG['CAT_IS_DELETED'], 'success');

        cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'])));
    }
    
    ////////////////////////// ПРОСМОТР ПОСТА //////////////////////////////////
    if($inCore->do == 'post'){
        $post = cmsCore::c('blog')->getPost($seolink);
        if (!$post){ cmsCore::error404(); }

        $blog = cmsCore::c('blog')->getBlog($post['blog_id']);
        // Совместимость со старыми ссылками на клубные посты блога
        if (!$blog) {
            $blog_user_id = cmsCore::c('db')->get_field('cms_blogs', "id = '{$post['blog_id']}' AND owner = 'club'", 'user_id');
            if($blog_user_id){
                cmsCore::redirect('/clubs/'.$blog_user_id.'_'.$post['seolink'].'.html', '301');
            }
        }

        if (!$blog) { cmsCore::error404(); }

        // Проверяем сеолинк блога и делаем редирект если он изменился
        if($bloglink != $blog['seolink']) {
            cmsCore::redirect(cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']), '301');
        }

        // право просмотра блога
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'].'<br>'.$_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blogs');
        }

        // право просмотра самого поста
        if (!cmsUser::checkUserContentAccess($post['allow_who'], $post['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_POST'].'<br>'.$_LANG['CLOSED_POST_TEXT'], 'error');
            cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($blog['seolink']));
        }

        if (cmsCore::c('user')->id) {
            cmsCore::c('page')->addHeadJS('components/blogs/js/blog.js');
        }
        cmsCore::c('page')->addPathway($blog['title'], cmsCore::m('blogs')->getBlogURL($blog['seolink']));
        cmsCore::c('page')->addPathway($post['title']);
        
        cmsCore::c('page')->setTitle($post['pagetitle'] ? $post['pagetitle'] : $post['title']);
        cmsCore::c('page')->setDescription($post['meta_desc'] ? $post['meta_desc'] : crop($post['content_html']));
        cmsCore::c('page')->setKeywords($post['meta_keys'] ? $post['meta_keys'] : $post['title']);

        if ($post['cat_id']){
            $cat = cmsCore::c('blog')->getBlogCategory($post['cat_id']);
        }

        $post['tags'] = cmsTagBar('blogpost', $post['id']);

        $is_author = (cmsCore::c('user')->id && cmsCore::c('user')->id == $post['user_id']);
        
        // увеличиваем кол-во просмотров
        if (!$is_author) {
            cmsCore::c('db')->setFlag('cms_blog_posts', $post['id'], 'hits', $post['hits']+1);
        }

        cmsPage::initTemplate('components', 'com_blog_view_post')->
            assign('post', $post)->
            assign('blog', $blog)->assign('cat', $cat)->
            assign('is_author', $is_author)->
            assign('is_writer', cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id))->
            assign('myblog', (cmsCore::c('user')->id && cmsCore::c('user')->id == $blog['user_id']))->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('karma_form', cmsKarmaForm('blogpost', $post['id'], $post['rating'], $is_author))->
            assign('navigation', cmsCore::c('blog')->getPostNavigation($post['id'], $blog['id'], cmsCore::m('blogs'), $blog['seolink']))->
            display();

        if ($inCore->isComponentEnable('comments') && $post['comments']) {
            cmsCore::includeComments();
            comments('blog', $post['id'], array(), $is_author);
        }
    }

    ///////////////////////// УДАЛЕНИЕ ПОСТА ///////////////////////////////////
    if ($inCore->do == 'delpost'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }
        
        $post = cmsCore::c('blog')->getPost($post_id);
        if (!$post){ cmsCore::halt(); }

        $blog = cmsCore::c('blog')->getBlog($post['blog_id']);
        if (!$blog) { cmsCore::halt(); }

        $myblog = (cmsCore::c('user')->id == $blog['user_id']); // автор блога
        $is_writer = cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id);
        
        // если не его блог, пользователь не писатель и не админ
        if (!$myblog && !$is_writer && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }
        
        // проверяем является ли пользователь автором
        if (!cmsCore::c('user')->is_admin && !$myblog && $post['user_id'] != cmsCore::c('user')->id) { cmsCore::halt(); }

        if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

        cmsCore::c('blog')->deletePost($post['id']);

        if (cmsCore::c('user')->id != $post['user_id']){
            cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'].' <b>&laquo;'.$post['title'].'&raquo;</b> '.$_LANG['WAS_DELETED_FROM_BLOG'].' <b>&laquo;<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>&raquo;</b>');
        }

        cmsCore::addSessionMessage($_LANG['POST_IS_DELETED'], 'success');

        cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'])));
    }
    
    ///////////////////////// ПУБЛИКАЦИЯ ПОСТА /////////////////////////////////
    if ($inCore->do == 'publishpost'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        $post = cmsCore::c('blog')->getPost($post_id);
        if (!$post){ cmsCore::halt(); }

        $blog = cmsCore::c('blog')->getBlog($post['blog_id']);
        if (!$blog) { cmsCore::halt(); }

        // публикуют авторы блога и админы
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin) { cmsCore::halt(); }

        cmsCore::c('blog')->publishPost($post_id);

        $post['seolink'] = cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']);

        if ($blog['allow_who'] == 'all' && $post['allow_who'] == 'all') { cmsCore::callEvent('ADD_POST_DONE', $post); }

        if ($blog['allow_who'] != 'nobody' && $post['allow_who'] != 'nobody'){
            cmsActions::log('add_post', array(
                    'object' => $post['title'],
                    'user_id' => $post['user_id'],
                    'object_url' => $post['seolink'],
                    'object_id' => $post['id'],
                    'target' => $blog['title'],
                    'target_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink']),
                    'target_id' => $blog['id'],
                    'description' => '',
                    'is_friends_only' => (int)($blog['allow_who'] == 'friends' || $post['allow_who'] == 'friends')
            ));
        }

        cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'].' <b>&laquo;<a href="'.$post['seolink'].'">'.$post['title'].'</a>&raquo;</b> '.$_LANG['PUBLISHED_IN_BLOG'].' <b>&laquo;<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>&raquo;</b>');

        cmsCore::halt('ok');
    }

    ///////////////////////// УДАЛЕНИЕ БЛОГА ///////////////////////////////////
    if ($inCore->do == 'delblog'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::error404(); }

        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }

        if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

        cmsCore::c('blog')->deleteBlog($blog['id']);

        cmsCore::addSessionMessage($_LANG['BLOG_IS_DELETED'], 'success');

        cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/blogs'));
    }

    ////////// VIEW POPULAR POSTS //////////////////////////////////////////////
    if ($inCore->do=='best'){
        cmsCore::c('page')->setTitle($_LANG['POPULAR_IN_BLOGS']);
        cmsCore::c('page')->addPathway($_LANG['POPULAR_IN_BLOGS']);
        cmsCore::c('page')->setDescription($_LANG['POPULAR_IN_BLOGS']);

        // кроме админов в списке только с доступом для всех
        if(!cmsCore::c('user')->is_admin){
            cmsCore::c('blog')->whereOnlyPublic();
        }

        // ограничиваем по рейтингу если надо
        if(cmsCore::m('blogs')->config['list_min_rating']){
            cmsCore::c('blog')->ratingGreaterThan(cmsCore::m('blogs')->config['list_min_rating']);
        }

        // всего постов
        $total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin);

        //устанавливаем сортировку
        cmsCore::c('db')->orderBy('p.rating', 'DESC');

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage']);

        // сами посты
        $posts = cmsCore::c('blog')->getPosts(cmsCore::c('user')->is_admin, cmsCore::m('blogs'));
        if(!$posts && $page > 1){ cmsCore::error404(); }

        cmsPage::initTemplate('components', 'com_blog_view_posts')->
            assign('pagetitle', $_LANG['POPULAR_IN_BLOGS'])->
            assign('total', $total)->
            assign('ownertype', $ownertype)->
            assign('posts', $posts)->
            assign('pagination', cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], '/blogs/popular-%page%.html'))->
            assign('cfg', cmsCore::m('blogs')->config)->
            display();
    }

}
Beispiel #3
0
function faq(){

    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB   = cmsDatabase::getInstance();
	$inUser = cmsUser::getInstance();

    $model = new cms_model_faq();

    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) { $inCore->loadClass('billing'); }

	global $_LANG;

    $pagetitle = $inCore->getComponentTitle();

	$inPage->addPathway($pagetitle, '/faq');
	$inPage->setTitle($pagetitle);
	$inPage->setDescription($pagetitle);
    $inPage->addHeadJsLang(array('ERR_QUESTION'));

	$cfg = $inCore->loadComponentConfig('faq');

    if(!isset($cfg['guest_enabled'])) { $cfg['guest_enabled'] = 1; }
    if(!isset($cfg['user_link'])) { $cfg['user_link'] = 1; }
    if(!isset($cfg['publish'])) { $cfg['publish'] = 0; }
	if(!isset($cfg['is_comment'])) { $cfg['is_comment'] = 1; }

	$id = $inCore->request('id', 'int', 0);
	$do = $inCore->do;

///////////////////////////////////// VIEW CATEGORY ////////////////////////////////////////////////////////////////////////////////
if ($do=='view'){

	if($id>0){
		//CURRENT CATEGORY
		$sql = "SELECT *
				FROM cms_faq_cats
				WHERE id = '$id'
				ORDER BY title ASC LIMIT 1
				";

		$result = $inDB->query($sql) ;

		if (!$inDB->num_rows($result)) { cmsCore::error404(); }

		$cat = $inDB->fetch_assoc($result);

		//PAGE HEADING
		$pagetitle = $cat['title'];
		$inPage->setTitle($cat['title']);
		$inPage->addPathway($cat['title']);
		$inPage->setDescription($cat['title']);
	}

	//LIST OF SUBCATEGORIES
	$sql = "SELECT *
			FROM cms_faq_cats
			WHERE parent_id = $id AND id > 0 AND published = 1
			ORDER BY title ASC
			";

	$result = $inDB->query($sql) ;

	if ($inDB->num_rows($result)){
		$subcats = array();
		while($subcat = $inDB->fetch_assoc($result)){
			$subcats[] = $subcat;
		}
		$is_subcats = true;
	} else {
		$is_subcats = false;
	}

	//CURRENT CATEGORY CONTENT
	$perpage = 15;
	$page = $inCore->request('page', 'int', 1);
    $records = 0;

	if ($id > 0){
		$sql = "SELECT q.*, u.login, u.nickname
				FROM cms_faq_quests q
				LEFT JOIN cms_users u ON u.id = q.user_id
				WHERE q.category_id = $id AND q.published = 1
				ORDER BY q.pubdate DESC
				LIMIT ".(($page-1)*$perpage).", $perpage";
		$result_total = $inDB->query("SELECT id FROM cms_faq_quests WHERE category_id = $id AND published = 1") ;
		$records = $inDB->num_rows($result_total);
	} else {
		$sql = "SELECT q.*, c.title cat_title, c.id cid, u.login, u.nickname
				FROM cms_faq_quests q
				LEFT JOIN cms_faq_cats c ON c.id = q.category_id
				LEFT JOIN cms_users u ON u.id = q.user_id
				WHERE q.published = 1
				ORDER BY q.pubdate DESC
				LIMIT 15";
	}
	$result = $inDB->query($sql) ;

	if ($inDB->num_rows($result)){
		$quests = array();
		while($con = $inDB->fetch_assoc($result)){
			$con['pubdate'] = $inCore->dateFormat($con['pubdate'], true, false, false);
			$con['quest']	= nl2br($con['quest']);
			$quests[] = $con;
		}
		$is_quests = true;
	} else {
		$is_quests = false;
	}

	cmsPage::initTemplate('components', 'com_faq_view')->
            assign('pagetitle', $pagetitle)->
            assign('id', $id)->
            assign('subcats', $subcats)->
            assign('is_subcats', $is_subcats)->
            assign('quests', $quests)->
            assign('cfg', $cfg)->
            assign('is_quests', $is_quests)->
            assign('is_user', $inUser->id)->
            assign('pagebar', cmsPage::getPagebar($records, $page, $perpage, '/faq/%id%-%page%', array('id'=>$id)))->
            display();

}

///////////////////////////////////// READ QUESTION ////////////////////////////////////////////////////////////////////////////////
if ($do=='read'){
		$sql = "SELECT con.*,
				cat.title cat_title, cat.id cat_id, u.login, u.nickname
				FROM cms_faq_quests con
				LEFT JOIN cms_faq_cats cat ON cat.id = con.category_id
				LEFT JOIN cms_users u ON u.id = con.user_id
				WHERE con.id = $id LIMIT 1";

		$result = $inDB->query($sql);

		if ($inDB->num_rows($result)){

			$inDB->query("UPDATE cms_faq_quests SET hits = hits + 1 WHERE id = $id") ;

			$quest = $inDB->fetch_assoc($result);

			$quest['pubdate']    = $inCore->dateFormat($quest['pubdate'], true, false, false);
			$quest['answerdate'] = $inCore->dateFormat($quest['answerdate'], true, false, false);
			if (mb_strlen($quest['quest'])>40) { $shortquest = mb_substr($quest['quest'], 0, 40).'...'; }
			else { $shortquest = $quest['quest']; }
			$quest['quest']		 = nl2br($quest['quest']);

			$inPage->setTitle($shortquest);
			$inPage->setDescription($shortquest);

			$inPage->addPathway($quest['cat_title'], '/faq/'.$quest['cat_id']);
			$inPage->addPathway($shortquest);

			cmsPage::initTemplate('components', 'com_faq_read')->
                    assign('quest', $quest)->
                    assign('cfg', $cfg)->
                    assign('labels', array('comments' => $_LANG['ANSWERS'], 'add' => $_LANG['REPLY'], 'rss' => $_LANG['RSS_FEED'], 'not_comments' => $_LANG['NOT_ANSWERS']))->
                    assign('is_admin', $inUser->is_admin)->
                    display();

		} else { cmsCore::error404(); }
}
///////////////////////////////////// SEND QUEST ////////////////////////////////////////////////////////////////////////////////
if ($do=='sendquest'){

    if (!$inUser->id && !$cfg['guest_enabled']){ cmsCore::error404(); }

	$inPage->setTitle($_LANG['SET_QUESTION']);
	$inPage->addPathway($_LANG['SET_QUESTION']);

	$inPage->addHeadJS('components/faq/js/common.js');

    $error          = '';
    $captha_code    = $inCore->request('code', 'str', '');
    $message        = $inCore->request('message', 'str', '');
    $category_id    = $inCore->request('category_id', 'int', '');
    $published      = ($inUser->is_admin || $cfg['publish']) ? 1 : 0;
    $is_submit      = $inCore->inRequest('message');

    if ($is_submit && !$inUser->id && !cmsCore::checkCaptchaCode()) { $error = $_LANG['ERR_CAPTCHA']; }

	if (!$is_submit || $error){

        if (IS_BILLING && $inUser->id){ cmsBilling::checkBalance('faq', 'add_quest'); }

		cmsPage::initTemplate('components', 'com_faq_add')->
                assign('catslist', $inCore->getListItems('cms_faq_cats', $category_id))->
                assign('user_id', $inUser->id)->
                assign('message', htmlspecialchars($inCore->request('message', 'html', '')))->
                assign('error', $error)->
                display();

	} else {

        //SAVE QUESTION
		$sql = "INSERT INTO cms_faq_quests (category_id, pubdate, published, quest, answer, user_id, answeruser_id, answerdate, hits)
				VALUES ('$category_id', NOW(), '$published', '$message', '', '{$inUser->id}', 0, NOW(), 0)";
		$inDB->query($sql);

		$quest_id = $inDB->get_last_id('cms_faq_quests');

        if (IS_BILLING && $inUser->id){ cmsBilling::process('faq', 'add_quest'); }

		$inPage->setTitle($_LANG['QUESTION_SEND']);
		$inPage->addPathway($_LANG['QUESTION_SEND']);

        if (!$published){
			echo '<div class="con_heading">'.$_LANG['QUESTION_SEND'].'</div>';
            echo '<div style="margin-top:10px">'.$_LANG['QUESTION_PREMODER'].'</div>';
			echo '<div style="margin-top:10px"><a href="/faq">'.$_LANG['CONTINUE'].'</a></div>';
        } elseif ($published) {
			$category = $inDB->get_field('cms_faq_cats', "id={$category_id}", 'title');
            //регистрируем событие
            cmsActions::log('add_quest', array(
                'object' => $_LANG['QUESTION'],
                'object_url' => '/faq/quest'.$quest_id.'.html',
                'object_id' => $quest_id,
                'target' => $category,
                'target_url' => '/faq/'.$category_id,
                'target_id' => $category_id,
                'description' => strip_tags( mb_strlen(strip_tags($message))>100 ? mb_substr($message, 0, 100) : $message )
            ));
            $inCore->redirect('/faq/quest'.$quest_id.'.html');
		} else { $inCore->redirect('/faq/quest'.$quest_id.'.html'); }

	}
}

///////////////////////////////////// DELETE QUEST ////////////////////////////////////////////////////////////////////////////////

if ($do=='delquest'){

    $quest_id 	= $inCore->request('quest_id', 'int', 0);
    $user_id    = $inUser->id;

	$sql    = "SELECT con.id, con.quest, con.category_id
				FROM cms_faq_quests con
				WHERE con.id = '$quest_id' LIMIT 1";

	$result = $inDB->query($sql);
	$quest  = $inDB->fetch_assoc($result);

    if (!$user_id || !$quest_id || !$quest) { $inCore->redirectBack(); }

    if ( !$inCore->inRequest('confirm') ) {

        if (cmsUser::userIsAdmin($user_id)){
			$inPage->setTitle($_LANG['DEL_QUES']);
			$inPage->addPathway($_LANG['DEL_QUES']);
            $confirm['title'] = $_LANG['DELETE_QUES'];
            $confirm['text']  = $_LANG['YOU_REALY_DELETE_QUES'].':<br> "<a href="/faq/quest'.$quest['id'].'.html">'.$quest['quest'].'</a>"<br><br>';
			$confirm['action']                  = $_SERVER['REQUEST_URI'];
			$confirm['yes_button']              = array();
			$confirm['yes_button']['type']      = 'submit';
			$confirm['yes_button']['name']  	= 'confirm';
            cmsPage::initTemplate('components', 'action_confirm')->
                    assign('confirm', $confirm)->
                    display();
        } else {
            $inCore->redirectBack();
        }
	}

    if ( $inCore->inRequest('confirm') ){

        if (cmsUser::userIsAdmin($user_id)){

            $model->deleteQuest($quest_id);

        }
        $inCore->redirect('/faq/'.$quest['category_id']);
    }

}

} //function
Beispiel #4
0
    $is_karma_enabled = (($inUser->karma >= $club['blog_min_karma']) && $is_member) ? true : false;

	if(!$is_admin && !$is_moder && !$is_karma_enabled) { cmsCore::error404();}

    $inPage->addPathway($club['title'], '/clubs/'.$club['id']);

    // проверяем является ли пользователь автором, если редактируем пост
    if (($bdo == 'editpost') && !$is_admin && !$is_moder && $post['user_id'] != $inUser->id) { cmsCore::error404(); }

    //Если еще не было запроса на сохранение
    if (!cmsCore::inRequest('goadd')){

		//для нового поста
		if ($bdo=='newpost'){

			if (IS_BILLING){ cmsBilling::checkBalance('blogs', 'add_post'); }

			$inPage->addPathway($_LANG['NEW_POST']);
			$inPage->setTitle($_LANG['NEW_POST']);

			$post = cmsUser::sessionGet('mod');
			if ($post){
				cmsUser::sessionDel('mod');
			} else {
				$post['cat_id'] = $cat_id;
				$post['comments'] = 1;

			}

		}
Beispiel #5
0
function board() {
    $inCore = cmsCore::getInstance();

    global $_LANG;

    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) { cmsCore::loadClass('billing'); }

    $do = $inCore->do;

    $pagetitle = $inCore->getComponentTitle();
    $pagekeys = $pagedesc  = '';
    
    cmsCore::c('page')->setTitle($pagetitle);
    cmsCore::c('page')->addPathway($pagetitle, '/board');

/////////////////////////////// VIEW CATEGORY //////////////////////////////////
if ($do == 'view') {
    //Получаем текущую категорию
    $category = cmsCore::m('board')->getCategory(cmsCore::m('board')->category_id);
    if (!$category || (!$category['published'] && !cmsCore::c('user')->is_admin)) {
        cmsCore::error404();
    }

    if ($category['id'] != cmsCore::m('board')->root_cat['id']) {
        $pagetitle = $category['pagetitle'] ? $category['pagetitle'] : $category['title'];
        $pagekeys  = $category['meta_keys'];
        $pagedesc  = $category['meta_desc'];

        $category_path  = cmsCore::c('db')->getNsCategoryPath('cms_board_cats', $category['NSLeft'], $category['NSRight']);
        if ($category_path) {
            foreach($category_path as $pcat) {
                cmsCore::c('page')->addPathway($pcat['title'], '/board/'. $pcat['id']);
            }
        }
    } else {
        $category['title'] = $pagetitle = $inCore->menuTitle();
        $category['description'] = cmsCore::m('board')->config['root_description'];
        $pagekeys = cmsCore::m('board')->config['meta_keys'];
        $pagedesc = cmsCore::m('board')->config['meta_desc'];
    }

    // rss в адресной строке
    $rss_cat_id = $category['id'] == cmsCore::m('board')->root_cat['id'] ? 'all' : $category['id'];
    cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'. $_LANG['BOARD'] .'" href="'. HOST .'/rss/board/'. $rss_cat_id .'/feed.rss">');

    //Формируем категории
    $cats = cmsCore::m('board')->getSubCats($category['id']);

    // Формируем список объявлений
    // Устанавливаем категорию
    if ($category['id'] != cmsCore::m('board')->root_cat['id']) {
        cmsCore::m('board')->whereThisAndNestedCats($category['NSLeft'], $category['NSRight']);
    }

    //Город
    if (cmsCore::m('board')->city) {
        cmsCore::m('board')->whereCityIs(cmsCore::m('board')->city);
        $pagetitle .= ' :: '. cmsCore::m('board')->city;
    }

    // Типы объявлений
    if (cmsCore::m('board')->obtype && mb_stristr(icms_ucfirst($category['obtypes']), cmsCore::m('board')->obtype)) {
        cmsCore::m('board')->whereTypeIs(cmsCore::m('board')->obtype);
        $pagetitle .= ' :: '. cmsCore::m('board')->obtype;
    }

    // модератор или админ
    $is_moder = cmsCore::c('user')->is_admin || cmsCore::m('board')->is_moderator_by_group;

    // Общее количество объявлений по заданным выше условиям
    $total = cmsCore::m('board')->getAdvertsCount($is_moder, true);

    //устанавливаем сортировку
    $orderby = cmsCore::m('board')->getOrder('orderby', $category['orderby']);
    $orderto = cmsCore::m('board')->getOrder('orderto', $category['orderto']);
    cmsCore::c('db')->orderBy('is_vip DESC, '. $orderby, $orderto);

    //устанавливаем номер текущей страницы и кол-во объявлений на странице
    cmsCore::c('db')->limitPage(cmsCore::m('board')->page, $category['perpage']);

    // Получаем объявления
    $items = cmsCore::m('board')->getAdverts($is_moder, true, false, true);
    // Если объявлений на странице большей чем 1 нет, 404
    if (!$items && cmsCore::m('board')->page > 1) { cmsCore::error404(); }

    // если не указаны ключевые слова, формируем их из названий рубрик и типов 
    if (!$pagekeys && $cats) { 
        foreach($cats as $c) { 
            $keys[] = $c['title']; 
            foreach (explode("\n", $c['obtypes']) as $obtype) {
                $keys[] = trim($obtype);
            }
        }

        $pagekeys = implode(',', $keys);
    } else if(!$cats) {
        $pagekeys = $category['title'];
    }

    // если не указано описание, формируем из текущих объявлений
    if (!$pagedesc && $items) {
        foreach ($items as $i) {
            $desc[] = $i['title'];
        }

        $pagedesc = implode('. ', $desc);
    } else if(!$items && $category['description']) {
        $pagedesc = crop($category['description']);
    }

    // Проставляем заголовки страницы и описание согласно выборки
    cmsCore::c('page')->setDescription(crop($pagedesc));
    cmsCore::c('page')->setKeywords($pagekeys);
    cmsCore::c('page')->setTitle($pagetitle);

    // Отдаем в шаблон категории
    cmsPage::initTemplate('components', 'com_board_cats')->
        assign('cats', $cats)->
        assign('category', $category)->
        assign('root_id', cmsCore::m('board')->root_cat['id'])->
        assign('is_user', cmsCore::c('user')->id)->
        assign('maxcols', cmsCore::m('board')->config['maxcols'])->
        display();

    $pagebar = cmsPage::getPagebar($total, cmsCore::m('board')->page, $category['perpage'], '/board/%catid%-%page%', array('catid'=>$category['id']));
    $order_form = $category['orderform'] ? cmsCore::m('board')->orderForm($orderby, $orderto, $category) : '';

    // Отдаем в шаблон объявления
    cmsPage::initTemplate('components', 'com_board_items')->
        assign('order_form', $order_form)->
        assign('cfg', cmsCore::m('board')->config)->
        assign('root_id', cmsCore::m('board')->root_cat['id'])->
        assign('items', $items)->
        assign('cat', $category)->
        assign('maxcols', $category['maxcols'])->
        assign('colwidth', round(100/$category['maxcols']))->
        assign('pagebar', $pagebar)->
        display();
}

/////////////////////////////// VIEW USER ADV //////////////////////////////////
if ($do == 'by_user') {
    // логин пользователя
    $login = cmsCore::request('login', 'str', cmsCore::c('user')->login);

    // получаем данные пользователя
    $user = cmsUser::getShortUserData($login);
    if (!$user) { cmsCore::error404(); }

    $myprofile = cmsCore::m('board')->checkAccess($user['id']);

    cmsCore::c('page')->addPathway($user['nickname']);
    cmsCore::c('page')->setTitle($_LANG['BOARD'] .' - '. $user['nickname']);
    cmsCore::c('page')->setDescription($_LANG['BOARD'] .' - '. $user['nickname']);

    // Формируем список объявлений
    cmsCore::m('board')->whereUserIs($user['id']);

    // Общее количество объявлений по заданным выше условиям
    $total = cmsCore::m('board')->getAdvertsCount($myprofile);

    //устанавливаем сортировку
    cmsCore::c('db')->orderBy('pubdate', 'DESC');

    //устанавливаем номер текущей страницы и кол-во объявлений на странице
    cmsCore::c('db')->limitPage(cmsCore::m('board')->page, 15);

    // Получаем объявления
    $items = cmsCore::m('board')->getAdverts($myprofile, true, false, true);
    // Если объявлений на странице большей чем 1 нет, 404
    if(!$items && cmsCore::m('board')->page > 1){ cmsCore::error404(); }

    // Пагинация
    $pagebar = cmsPage::getPagebar($total, cmsCore::m('board')->page, 15, '/board/by_user_'.$login.'/page-%page%');

    // Показываем даты
    $category['showdate'] = 1;

    cmsPage::initTemplate('components', 'com_board_items')->
        assign('cfg', cmsCore::m('board')->config)->
        assign('page_title', $_LANG['BOARD'].' - '.$user['nickname'])->
        assign('root_id', cmsCore::m('board')->root_cat['id'])->
        assign('items', $items)->
        assign('cat', $category)->
        assign('maxcols', 1)->
        assign('colwidth', 100)->
        assign('pagebar', $pagebar)->
        display();
}

/////////////////////////////// VIEW ITEM //////////////////////////////////////
if ($do == 'read') {
    // получаем объявление
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    if (!$item) { cmsCore::error404(); }

    // неопубликованные показываем админам, модераторам и автору
    if (!$item['published'] && !$item['moderator']) { cmsCore::error404(); }

    // для неопубликованного показываем инфо: просрочено/на модерации
    if (!$item['published']) {
        $info_text = $item['is_overdue'] ? $_LANG['ADV_IS_EXTEND'] : $_LANG['ADV_IS_MODER'];
        cmsCore::addSessionMessage($info_text, 'info');
    } else {
        // увеличиваем кол-во просмотров
        cmsCore::c('db')->setFlag('cms_board_items', cmsCore::m('board')->item_id, 'hits', $item['hits']+1);
    }

    // формируем заголовок и тело сообщения
    $item['title']   = $item['obtype'].' '.$item['title'];
    $item['content'] = nl2br($item['content']);
    $item['content'] = cmsCore::m('board')->config['auto_link'] ? $inCore->parseSmiles($item['content']) : $item['content'];

    $category_path = cmsCore::c('db')->getNsCategoryPath('cms_board_cats', $item['NSLeft'], $item['NSRight']);
    if ($category_path) {
        foreach ($category_path as $pcat) {
            cmsCore::c('page')->addPathway($pcat['title'], '/board/'.$pcat['id']);
        }
    }
    cmsCore::c('page')->addPathway($item['title']);

    $pagetitle = $item['pagetitle'] ? $item['pagetitle'] : $item['title'];
    $pagekeys  = $item['meta_keys'] ? $item['meta_keys'] : $item['title'];
    $pagedesc  = $item['meta_desc'] ? $item['meta_desc'] : $item['content'];

    cmsCore::c('page')->setTitle($pagetitle);
    cmsCore::c('page')->setDescription(crop($pagedesc));
    cmsCore::c('page')->setKeywords($pagekeys);

    cmsPage::initTemplate('components', 'com_board_item')->
        assign('item', $item)->
        assign('cfg', cmsCore::m('board')->config)->
        assign('user_id', cmsCore::c('user')->id)->
        assign('is_admin', cmsCore::c('user')->is_admin)->
        assign('formsdata', cmsForm::getFieldsValues($item['form_id'], $item['form_array']))->
        assign('is_moder', cmsCore::m('board')->is_moderator_by_group)->
        display();
}

/////////////////////////////// NEW BOARD ITEM /////////////////////////////////
if ($do == 'additem') {
    // Получаем категории, в которые может загружать пользователь
    $catslist = cmsCore::m('board')->getPublicCats(cmsCore::m('board')->category_id);
    if (!$catslist) {
        cmsCore::addSessionMessage($_LANG['YOU_CANT_ADD_ADV_ANY'], 'error');
        $inCore->redirect('/board');
    }

    $cat['is_photos'] = 1;
    $formsdata = array();
    if (cmsCore::m('board')->category_id && cmsCore::m('board')->category_id != cmsCore::m('board')->root_cat['id']) {
        $cat = cmsCore::m('board')->getCategory(cmsCore::m('board')->category_id);
        $formsdata = cmsForm::getFieldsHtml($cat['form_id']);
    }

    cmsCore::c('page')->addPathway($_LANG['ADD_ADV']);

    if ( !cmsCore::inRequest('submit') ) {
        if (IS_BILLING) { cmsBilling::checkBalance('board', 'add_item'); }
        cmsCore::c('page')->setTitle($_LANG['ADD_ADV']);

        $item = cmsUser::sessionGet('item');
        if ($item) { cmsUser::sessionDel('item'); }

        $item['city'] = !empty($item['city']) ? $item['city'] : cmsCore::c('user')->city;

        cmsPage::initTemplate('components', 'com_board_edit')->
            assign('action', "/board/add.html")->
            assign('form_do', 'add')->
            assign('cfg', cmsCore::m('board')->config)->
            assign('cat', $cat)->
            assign('item', $item)->
            assign('pagetitle', $_LANG['ADD_ADV'])->
            assign('formsdata', $formsdata)->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('is_user', cmsCore::c('user')->id)->
            assign('catslist', $catslist)->
            assign('is_billing', IS_BILLING)->assign('balance', cmsCore::c('user')->balance)->
            display();

        cmsUser::sessionClearAll();

        return;
    }

    if ( cmsCore::inRequest('submit') ) {
        // проверяем на заполненость скрытое поле
        $title_fake = cmsCore::request('title_fake', 'str', '');
        // если оно заполнено, считаем что это бот, 404
        if ($title_fake) { cmsCore::error404(); }

        $errors = false;

        // проверяем наличие категории
        if (!$cat['id']) {
            cmsCore::addSessionMessage($_LANG['NEED_CAT_ADV'], 'error');
            $errors = true;
        }

        // Проверяем количество добавленных за сутки
        if (!cmsCore::m('board')->checkLoadedByUser24h($cat)){
            cmsCore::addSessionMessage($_LANG['MAX_VALUE_OF_ADD_ADV'], 'error');
            $errors = true;
        }
        // Можем ли добавлять в эту рубрику
        if (!cmsCore::m('board')->checkAdd($cat)){
            cmsCore::addSessionMessage($_LANG['YOU_CANT_ADD_ADV'], 'error');
            $errors = true;
        }

        // входные данные
        $obtype     = icms_ucfirst(cmsCore::request('obtype', 'str', ''));
        $title      = trim(str_ireplace($obtype, '', cmsCore::request('title', 'str', '')));
        $content    = cmsCore::request('content', 'str', '');
        $city       = cmsCore::request('city', 'str', '');

        if ((cmsCore::m('board')->config['seo_user_access'] && cmsCore::c('user')->id) || cmsCore::c('user')->is_admin) {
            $pagetitle = cmsCore::request('pagetitle', 'str', '');
            $meta_keys = cmsCore::request('meta_keys', 'str', '');
            $meta_desc = cmsCore::request('meta_desc', 'str', '');
        } else {
            $pagetitle = $meta_keys = $meta_desc = '';
        }

        $form_input = cmsForm::getFieldsInputValues($cat['form_id']);
        $formsdata  = cmsCore::c('db')->escape_string(cmsCore::arrayToYaml($form_input['values']));

        $vipdays    = cmsCore::request('vipdays', 'int', 0);

        $published  = cmsCore::m('board')->checkPublished($cat);

        if (cmsCore::m('board')->config['srok']){  $pubdays = (cmsCore::request('pubdays', 'int') <= 50) ? cmsCore::request('pubdays', 'int') : 50; }
        if (!cmsCore::m('board')->config['srok']){ $pubdays = isset(cmsCore::m('board')->config['pubdays']) ? cmsCore::m('board')->config['pubdays'] : 14; }

        // Проверяем значения
        if (!$title) {
            cmsCore::addSessionMessage($_LANG['NEED_TITLE'], 'error');
            $errors = true;
        }
        if (!$content) {
            cmsCore::addSessionMessage($_LANG['NEED_TEXT_ADV'], 'error');
            $errors = true;
        }
        if (!$city) {
            cmsCore::addSessionMessage($_LANG['NEED_CITY'], 'error');
            $errors = true;
        }
        if (!cmsCore::c('user')->id && !cmsCore::checkCaptchaCode()) {
            cmsCore::addSessionMessage($_LANG['ERR_CAPTCHA'], 'error');
            $errors = true;
        }

        // Проверяем значения формы
        foreach ($form_input['errors'] as $field_error) {
            if ($field_error) {
                cmsCore::addSessionMessage($field_error, 'error');
                $errors = true;
            }
        }

        if ($errors) {
            $item['content'] = htmlspecialchars(stripslashes($_REQUEST['content']));
            $item['city']    = stripslashes($city);
            $item['title']   = stripslashes($title);
            $item['obtype']  = $obtype;
            cmsUser::sessionPut('item', $item);
            cmsCore::redirect('/board/'. cmsCore::m('board')->category_id .'/add.html');
        }

        if ($cat['is_photos']) {
            // Загружаем фото
            $file = cmsCore::m('board')->uploadPhoto('', $cat);
        } else {
            $file['filename'] = '';
            cmsCore::addSessionMessage($_LANG['INFO_CAT_NO_PHOTO'], 'info');
        }
        
        
        $add = array(
            'category_id' => cmsCore::m('board')->category_id,
            'user_id'     => cmsCore::c('user')->id,
            'obtype'      => $obtype,
            'title'       => $title,
            'content'     => $content,
            'formsdata'   => $formsdata,
            'city'        => $city,
            'pubdays'     => $pubdays,
            'published'   => $published,
            'pagetitle'   => $pagetitle,
            'meta_keys'   => $meta_keys,
            'meta_desc'   => $meta_desc,
            'file'        => $file['filename']
        );
        $add['id'] = cmsCore::m('board')->addRecord($add);

        if (cmsCore::c('user')->is_admin && $vipdays) {
            cmsCore::m('board')->setVip($add['id'], $vipdays);
        }

        if (IS_BILLING) {
            cmsBilling::process('board', 'add_item');
            if (cmsCore::m('board')->config['vip_enabled'] && $vipdays && cmsCore::m('board')->config['vip_day_cost']) {
                if ($vipdays > cmsCore::m('board')->config['vip_max_days']) {
                    $vipdays = cmsCore::m('board')->config['vip_max_days'];
                }

                $summ = $vipdays * cmsCore::m('board')->config['vip_day_cost'];

                if (cmsCore::c('user')->balance >= $summ) {
                    cmsBilling::pay(cmsCore::c('user')->id, $summ, $_LANG['VIP_ITEM']);
                    cmsCore::m('board')->setVip($add['id'], $vipdays);
                }
            }
        }

        cmsUser::sessionClearAll();

        if ($published) {
            //регистрируем событие
            cmsActions::log('add_board', array(
                'object'      => $obtype .' '. $title,
                'object_url'  => '/board/read'. $add['id'] .'.html',
                'object_id'   => $add['id'],
                'target'      => $cat['title'],
                'target_url'  => '/board/'. $cat['id'],
                'target_id'   => $cat['id'],
                'description' => ''
            ));
            cmsCore::addSessionMessage($_LANG['ADV_IS_ADDED'], 'success');
            cmsCore::callEvent('ADD_BOARD_DONE', $add);
            cmsCore::redirect('/board/read'. $add['id'] .'.html');
        }

        if (!$published) {
            $link = '<a href="/board/read'. $add['id'] .'.html">'. $obtype .' '. $title .'</a>';
            if (cmsCore::c('user')->id) {
                $user = '******'. cmsUser::getProfileURL(cmsCore::c('user')->login) .'">'. cmsCore::c('user')->nickname .'</a>';
            } else {
                $user = $_LANG['BOARD_GUEST'] .', ip: '. cmsCore::c('user')->ip;
            }
            $message = str_replace('%user%', $user, $_LANG['MSG_ADV_SUBMIT']);
            $message = str_replace('%link%', $link, $message);
            cmsUser::sendMessage(USER_UPDATER, 1, $message);

            cmsCore::addSessionMessage($_LANG['ADV_IS_ADDED'] .'<br>'. $_LANG['ADV_PREMODER_TEXT'], 'success');
            cmsCore::redirect('/board/'.cmsCore::m('board')->category_id);
        }
    }
}

/////////////////////////////// EDIT BOARD ITEM ////////////////////////////////
if ($do == 'edititem') {
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    $cat  = cmsCore::m('board')->getCategory($item['category_id']);

    if (!$cat || !$item) { cmsCore::error404(); }

    cmsCore::c('page')->setTitle($_LANG['EDIT_ADV']);
    cmsCore::c('page')->addPathway($item['category'], '/board/'. $item['cat_id']);
    cmsCore::c('page')->addPathway($_LANG['EDIT_ADV']);

    if (!$item['moderator']) {
        cmsCore::addSessionMessage($_LANG['YOU_HAVENT_ACCESS'], 'error');
        cmsCore::redirect('/board/read'. $item['id'] .'.html');
    }

    $errors = false;

    if (!cmsCore::inRequest('submit')) {
        cmsPage::initTemplate('components', 'com_board_edit')->
            assign('action', "/board/edit{$item['id']}.html")->
            assign('form_do', 'edit')->
            assign('cfg', cmsCore::m('board')->config)->
            assign('cat', $cat)->
            assign('item', $item)->
            assign('pagetitle', $_LANG['EDIT_ADV'])->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('catslist', cmsCore::m('board')->getPublicCats($item['category_id'], true))->
            assign('formsdata', cmsForm::getFieldsHtml($cat['form_id'], $item['form_array']))->
            assign('is_user', cmsCore::c('user')->id)->
            assign('is_billing', IS_BILLING)->assign('balance', cmsCore::c('user')->balance)->
            display();

        cmsUser::sessionClearAll();
    }

    if (cmsCore::inRequest('submit')) {
        $new_cat_id = cmsCore::request('category_id', 'int', 0);
        if ($new_cat_id) {
            $item['category_id'] = $new_cat_id;
        }

        $form_input = cmsForm::getFieldsInputValues($cat['form_id']);
        $formsdata  = cmsCore::c('db')->escape_string(cmsCore::arrayToYaml($form_input['values']));

        if ($item['is_overdue'] && !$item['published']) {
            if (cmsCore::m('board')->config['srok']) {
                $pubdays = (cmsCore::request('pubdays', 'int') <= 50) ? cmsCore::request('pubdays', 'int') : 50;
            }
            if (!cmsCore::m('board')->config['srok']) {
                $pubdays = isset(cmsCore::m('board')->config['pubdays']) ? cmsCore::m('board')->config['pubdays'] : 14;
            }

            $pubdate = date('Y-m-d H:i:s');
        } else {
            $pubdays = $item['pubdays'];
            $pubdate = $item['fpubdate'];
        }

        $update['obtype']      = icms_ucfirst(cmsCore::request('obtype', 'str'));
        $update['title']       = trim(str_ireplace($update['obtype'], '', cmsCore::request('title', 'str', '')));
        $update['category_id'] = $item['category_id'];
        $update['content']     = cmsCore::request('content', 'str', '');
        $update['formsdata']   = $formsdata;
        $update['city']        = cmsCore::request('city', 'str', '');
        $update['pubdate']     = $pubdate;
        $update['pubdays']     = $pubdays;
        $update['published']   = cmsCore::m('board')->checkPublished($cat, true);
        if ((cmsCore::m('board')->config['seo_user_access'] && cmsCore::c('user')->id) || cmsCore::c('user')->is_admin) {
            $update['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
            $update['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
            $update['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
        }

        if (!$update['title']) {
            cmsCore::addSessionMessage($_LANG['NEED_TITLE'], 'error');
            $errors = true;
        }
        if (!$update['content']) {
            cmsCore::addSessionMessage($_LANG['NEED_TEXT_ADV'], 'error');
            $errors = true;
        }
        if (!$update['city']) {
            cmsCore::addSessionMessage($_LANG['NEED_CITY'], 'error');
            $errors = true;
        }

        // Проверяем значения формы
        foreach ($form_input['errors'] as $field_error) {
            if ($field_error) {
                cmsCore::addSessionMessage($field_error, 'error');
                $errors = true;
            }
        }

        if ($errors) {
            $inCore->redirect('/board/edit'. $item['id'] .'.html');
        }

        if ($cat['is_photos']) {
            // Загружаем фото
            $file = cmsCore::m('board')->uploadPhoto($item['file'], $cat);
        }

        $update['file'] = $file['filename'] ? $file['filename'] : $item['file'];

        // обновляем объявление
        cmsCore::m('board')->updateRecord($item['id'], $update);
        // обновляем запись в ленте активности
        cmsActions::updateLog('add_board', array('object' => $update['obtype'] .' '. $update['title']), $item['id']);
        $vipdays = cmsCore::request('vipdays', 'int', 0);

        if (cmsCore::c('user')->is_admin) {
            if ($vipdays > 0) {
                cmsCore::m('board')->setVip($item['id'], $vipdays);
            }
            if ($vipdays == -1) {
                cmsCore::m('board')->deleteVip($item['id']);
            }
        }

        if (IS_BILLING) {
            if (cmsCore::m('board')->config['vip_enabled'] && cmsCore::m('board')->config['vip_prolong'] && $vipdays && cmsCore::m('board')->config['vip_day_cost']) {
                if ($vipdays > cmsCore::m('board')->config['vip_max_days']) {
                    $vipdays = cmsCore::m('board')->config['vip_max_days'];
                }

                $summ = $vipdays * cmsCore::m('board')->config['vip_day_cost'];

                if (cmsCore::c('user')->balance >= $summ) {
                    cmsBilling::pay(cmsCore::c('user')->id, $summ, $_LANG['VIP_ITEM']);
                    cmsCore::m('board')->setVip($item['id'], $vipdays);
                }
            }
        }

        cmsUser::sessionClearAll();

        if (!$update['published']) {
            $link = '<a href="/board/read'. $item['id'] .'.html">'. $update['obtype'] .' '. $update['title'] .'</a>';
            $user = '******'. cmsUser::getProfileURL(cmsCore::c('user')->login) .'">'. cmsCore::c('user')->nickname .'</a>';

            $message = str_replace(array('%link%','%user%'), array($link,$user), $_LANG['MSG_ADV_EDITED']);
            cmsUser::sendMessage(USER_UPDATER, 1, $message);

            cmsCore::addSessionMessage($_LANG['ADV_EDIT_PREMODER_TEXT'], 'info');
        }

        cmsCore::addSessionMessage($_LANG['ADV_MODIFIED'], 'success');
        cmsCore::redirect('/board/read'. $item['id'] .'.html');
    }
}

///////////////////////// PUBLISH BOARD ITEM ///////////////////////////////////
if ($do == 'publish') {
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    if (!$item) { cmsCore::error404(); }

    // если уже опубликовано, 404
    if ($item['published']) { cmsCore::error404(); }

    // публиковать могут админы и модераторы доски
    if (!cmsCore::c('user')->is_admin && !cmsCore::m('board')->is_moderator_by_group) {
        cmsCore::error404();
    }

    // публикуем
    cmsCore::c('db')->setFlag('cms_board_items', cmsCore::m('board')->item_id, 'published', 1);

    cmsCore::callEvent('ADD_BOARD_DONE', $item);

    if ($item['user_id']) {
        //регистрируем событие
        cmsActions::log('add_board', array(
            'object'      => $item['obtype'] .' '. $item['title'],
            'user_id'     => $item['user_id'],
            'object_url'  => '/board/read'. $item['id'] .'.html',
            'object_id'   => $item['id'],
            'target'      => $item['category'],
            'target_url'  => '/board/'. $item['cat_id'],
            'target_id'   => $item['cat_id'],
            'description' => ''
        ));

        $link = '<a href="/board/read'. $item['id'] .'.html">'. $item['obtype'] .' '. $item['title'] .'</a>';
        $message = str_replace('%link%', $link, $_LANG['MSG_ADV_ACCEPTED']);
        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);
    }

    cmsCore::addSessionMessage($_LANG['ADV_IS_ACCEPTED'], 'success');

    cmsCore::redirect('/board/read'. $item['id'] .'.html');
}

/////////////////////////////// DELETE BOARD ITEM //////////////////////////////
if ($do == 'delete') {
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    if (!$item) { cmsCore::error404(); }

    if (!$item['moderator']) {
        cmsCore::addSessionMessage($_LANG['YOU_HAVENT_ACCESS'], 'error');
        cmsCore::redirect('/board/'. $item['cat_id']);
    }

    if (!cmsCore::inRequest('godelete')) {
        cmsCore::c('page')->setTitle($_LANG['DELETE_ADV']);
        cmsCore::c('page')->addPathway($item['category'], '/board/'. $item['cat_id']);
        cmsCore::c('page')->addPathway($_LANG['DELETE_ADV']);

        $confirm['title']               = $_LANG['DELETING_ADV'];
        $confirm['text']                = $_LANG['YOU_SURE_DELETE_ADV'] .' "'. $item['title'] .'"?';
        $confirm['action']              = $_SERVER['REQUEST_URI'];
        $confirm['yes_button']['name']  = 'godelete';

        cmsPage::initTemplate('components', 'action_confirm')->
            assign('confirm', $confirm)->
            display();
    }

    if (cmsCore::inRequest('godelete')) {
        cmsCore::m('board')->deleteRecord(cmsCore::m('board')->item_id);
        cmsCore::addSessionMessage($_LANG['ADV_IS_DELETED'], 'success');
        cmsCore::redirect('/board/'. $item['cat_id']);
    }
}
}
Beispiel #6
0
 $is_member = $model->checkUserRightsInClub('member');
 $is_karma_enabled = $inUser->karma >= $club['blog_min_karma'] && $is_member ? true : false;
 if (!$is_admin && !$is_moder && !$is_karma_enabled) {
     cmsCore::error404();
 }
 $inPage->addPathway($club['title'], '/clubs/' . $club['id']);
 // проверяем является ли пользователь автором, если редактируем пост
 if ($bdo == 'editpost' && !$is_admin && !$is_moder && $post['user_id'] != $inUser->id) {
     cmsCore::error404();
 }
 //Если еще не было запроса на сохранение
 if (!cmsCore::inRequest('goadd')) {
     //для нового поста
     if ($bdo == 'newpost') {
         if (IS_BILLING) {
             cmsBilling::checkBalance('blogs', 'add_post');
         }
         $inPage->addPathway($_LANG['NEW_POST']);
         $inPage->setTitle($_LANG['NEW_POST']);
         $post = cmsUser::sessionGet('mod');
         if ($post) {
             cmsUser::sessionDel('mod');
         } else {
             $post['cat_id'] = $cat_id;
             $post['comments'] = 1;
         }
     }
     //для редактирования поста
     if ($bdo == 'editpost') {
         $inPage->addPathway($post['title'], $model->getPostURL($club['id'], $post['seolink']));
         $inPage->addPathway($_LANG['EDIT_POST']);
Beispiel #7
0
function forum()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    $model = new cms_model_forum();
    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) {
        cmsCore::loadClass('billing');
    }
    global $_LANG;
    $pagetitle = $inCore->getComponentTitle();
    $inPage->addPathway($pagetitle, '/forum');
    $inPage->setTitle($pagetitle);
    $inPage->setDescription($model->config['meta_desc'] ? $model->config['meta_desc'] : $pagetitle);
    $inPage->setKeywords($model->config['meta_keys'] ? $model->config['meta_keys'] : $pagetitle);
    $id = cmsCore::request('id', 'int', 0);
    $do = $inCore->do;
    $page = cmsCore::request('page', 'int', 1);
    $inPage->addHeadJS('components/forum/js/common.js');
    $inPage->addHeadJsLang(array('CONFIRM_DELETE_POLL', 'CONFIRM_DEL_POST', 'CONFIRM_DEL_THREAD', 'MOVE_THREAD', 'MOVE_POST', 'RENAME_THREAD', 'CONFIRM_DELETE_FILE', 'SELECT_NEW_FILE_UPLOAD', 'SELECT_TEXT_QUOTE', 'CONFIRM_DELETE_ALL_USER_POSTS'));
    //============================================================================//
    //=============================== Список Форумов  ============================//
    //============================================================================//
    if ($do == 'view') {
        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . $_LANG['FORUMS'] . '" href="' . HOST . '/rss/forum/all/feed.rss">');
        $forums = $model->getForums();
        cmsPage::initTemplate('components', 'com_forum_list')->assign('pagetitle', $pagetitle)->assign('forums', $forums)->assign('forum', array())->assign('user_id', $inUser->id)->assign('cfg', $model->config)->display('com_forum_list.tpl');
    }
    //============================================================================//
    //================ Список тем форума + список подфорумов  ====================//
    //============================================================================//
    if ($do == 'forum') {
        $forum = $model->getForum($id);
        if (!$forum) {
            cmsCore::error404();
        }
        $forum = translations::process(cmsConfig::getConfig('lang'), 'forum_forums', $forum);
        $moderators = $model->getForumModerators($forum['moder_list']);
        // опции просмотра
        $order_by = cmsCore::getSearchVar('order_by', 'pubdate');
        $order_to = cmsCore::getSearchVar('order_to', 'desc');
        if (!in_array($order_by, array('pubdate', 'title', 'post_count', 'hits'))) {
            $order_by = 'pubdate';
        }
        if (!in_array($order_to, array('asc', 'desc'))) {
            $order_to = 'desc';
        }
        $daysprune = (int) cmsCore::getSearchVar('daysprune');
        if (!cmsCore::checkContentAccess($forum['access_list'])) {
            cmsPage::includeTemplateFile('special/accessdenied.php');
            return;
        }
        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . htmlspecialchars($forum['title']) . '" href="' . HOST . '/rss/forum/' . $forum['id'] . '/feed.rss">');
        $inPage->setTitle($forum['pagetitle'] ? $forum['pagetitle'] : $forum['title']);
        $inPage->setDescription($forum['meta_desc'] ? $forum['meta_desc'] : crop($forum['description'] ? $forum['description'] : $forum['title']));
        $inPage->setKeywords($forum['meta_keys'] ? $forum['meta_keys'] : $forum['title']);
        // Получаем дерево форумов
        $path_list = $inDB->getNsCategoryPath('cms_forums', $forum['NSLeft'], $forum['NSRight'], 'id, title, access_list, moder_list');
        // Строим глубиномер
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'forum_forums', $path_list);
            foreach ($path_list as $pcat) {
                if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                    cmsPage::includeTemplateFile('special/accessdenied.php');
                    return;
                }
                $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']);
            }
        }
        // Получим подфорумы
        $model->whereNestedForum($forum['NSLeft'], $forum['NSRight']);
        $sub_forums = $model->getForums();
        cmsPage::initTemplate('components', 'com_forum_list')->assign('pagetitle', $forum['title'])->assign('forums', $sub_forums)->assign('forum', $forum)->assign('cfg', $model->config)->assign('user_id', $inUser->id)->display('com_forum_list.tpl');
        // Получим темы
        if ($daysprune) {
            $model->whereDayIntervalIs($daysprune);
        }
        $model->whereForumIs($forum['id']);
        $inDB->orderBy('t.pinned', 'DESC, t.' . $order_by . ' ' . $order_to);
        $inDB->limitPage($page, $model->config['pp_forum']);
        $threads = $model->getThreads();
        if (!$threads && $page > 1) {
            cmsCore::error404();
        }
        cmsPage::initTemplate('components', 'com_forum_view')->assign('threads', $threads)->assign('show_panel', true)->assign('order_by', $order_by)->assign('order_to', $order_to)->assign('daysprune', $daysprune)->assign('moderators', $moderators)->assign('pagination', cmsPage::getPagebar($forum['thread_count'], $page, $model->config['pp_forum'], '/forum/' . $forum['id'] . '-%page%'))->display('com_forum_view.tpl');
    }
    //============================================================================//
    //======================== Просмотр темы форума  =============================//
    //============================================================================//
    if ($do == 'thread') {
        $thread = $model->getThread($id);
        if (!$thread) {
            cmsCore::error404();
        }
        // Строим глубиномер
        $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list');
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'forum_forums', $path_list);
            foreach ($path_list as $pcat) {
                if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                    cmsPage::includeTemplateFile('special/accessdenied.php');
                    return;
                }
                $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']);
            }
            // Для последнего форума проверяем
            // не модератор ли текущий пользователь
            $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
        }
        $inPage->addPathway($thread['title'], '/forum/thread' . $thread['id'] . '.html');
        if (!$thread['is_mythread']) {
            $inDB->setFlag('cms_forum_threads', $thread['id'], 'hits', $thread['hits'] + 1);
        }
        // получаем посты
        $model->whereThreadIs($thread['id']);
        $inDB->orderBy('p.pinned', 'DESC, p.pubdate ASC');
        $inDB->limitPage($page, $model->config['pp_thread']);
        $posts = $model->getPosts();
        if (!$posts) {
            cmsCore::error404();
        }
        // SEO
        $inPage->setTitle($thread['title']);
        // meta description
        if (!$thread['description']) {
            $first_post = current($posts);
            $first_post_content = strip_tags($first_post['content_html']);
            if (mb_strlen($first_post_content) >= 100) {
                $inPage->setDescription(crop($first_post_content));
            } else {
                $inPage->setDescription($thread['title']);
            }
        } else {
            $inPage->setDescription(crop($thread['description']));
        }
        // meta keywords
        $all_post_content = '';
        foreach ($posts as $p) {
            $all_post_content .= ' ' . strip_tags($p['content_html']);
        }
        $meta_keys = cmsCore::getKeywords($all_post_content);
        $inPage->setKeywords($meta_keys ? $meta_keys : $thread['title']);
        cmsCore::initAutoGrowText('#message');
        cmsPage::initTemplate('components', 'com_forum_view_thread')->assign('forum', $pcat)->assign('forums', $model->getForums())->assign('is_subscribed', cmsUser::isSubscribed($inUser->id, 'forum', $thread['id']))->assign('thread', $thread)->assign('prev_thread', $inDB->get_fields('cms_forum_threads', "id < '{$thread['id']}' AND forum_id = '{$thread['forum_id']}'", 'id, title', 'id DESC'))->assign('next_thread', $inDB->get_fields('cms_forum_threads', "id > '{$thread['id']}' AND forum_id = '{$thread['forum_id']}'", 'id, title', 'id ASC'))->assign('posts', $posts)->assign('thread_poll', $model->getThreadPoll($thread['id']))->assign('page', $page)->assign('num', ($page - 1) * $model->config['pp_thread'] + 1)->assign('lastpage', ceil($thread['post_count'] / $model->config['pp_thread']))->assign('pagebar', cmsPage::getPagebar($thread['post_count'], $page, $model->config['pp_thread'], '/forum/thread' . $thread['id'] . '-%page%.html'))->assign('user_id', $inUser->id)->assign('do', $do)->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->assign('is_can_add_post', cmsUser::isUserCan('forum/add_post'))->assign('cfg', $model->config)->assign('bb_toolbar', $inUser->id && $model->config['fast_on'] && $model->config['fast_bb'] ? cmsPage::getBBCodeToolbar('message', $model->config['img_on']) : '')->assign('smilies', $inUser->id && $model->config['fast_on'] && $model->config['fast_bb'] ? cmsPage::getSmilesPanel('message') : '')->display('com_forum_view_thread.tpl');
    }
    //============================================================================//
    //================ Новая тема, написать/редактировать пост ===================//
    //============================================================================//
    if (in_array($do, array('newthread', 'newpost', 'editpost'))) {
        if (!$inUser->id) {
            cmsUser::goToLogin();
        }
        // id первого поста в теме
        $first_post_id = false;
        // опросов по умолчанию нет
        $thread_poll = array();
        // применяется при редактировании поста
        $is_allow_attach = true;
        // ограничение по карме
        if (in_array($do, array('newthread', 'newpost'))) {
            if ($inUser->karma < $model->config['min_karma_add'] && !$inUser->is_admin) {
                cmsCore::addSessionMessage(sprintf($_LANG['ADD_KARMA_LIMIT'], cmsCore::spellCount($model->config['min_karma_add'], $_LANG['KPOINT1'], $_LANG['KPOINT2'], $_LANG['KPOINT10']), $inUser->karma), 'error');
                cmsCore::redirectBack();
            }
        }
        // новая тема
        if ($do == 'newthread') {
            // права доступа
            if (!cmsUser::isUserCan('forum/add_thread') && !$inUser->is_admin) {
                cmsPage::includeTemplateFile('special/accessdenied.php');
                return;
            }
            $forum = $model->getForum($id);
            if (!$forum) {
                cmsCore::error404();
            }
            if (!cmsCore::checkContentAccess($forum['access_list'])) {
                cmsPage::includeTemplateFile('special/accessdenied.php');
                return;
            }
            $path_list = $inDB->getNsCategoryPath('cms_forums', $forum['NSLeft'], $forum['NSRight'], 'id, title, access_list, moder_list');
            if ($path_list) {
                foreach ($path_list as $pcat) {
                    if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                        cmsPage::includeTemplateFile('special/accessdenied.php');
                        return;
                    }
                    $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']);
                }
                $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
            }
            if (IS_BILLING && $forum['topic_cost']) {
                cmsBilling::checkBalance('forum', 'add_thread', false, $forum['topic_cost']);
            }
            $pagetitle = $_LANG['NEW_THREAD'];
            $thread = cmsUser::sessionGet('thread');
            if ($thread) {
                cmsUser::sessionDel('thread');
            }
            $last_post['content'] = cmsUser::sessionGet('post_content');
            if ($last_post['content']) {
                cmsUser::sessionDel('post_content');
            }
        }
        // новый пост
        if ($do == 'newpost') {
            // права доступа
            if (!cmsUser::isUserCan('forum/add_post') && !$inUser->is_admin) {
                cmsPage::includeTemplateFile('special/accessdenied.php');
                return;
            }
            $thread = $model->getThread($id);
            if (!$thread || $thread['closed']) {
                cmsCore::error404();
            }
            $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list');
            if ($path_list) {
                foreach ($path_list as $pcat) {
                    if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                        cmsPage::includeTemplateFile('special/accessdenied.php');
                        return;
                    }
                    $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']);
                }
                $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
            }
            $inPage->addPathway($thread['title'], '/forum/thread' . $thread['id'] . '.html');
            $pagetitle = $_LANG['NEW_POST'];
            $last_post = $model->getPost(cmsCore::request('replyid', 'int', 0));
            if ($last_post) {
                $last_post['content'] = preg_replace('/\\[hide(.*?)\\](.*?)\\[\\/hide\\]/sui', '', $last_post['content']);
                $last_post['content'] = preg_replace('/\\[hide(.*?)\\](.*?)$/sui', '', $last_post['content']);
                $quote_nickname = $inDB->get_field('cms_users', "id = '{$last_post['user_id']}'", 'nickname');
                $last_post['content'] = '[quote=' . $quote_nickname . ']' . "\r\n" . $last_post['content'] . "\r\n" . '[/quote]' . "\r\n\r\n";
                $pagetitle = $_LANG['REPLY_FULL_QUOTE'];
            }
        }
        // редактирование поста
        if ($do == 'editpost') {
            $last_post = $model->getPost($id);
            if (!$last_post) {
                cmsCore::error404();
            }
            $is_allow_attach = $last_post['attach_count'] < $model->config['fa_max'];
            // уменьшаем значение настроек согласно загруженных файлов
            $model->config['fa_max'] = $model->config['fa_max'] - $last_post['attach_count'];
            $thread = $model->getThread($last_post['thread_id']);
            if (!$thread || $thread['closed']) {
                cmsCore::error404();
            }
            $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list');
            if ($path_list) {
                foreach ($path_list as $pcat) {
                    if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                        cmsPage::includeTemplateFile('special/accessdenied.php');
                        return;
                    }
                    $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']);
                }
                $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
            }
            $inPage->addPathway($thread['title'], '/forum/thread' . $thread['id'] . '.html');
            $end_min = $model->checkEditTime($last_post['pubdate']);
            $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $last_post['user_id'] == $inUser->id;
            // редактировать могут только администраторы, модераторы или авторы,  если время есть
            if (!$inUser->is_admin && !$is_forum_moder && !$is_author_can_edit) {
                cmsCore::error404();
            }
            if (!$inUser->is_admin && !$is_forum_moder && $model->config['edit_minutes']) {
                $msg_minute = str_replace('{min}', cmsCore::spellCount($end_min, $_LANG['MINUTE1'], $_LANG['MINUTE2'], $_LANG['MINUTE10']), $_LANG['EDIT_INFO']);
                cmsCore::addSessionMessage($msg_minute, 'info');
            }
            $first_post_id = $inDB->get_field('cms_forum_posts', "thread_id = '{$thread['id']}' ORDER BY pubdate ASC", 'id');
            $thread_poll = $model->getThreadPoll($thread['id']);
            $pagetitle = $_LANG['EDIT_POST'];
        }
        /////////////////////////
        ///  Показываем форму ///
        /////////////////////////
        if (!cmsCore::inRequest('gosend')) {
            $inPage->setTitle($pagetitle);
            $inPage->addPathway($pagetitle);
            $inPage->addHeadJsLang(array('FILE_SELECTED', 'FILE_DENIED', 'FILE_DUPLICATE'));
            cmsCore::initAutoGrowText('#message');
            cmsPage::initTemplate('components', 'com_forum_add')->assign('pagetitle', $pagetitle)->assign('is_first_post', isset($last_post['id']) ? $first_post_id == $last_post['id'] : true)->assign('thread_poll', $thread_poll)->assign('cfg', $model->config)->assign('do', $do)->assign('forum', isset($forum) ? $forum : $pcat)->assign('is_subscribed', cmsUser::isSubscribed($inUser->id, 'forum', @$thread['id']))->assign('thread', $thread)->assign('post_content', htmlspecialchars($last_post['content']))->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->assign('is_allow_attach', cmsCore::checkContentAccess($model->config['group_access']) && $is_allow_attach)->assign('bb_toolbar', cmsPage::getBBCodeToolbar('message', $model->config['img_on'], 'forum', 'post', @$last_post['id']))->assign('smilies', cmsPage::getSmilesPanel('message'))->display('com_forum_add.tpl');
        } else {
            /////////////////////////
            // Выполняем действия ///
            /////////////////////////
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $message_bb = $inDB->escape_string(cmsCore::request('message', 'html', ''));
            $message_html = $inDB->escape_string(cmsCore::parseSmiles(cmsCore::request('message', 'html', ''), true));
            if (!$message_html) {
                cmsCore::addSessionMessage($_LANG['NEED_TEXT_POST'], 'error');
                cmsCore::redirectBack();
            }
            $message_post = strip_tags($message_html);
            $message_post = mb_strlen($message_post) > 200 ? mb_substr($message_post, 0, 200) : $message_post;
            $post_pinned = 0;
            if (in_array($do, array('newthread', 'newpost'))) {
                if ($do == 'newthread') {
                    $thread['title'] = cmsCore::request('title', 'str', '');
                    $thread['description'] = cmsCore::request('description', 'str', '');
                    $post_pinned = 1;
                    if (!$thread['title']) {
                        cmsCore::addSessionMessage($_LANG['NEED_TITLE_THREAD_YOUR_POST'], 'error');
                        cmsUser::sessionPut('thread', $thread);
                        cmsUser::sessionPut('post_content', stripcslashes($message_bb));
                        cmsCore::redirectBack();
                    }
                    $thread['is_hidden'] = cmsCore::yamlToArray($forum['access_list']) ? 1 : 0;
                    $thread['forum_id'] = $forum['id'];
                    $thread['user_id'] = $inUser->id;
                    $thread['pubdate'] = date("Y-m-d H:i:s");
                    $thread['hits'] = 0;
                    $thread['id'] = $model->addThread($thread);
                    $thread['NSLeft'] = $forum['NSLeft'];
                    $thread['NSRight'] = $forum['NSRight'];
                    $thread['post_count'] = 0;
                    if (IS_BILLING && $forum['topic_cost']) {
                        cmsBilling::process('forum', 'add_thread', $forum['topic_cost']);
                    }
                }
                $post_id = $model->addPost(array('thread_id' => $thread['id'], 'user_id' => $inUser->id, 'pinned' => $post_pinned, 'content' => $message_bb, 'content_html' => $message_html, 'pubdate' => date("Y-m-d H:i:s"), 'editdate' => date("Y-m-d H:i:s")));
                // Обновляем количество постов в теме
                $thread_post_count = $model->updateThreadPostCount($thread['id']);
                // Закрываем тему если нужно
                $is_fixed = cmsCore::request('fixed', 'int', 0);
                if ($is_fixed && ($is_forum_moder || $inUser->is_admin || $thread['is_mythread'])) {
                    $model->closeThread($thread['id']);
                }
                // Загружаем аттачи
                if ($model->config['fa_on'] && cmsCore::checkContentAccess($model->config['group_access'])) {
                    $file_error = $model->addUpdatePostAttachments($post_id);
                    if ($file_error === false) {
                        cmsCore::addSessionMessage($_LANG['CHECK_SIZE_TYPE_FILE'] . $model->config['fa_max'], 'error');
                    }
                }
                // Обновляем кеши
                $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true);
                $total_pages = ceil($thread_post_count / $model->config['pp_thread']);
                // Проверяем награды
                cmsUser::checkAwards($inUser->id);
                // Рассылаем уведомления тем, кто подписан
                if ($do == 'newpost') {
                    cmsUser::sendUpdateNotify('forum', $thread['id'], array('link' => '/forum/thread' . $thread['id'] . '-' . $total_pages . '.html#' . $post_id, 'title' => stripslashes($thread['title']), 'letter_file' => 'newforumpost', 'author' => $inUser->nickname));
                }
                // Подписываемся сами если нужно
                if (cmsCore::inRequest('subscribe')) {
                    cmsUser::subscribe($inUser->id, 'forum', $thread['id']);
                }
                // Если пост не в скрытый форум и не в объедненный с предыдущим, добавляем в ленту
                if (!$thread['is_hidden'] && $thread_post_count > $thread['post_count']) {
                    if ($do == 'newthread') {
                        cmsActions::log('add_thread', array('object' => $thread['title'], 'object_url' => '/forum/thread' . $thread['id'] . '-1.html', 'object_id' => $thread['id'], 'target' => $forum['title'], 'target_url' => '/forum/' . $forum['id'], 'target_id' => $forum['id'], 'description' => $message_post));
                    } else {
                        cmsActions::log('add_fpost', array('object' => $_LANG['MESSAGE'], 'object_url' => '/forum/thread' . $thread['id'] . '-' . $total_pages . '.html#' . $post_id, 'object_id' => $post_id, 'target' => $thread['title'], 'target_url' => '/forum/thread' . $thread['id'] . '.html', 'target_id' => $thread['id'], 'description' => $message_post));
                    }
                }
                // Для новой темы прикрепляем опрос если нужно
                if ($do == 'newthread') {
                    $model->addPoll(cmsCore::request('poll', 'array', array()), $thread['id']);
                    $last_poll_error = $model->getLastAddPollError();
                    if ($last_poll_error) {
                        cmsCore::addSessionMessage($last_poll_error, 'error');
                        cmsCore::redirect('/forum/editpost' . $post_id . '-1.html');
                    }
                }
                cmsCore::redirect('/forum/thread' . $thread['id'] . '-' . $total_pages . '.html#' . $post_id);
            } elseif ($do == 'editpost') {
                $model->updatePost(array('content' => $message_bb, 'content_html' => $message_html, 'edittimes' => $last_post['edittimes'] + 1, 'editdate' => date("Y-m-d H:i:s")), $last_post['id']);
                if ($model->config['fa_on'] && cmsCore::checkContentAccess($model->config['group_access'])) {
                    $file_error = $model->addUpdatePostAttachments($last_post['id']);
                    if ($file_error === false) {
                        cmsCore::addSessionMessage($_LANG['CHECK_SIZE_TYPE_FILE'] . $model->config['fa_max'], 'error');
                    }
                }
                if ($first_post_id == $last_post['id']) {
                    cmsActions::updateLog('add_thread', array('description' => $message_post), $thread['id']);
                    if ($thread_poll) {
                        $model->updatePoll(cmsCore::request('poll', 'array', array()), $thread_poll);
                    } else {
                        $model->addPoll(cmsCore::request('poll', 'array', array()), $thread['id']);
                    }
                    $last_poll_error = $model->getLastAddPollError();
                    if ($last_poll_error) {
                        cmsUser::sessionPut('thread', $thread);
                        cmsUser::sessionPut('post_content', stripcslashes($message_bb));
                        cmsCore::addSessionMessage($last_poll_error, 'error');
                        cmsCore::redirectBack();
                    }
                } else {
                    cmsActions::updateLog('add_fpost', array('description' => $message_post), $last_post['id']);
                }
                $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true);
                cmsCore::redirect('/forum/thread' . $thread['id'] . '-' . $page . '.html#' . $last_post['id']);
            }
        }
    }
    ///////////////////////////// DELETE POST /////////////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'deletepost') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $post = $model->getPost($id);
        if (!$post) {
            cmsCore::error404();
        }
        $thread = $model->getThread($post['thread_id']);
        if (!$thread) {
            cmsCore::error404();
        }
        $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list, NSLeft, NSRight');
        if ($path_list) {
            foreach ($path_list as $pcat) {
                if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                    cmsCore::error404();
                }
            }
            $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
        }
        $end_min = $model->checkEditTime($post['pubdate']);
        $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $post['user_id'] == $inUser->id;
        if (!$inUser->is_admin && !($is_forum_moder && !cmsUser::userIsAdmin($post['user_id'])) && !$is_author_can_edit) {
            cmsCore::error404();
        }
        $model->deletePost($post['id']);
        $model->updateThreadPostCount($post['thread_id']);
        $model->cacheThreadLastPost($post['thread_id']);
        if ($path_list) {
            $path_list = array_reverse($path_list);
            foreach ($path_list as $pcat) {
                $model->updateForumCache($pcat['NSLeft'], $pcat['NSRight']);
            }
        }
        cmsCore::addSessionMessage($_LANG['MSG_IS_DELETED'], 'info');
        $total_pages = ceil(($thread['post_count'] - 1) / $model->config['pp_thread']);
        if ($page > $total_pages) {
            $page = $total_pages;
        }
        cmsCore::jsonOutput(array('error' => false, 'redirect' => '/forum/thread' . $thread['id'] . '-' . $page . '.html'));
    }
    //============================================================================//
    //========================== Операции с темами ===============================//
    //============================================================================//
    if (in_array($do, array('movethread', 'renamethread', 'deletethread', 'close', 'pin', 'pin_post', 'move_post'))) {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $thread = $model->getThread($id);
        if (!$thread) {
            cmsCore::halt();
        }
        $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list, NSLeft, NSRight');
        if ($path_list) {
            foreach ($path_list as $pcat) {
                if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                    cmsCore::halt();
                }
            }
            $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
        }
        //======================= Перемещение темы ===============================//
        if ($do == 'movethread') {
            if (!$inUser->is_admin && !$is_forum_moder) {
                cmsCore::halt();
            }
            if (!cmsCore::inRequest('gomove')) {
                cmsPage::initTemplate('components', 'com_forum_move_thread')->assign('thread', $thread)->assign('forums', $model->getForums())->display('com_forum_move_thread.tpl');
                cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
            } else {
                $new_forum = $model->getForum(cmsCore::request('forum_id', 'int', 0));
                if (!$new_forum) {
                    cmsCore::error404();
                }
                $is_hidden = 0;
                $path_list = $inDB->getNsCategoryPath('cms_forums', $new_forum['NSLeft'], $new_forum['NSRight'], 'id, title, access_list, moder_list');
                if ($path_list) {
                    foreach ($path_list as $pcat) {
                        if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                            cmsCore::halt();
                        }
                        if (cmsCore::yamlToArray($pcat['access_list'])) {
                            $is_hidden = 1;
                        }
                    }
                    $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
                }
                if (!$is_forum_moder && !$inUser->is_admin) {
                    cmsCore::addSessionMessage($_LANG['YOU_NO_THIS_FORUM_MODER'], 'error');
                    cmsCore::redirect('/forum/thread' . $thread['id'] . '.html');
                }
                $inDB->query("UPDATE cms_forum_threads SET forum_id = '{$new_forum['id']}', is_hidden = '{$is_hidden}' WHERE id = '{$thread['id']}'");
                cmsActions::updateLog('add_thread', array('target' => $new_forum['title'], 'target_url' => '/forum/' . $new_forum['id'], 'target_id' => $new_forum['id']), $thread['id']);
                // Обновляем кешированные значения
                // для старого форума
                $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true);
                // для нового форума
                $model->updateForumCache($new_forum['NSLeft'], $new_forum['NSRight'], true);
                cmsCore::addSessionMessage($_LANG['THREAD_IS_MOVE'] . '"' . $new_forum['title'] . '"', 'success');
                cmsCore::redirect('/forum/thread' . $thread['id'] . '.html');
            }
        }
        //===================== Переименование темы ==============================//
        if ($do == 'renamethread') {
            if (!$inUser->is_admin && !$is_forum_moder && !$thread['is_mythread']) {
                cmsCore::halt();
            }
            if (!cmsCore::inRequest('gorename')) {
                cmsPage::initTemplate('components', 'com_forum_rename_thread')->assign('thread', $thread)->display('com_forum_rename_thread.tpl');
                cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
            } else {
                $new_thread['title'] = cmsCore::request('title', 'str', $thread['title']);
                $new_thread['description'] = cmsCore::request('description', 'str', '');
                $model->updateThread($new_thread, $thread['id']);
                cmsActions::updateLog('add_fpost', array('target' => $new_thread['title']), 0, $thread['id']);
                cmsActions::updateLog('add_thread', array('object' => $new_thread['title']), $thread['id']);
                $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true);
                cmsCore::jsonOutput(array('error' => false, 'title' => stripslashes($new_thread['title']), 'description' => stripslashes($new_thread['description'])));
            }
        }
        //======================= Удаление темы ==================================//
        if ($do == 'deletethread') {
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            if (!$inUser->is_admin && !($is_forum_moder && !cmsUser::userIsAdmin($thread['user_id'])) && !$thread['is_mythread']) {
                cmsCore::halt();
            }
            $model->deleteThread($thread['id']);
            // Обновляем кешированные значения
            $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true);
            cmsCore::jsonOutput(array('error' => false, 'redirect' => '/forum/' . $thread['forum_id']));
        }
        //=============== Прикрепление/открепление темы ==========================//
        if ($do == 'pin') {
            if (!$inUser->is_admin && !$is_forum_moder) {
                cmsCore::halt();
            }
            $pinned = cmsCore::request('pinned', 'int', 0);
            $inDB->query("UPDATE cms_forum_threads SET pinned = '{$pinned}' WHERE id = '{$thread['id']}'");
            cmsCore::halt($pinned);
        }
        //========== Прикрепление/открепление сообщения темы =====================//
        if ($do == 'pin_post') {
            if (!$inUser->is_admin && !$is_forum_moder) {
                cmsCore::halt();
            }
            $pinned = cmsCore::request('pinned', 'int', 0);
            $post_id = cmsCore::request('post_id', 'int', 0);
            // Проверяем, принадлежит ли сообщение теме
            if (!$model->isBelongsToPostTopic($post_id, $thread['id'])) {
                cmsCore::halt();
            }
            $inDB->query("UPDATE cms_forum_posts SET pinned = '{$pinned}' WHERE id = '{$post_id}' AND thread_id = '{$thread['id']}'");
            // Ниже строки для тех, кто обновлялся с 1.9, если чистая установка, их можно удалить
            // Ставим принудительно для первого поста темы флаг pinned
            if ($pinned) {
                $first_post_id = $inDB->get_field('cms_forum_posts', "thread_id = '{$thread['id']}' ORDER BY pubdate ASC", 'id');
                $inDB->query("UPDATE cms_forum_posts SET pinned = 1 WHERE id = '{$first_post_id}' AND thread_id = '{$thread['id']}'");
            }
            cmsCore::redirect('/forum/thread' . $thread['id'] . '-1.html#' . $post_id);
        }
        //=========================== Перенос сообщения темы =====================//
        if ($do == 'move_post') {
            if (!$inUser->is_admin && !$is_forum_moder) {
                cmsCore::halt();
            }
            $post_id = cmsCore::request('post_id', 'int', 0);
            // Проверяем, принадлежит ли сообщение теме
            if (!$model->isBelongsToPostTopic($post_id, $thread['id'])) {
                cmsCore::halt();
            }
            cmsCore::callEvent('MOVE_FORUM_POST', array('thread' => $thread, 'post_id' => $post_id));
            if (!cmsCore::inRequest('gomove')) {
                cmsPage::initTemplate('components', 'com_forum_move_post')->assign('thread', $thread)->assign('post_id', $post_id)->assign('threads', cmsCore::getListItems('cms_forum_threads', $thread['id'], 'title', 'ASC', "forum_id = '{$thread['forum_id']}'"))->display('com_forum_move_post.tpl');
                cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
            } else {
                $new_thread = $model->getThread(cmsCore::request('new_thread_id', 'int', 0));
                if (!$new_thread) {
                    cmsCore::error404();
                }
                $n_path_list = $inDB->getNsCategoryPath('cms_forums', $new_thread['NSLeft'], $new_thread['NSRight'], 'id, title, access_list, moder_list, NSLeft, NSRight');
                if ($n_path_list) {
                    foreach ($n_path_list as $n_pcat) {
                        if (!cmsCore::checkContentAccess($n_pcat['access_list'])) {
                            cmsCore::halt();
                        }
                    }
                    $is_forum_moder = $model->isForumModerator($n_pcat['moder_list']);
                }
                if (!$is_forum_moder && !$inUser->is_admin) {
                    cmsCore::error404();
                }
                $model->updatePost(array('thread_id' => $new_thread['id'], 'pubdate' => date("Y-m-d H:i:s")), $post_id);
                $model->updateThreadPostCount($thread['id']);
                $thread_post_count = $model->updateThreadPostCount($new_thread['id']);
                $total_pages = ceil($thread_post_count / $model->config['pp_thread']);
                cmsActions::updateLog('add_fpost', array('target' => $new_thread['title'], 'target_url' => '/forum/thread' . $new_thread['id'] . '.html', 'target_id' => $new_thread['id'], 'object_url' => '/forum/thread' . $new_thread['id'] . '-' . $total_pages . '.html#' . $post_id, 'pubdate' => date("Y-m-d H:i:s")), $post_id);
                $model->cacheThreadLastPost($thread['id']);
                if ($path_list) {
                    $path_list = array_reverse($path_list);
                    foreach ($path_list as $pcat) {
                        $model->cacheLastPost($pcat['NSLeft'], $pcat['NSRight']);
                    }
                }
                if ($n_path_list) {
                    $n_path_list = array_reverse($n_path_list);
                    foreach ($n_path_list as $pcat) {
                        $model->cacheLastPost($pcat['NSLeft'], $pcat['NSRight']);
                    }
                }
                cmsCore::addSessionMessage($_LANG['POST_IS_MOVE'] . '"' . $new_thread['title'] . '"', 'success');
                cmsCore::redirect('/forum/thread' . $new_thread['id'] . '-' . $total_pages . '.html#' . $post_id);
            }
        }
        //==================== Открытие/закрытие темы ============================//
        if ($do == 'close') {
            if (!$inUser->is_admin && !$is_forum_moder && !$thread['is_mythread']) {
                cmsCore::halt();
            }
            $closed = cmsCore::request('closed', 'int', 0);
            if ($closed) {
                $model->closeThread($thread['id']);
            } else {
                $model->openThread($thread['id']);
            }
            cmsCore::halt($closed);
        }
        cmsCore::halt();
    }
    //============================================================================//
    //========================== Операции с файлами ==============================//
    //============================================================================//
    if (in_array($do, array('download', 'delfile', 'reloadfile'))) {
        if (!$model->config['fa_on']) {
            cmsCore::error404();
        }
        $file = $model->getPostAttachment($id);
        if (!$file) {
            cmsCore::error404();
        }
        $post = $model->getPost($file['post_id']);
        if (!$post) {
            cmsCore::error404();
        }
        $thread = $model->getThread($post['thread_id']);
        if (!$thread) {
            cmsCore::error404();
        }
        $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list');
        if ($path_list) {
            foreach ($path_list as $pcat) {
                if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                    cmsCore::error404();
                }
            }
            $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
        }
        //================= Скачивание прикрепленного файла ======================//
        if ($do == 'download') {
            $location = PATH . '/upload/forum/post' . $file['post_id'] . '/' . $file['filename'];
            if (!file_exists($location)) {
                cmsCore::error404();
            }
            $inDB->query("UPDATE cms_forum_files SET hits = hits + 1 WHERE id = '{$file['id']}'");
            ob_clean();
            header('Content-Disposition: attachment; filename=' . htmlspecialchars($file['filename']));
            header('Content-Type: application/x-force-download; name="' . htmlspecialchars($file['filename']) . '"');
            header('Content-Length: ' . $file['filesize']);
            header('Accept-Ranges: bytes');
            cmsCore::halt(file_get_contents($location));
        }
        //=================== Удаление прикрепленного файла ======================//
        if ($do == 'delfile') {
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $end_min = $model->checkEditTime($post['pubdate']);
            $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $post['user_id'] == $inUser->id && cmsCore::checkContentAccess($model->config['group_access']);
            if (!$inUser->is_admin && !$is_forum_moder && !$is_author_can_edit) {
                cmsCore::halt();
            }
            $model->deletePostAttachment($file);
            cmsCore::halt(1);
        }
        //================== Перезакачка прикрепленного файла ====================//
        if ($do == 'reloadfile') {
            $end_min = $model->checkEditTime($post['pubdate']);
            $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $post['user_id'] == $inUser->id && cmsCore::checkContentAccess($model->config['group_access']);
            if (!$inUser->is_admin && !$is_forum_moder && !$is_author_can_edit) {
                cmsCore::error404();
            }
            if (!cmsCore::inRequest('goreload')) {
                cmsPage::initTemplate('components', 'com_forum_file_reload')->assign('file', $file)->assign('cfg', $model->config)->display('com_forum_file_reload.tpl');
                cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
            } else {
                $success = $model->addUpdatePostAttachments($post['id'], $file);
                if ($success) {
                    $post['attached_files'] = $model->getPostAttachments($post['id']);
                    $post['is_author_can_edit'] = $is_author_can_edit;
                    cmsPage::initTemplate('components', 'com_forum_attached_files')->assign('post', $post)->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->assign('cfg', $model->config)->display('com_forum_attached_files.tpl');
                    cmsCore::jsonOutput(array('error' => false, 'post_id' => $post['id'], 'html' => ob_get_clean()));
                } else {
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CHECK_SIZE_TYPE_FILE'] . $model->config['fa_max']));
                }
            }
        }
        cmsCore::halt();
    }
    //============================================================================//
    //========================= Операции с опросами ==============================//
    //============================================================================//
    if ($do == 'view_poll') {
        $thread = $model->getThread($id);
        if (!$thread) {
            cmsCore::halt();
        }
        $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list');
        if ($path_list) {
            foreach ($path_list as $pcat) {
                if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                    cmsCore::halt();
                }
            }
            $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
        }
        $thread_poll = $model->getThreadPoll($thread['id']);
        if (!$thread_poll) {
            cmsCore::halt();
        }
        if ($inUser->id && $thread_poll['is_user_vote'] && $thread_poll['options']['change'] && cmsCore::request('revote', 'int')) {
            $model->deleteVote($thread_poll);
            $thread_poll['is_user_vote'] = 0;
            $thread_poll['vote_count'] -= 1;
        }
        if (!$thread_poll['is_user_vote'] && !$thread_poll['options']['result']) {
            $thread_poll['show_result'] = cmsCore::request('show_result', 'int');
        }
        cmsPage::initTemplate('components', 'com_forum_thread_poll')->assign('thread', $thread)->assign('thread_poll', $thread_poll)->assign('user_id', $inUser->id)->assign('do', $thread_poll['show_result'] ? $do : 'thread')->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->display('com_forum_thread_poll.tpl');
        cmsCore::halt(ob_get_clean());
    }
    if ($do == 'delete_poll') {
        if (!$inUser->id) {
            cmsCore::halt();
        }
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::halt();
        }
        $thread = $model->getThread($id);
        if (!$thread) {
            cmsCore::halt();
        }
        $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list');
        if ($path_list) {
            foreach ($path_list as $pcat) {
                if (!cmsCore::checkContentAccess($pcat['access_list'])) {
                    cmsCore::halt();
                }
            }
            $is_forum_moder = $model->isForumModerator($pcat['moder_list']);
        }
        $thread_poll = $model->getThreadPoll($thread['id']);
        if (!$thread_poll) {
            cmsCore::halt();
        }
        if (!$is_forum_moder && !$inUser->is_admin) {
            cmsCore::halt();
        }
        $model->deletePoll($thread_poll['id']);
        cmsCore::halt(1);
    }
    if ($do == 'vote_poll') {
        if (!$inUser->id) {
            cmsCore::halt();
        }
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::halt();
        }
        $answer = cmsCore::request('answer', 'str', '');
        $poll = $model->getPollById(cmsCore::request('poll_id', 'int'));
        if (!$answer || !$poll) {
            cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['SELECT_THE_OPTION']));
        }
        if ($model->isUserVoted($poll['id'])) {
            cmsCore::jsonOutput(array('error' => true, 'text' => ''));
        }
        $model->votePoll($poll, $answer);
        cmsCore::jsonOutput(array('error' => false, 'text' => ''));
    }
    //============================================================================//
    //========================= Последние сообщения ==============================//
    //============================================================================//
    if ($do == 'latest_posts') {
        $inActions = cmsActions::getInstance();
        $inPage->setTitle($_LANG['LATEST_POSTS_ON_FORUM']);
        $inPage->addPathway($_LANG['FORUMS'], '/forum');
        $inPage->addPathway($_LANG['LATEST_POSTS_ON_FORUM']);
        $inActions->showTargets(true);
        $action = $inActions->getAction('add_fpost');
        $inActions->onlySelectedTypes(array($action['id']));
        $total = $inActions->getCountActions();
        $inDB->limitPage($page, 15);
        $actions = $inActions->getActionsLog();
        if (!$actions && $page > 1) {
            cmsCore::error404();
        }
        cmsPage::initTemplate('components', 'com_forum_actions')->assign('actions', $actions)->assign('total', $total)->assign('do', $do)->assign('user_id', $inUser->id)->assign('pagetitle', $_LANG['LATEST_POSTS_ON_FORUM'])->assign('pagebar', cmsPage::getPagebar($total, $page, 15, '/forum/latest_posts/page-%page%'))->display('com_forum_actions.tpl');
    }
    //============================================================================//
    //============================= Последние темы ===============================//
    //============================================================================//
    if ($do == 'latest_thread') {
        $inActions = cmsActions::getInstance();
        $inPage->setTitle($_LANG['NEW_THREADS_ON_FORUM']);
        $inPage->addPathway($_LANG['FORUMS'], '/forum');
        $inPage->addPathway($_LANG['NEW_THREADS_ON_FORUM']);
        $inActions->showTargets(true);
        $action = $inActions->getAction('add_thread');
        $inActions->onlySelectedTypes(array($action['id']));
        $total = $inActions->getCountActions();
        $inDB->limitPage($page, 15);
        $actions = $inActions->getActionsLog();
        if (!$actions && $page > 1) {
            cmsCore::error404();
        }
        cmsPage::initTemplate('components', 'com_forum_actions')->assign('actions', $actions)->assign('total', $total)->assign('do', $do)->assign('user_id', $inUser->id)->assign('pagetitle', $_LANG['NEW_THREADS_ON_FORUM'])->assign('pagebar', cmsPage::getPagebar($total, $page, 15, '/forum/latest_thread/page-%page%'))->display('com_forum_actions.tpl');
    }
    //============================================================================//
    //========================== Просмотр категории ==============================//
    //============================================================================//
    if ($do == 'view_cat') {
        $cat = $model->getForumCat(cmsCore::request('seolink', 'str', ''));
        if (!$cat) {
            cmsCore::error404();
        }
        $cat = translations::process(cmsConfig::getConfig('lang'), 'forum_forum_cats', $cat);
        $inPage->setTitle($cat['pagetitle'] ? $cat['pagetitle'] : $cat['title']);
        $inPage->setDescription($cat['meta_desc'] ? $cat['meta_desc'] : $cat['title']);
        $inPage->setKeywords($cat['meta_keys'] ? $cat['meta_keys'] : $cat['title']);
        $inPage->addPathway($cat['title']);
        $model->whereForumCatIs($cat['id']);
        $sub_forums = $model->getForums();
        cmsPage::initTemplate('components', 'com_forum_list')->assign('pagetitle', $cat['title'])->assign('forums', $sub_forums)->assign('forum', array())->assign('cfg', $model->config)->assign('user_id', false)->display('com_forum_list.tpl');
        $inDB->addJoin('INNER JOIN cms_forums f ON f.id = t.forum_id');
        $inDB->where("t.is_hidden = 0");
        $model->whereForumCatIs($cat['id']);
        $inDB->orderBy('t.pubdate', 'DESC, t.hits DESC');
        $inDB->limit(15);
        $threads = $model->getThreads();
        cmsPage::initTemplate('components', 'com_forum_view')->assign('threads', $threads)->display('com_forum_view.tpl');
    }
    //============================================================================//
    //===================== Активность пользователя ==============================//
    //============================================================================//
    if ($do == 'user_activity') {
        $login = cmsCore::request('login', 'str', $inUser->login);
        $sub_do = cmsCore::request('sub_do', 'str', 'threads');
        $user = cmsUser::getShortUserData($login);
        if (!$user) {
            cmsCore::error404();
        }
        $my_profile = $inUser->login == $login;
        $pagetitle = $my_profile ? $_LANG['MY_ACTIVITY'] : $user['nickname'] . ' - ' . $_LANG['ACTIVITY_ON_FORUM'];
        $inPage->setTitle($pagetitle);
        $inPage->addPathway($pagetitle);
        $threads = array();
        $posts = array();
        if (!$my_profile && !$inUser->is_admin) {
            $model->wherePublicThreads();
        }
        $model->whereThreadUserIs($user['id']);
        $thread_count = $model->getThreadsCount();
        if ($sub_do == 'threads' && $thread_count) {
            $inDB->orderBy('t.pubdate', 'DESC, t.hits DESC');
            $inDB->limitPage($page, 15);
            $threads = $model->getThreads();
            $pagination = cmsPage::getPagebar($thread_count, $page, 15, "javascript:forum.getUserActivity('threads','/forum/{$user['login']}_activity.html','%page%');");
        }
        $inDB->resetConditions();
        // Если тем у пользователя нет, показываем вкладку сообщений
        if (!$thread_count) {
            $sub_do = 'posts';
        }
        $inDB->addSelect('t.title as thread_title');
        $inDB->addJoin('INNER JOIN cms_forum_threads t ON t.id = p.thread_id');
        $model->wherePostUserIs($user['id']);
        if (!$my_profile && !$inUser->is_admin) {
            $model->wherePublicThreads();
        }
        $post_count = $model->getPostsCount();
        // Если сообщений нет, 404
        if (!$post_count && !$my_profile) {
            cmsCore::error404();
        }
        if ($sub_do == 'posts' && $post_count) {
            $inDB->orderBy('p.thread_id', 'DESC, p.pubdate DESC');
            $inDB->limitPage($page, 10);
            $posts = $model->getPosts();
            $pagination = cmsPage::getPagebar($post_count, $page, 10, "javascript:forum.getUserActivity('posts','/forum/{$user['login']}_activity.html','%page%');");
        }
        $inDB->resetConditions();
        cmsPage::initTemplate('components', 'com_forum_user_activity')->assign('threads', $threads)->assign('posts', $posts)->assign('post_count', $post_count)->assign('thread_count', $thread_count)->assign('pagetitle', $pagetitle)->assign('sub_do', $sub_do)->assign('page', $page)->assign('user_id', $user['id'])->assign('my_profile', $my_profile)->assign('is_admin', $inUser->is_admin)->assign('is_moderator', cmsUser::isUserCan('forum/moderate'))->assign('pagination', $pagination)->assign('link', '/forum/' . $user['login'] . '_activity.html')->display('com_forum_user_activity.tpl');
    }
    ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'delete_all_user_posts') {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        if (!$inUser->is_admin && !cmsUser::isUserCan('forum/moderate')) {
            cmsCore::error404();
        }
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::halt();
        }
        $user = cmsUser::getShortUserData(cmsCore::request('user_id', 'int', 0));
        if (!$user || $user['id'] == $inUser->id) {
            cmsCore::error404();
        }
        $model->deleteAllUserPosts($user['id']);
        cmsCore::addSessionMessage($_LANG['ALL_USERPOSTS_ISDELETED'], 'success');
        cmsCore::halt();
    }
}
Beispiel #8
0
function catalog(){

    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB   = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();

    global $_LANG;

    $model = new cms_model_catalog();

    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) { cmsCore::loadClass('billing'); }

    $pagetitle = $inCore->getComponentTitle();

	$inPage->addPathway($pagetitle, '/catalog');
	$inPage->setTitle($pagetitle);

	$inPage->setDescription($model->config['meta_desc'] ? $model->config['meta_desc'] : $pagetitle);
    $inPage->setKeywords($model->config['meta_keys'] ? $model->config['meta_keys'] : $pagetitle);

    $cfg = $inCore->loadComponentConfig('catalog');

    if (cmsCore::inRequest('cat_id')){
        $id = cmsCore::request('cat_id', 'int', 0);
    } else {
        $id = cmsCore::request('id', 'int', 0);
    }

    $do = $inCore->do;

    cmsCore::includeFile('components/catalog/includes/shopcore.php');

    //////////////////////////// RATING SUBMISSION ///////////////////////////////////////////////////////////////////
    if (cmsCore::inRequest('rating')){
        $points     = cmsCore::request('points', 'int', 0);
        $item_id    = cmsCore::request('item_id', 'int', 0);
        $ip         = $inUser->ip;
        if (!alreadyVoted($item_id)){
            $inDB->query("INSERT INTO cms_uc_ratings (item_id, points, ip) VALUES ($item_id, $points, '$ip')") ;
            $inDB->query("DELETE FROM cms_uc_ratings WHERE item_id = $item_id AND ip = '0.0.0.0'") ;
        }
    }

    //////////////////////////// SEARCH BY TAG ///////////////////////////////////////////////////////////////////////
    if ($do == 'tag') {

		$tag = $inCore->strClear(urldecode($inCore->request('tag', 'html', '')));

        $sql = "SELECT tag FROM cms_tags WHERE tag = '$tag' AND target='catalog' LIMIT 1";
        $result = $inDB->query($sql) ;
        if ($inDB->num_rows($result)==1){
            $item = $inDB->fetch_assoc($result);
            $query = $inCore->strClear($item['tag']);
            $findsql = "SELECT *
                        FROM cms_uc_items
                        WHERE category_id = '$id' AND published = 1 AND tags LIKE '%$query%'";
            $do = 'cat';
        } else { echo $_LANG['NO_MATCHING_FOUND']; }

    }
    //////////////////////////// ADVANCED SEARCH ////////////////////////////////////////////////////////////////////
    if ($do == 'search') {

        if (cmsCore::inRequest('gosearch')){

            $fdata = cmsCore::request('fdata', 'array', array());
            $query = cmsCore::strClear(implode('%', $fdata));
            $title = cmsCore::request('title', 'str', '');
            $tags  = cmsCore::request('tags', 'str', '');

            if ($query || $title || $tags){

                $findsql = "SELECT i.* , IFNULL(AVG(r.points),0) AS rating
                            FROM cms_uc_items i
                            LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                            WHERE i.published = 1 AND i.category_id = '$id' ";

                if($query){
                    $findsql .= " AND i.fieldsdata LIKE '%{$query}%' ";
                }
                if($title){
                    $findsql .= " AND i.title LIKE '%$title%' ";
                }
                if($tags){
                    $findsql .= "AND (i.tags LIKE '%".$tags."%')";
                }

                $findsql .=	" GROUP BY i.id";
                $advsearch = 1;
            }
            $do = 'cat';
        } else {
            //show search form
            $sql = "SELECT * FROM cms_uc_cats WHERE id = '$id'";
            $result = $inDB->query($sql) ;

            if ($inDB->num_rows($result)==1){
                $cat = $inDB->fetch_assoc($result);
                $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

                //heading
                $inPage->addPathway($cat['title'], '/catalog/'.$cat['id']);
                $inPage->addPathway($_LANG['SEARCH'], '/catalog/'.$cat['id'].'/search.html');
                $inPage->setTitle($_LANG['SEARCH_IN_CAT']);

                $inPage->addHeadJS('components/catalog/js/search.js');

                $fstruct_ready = array();
                foreach($fstruct as $key=>$value) {
                    if (mb_strstr($value, '/~h~/')) { $ftype = 'html'; $value=str_replace('/~h~/', '', $value); }
                    elseif (mb_strstr($value, '/~l~/')) { $ftype = 'link'; $value=str_replace('/~l~/', '', $value); } else { $ftype='text'; }
                    if (mb_strstr($value, '/~m~/')) {
                        $value = str_replace('/~m~/', '', $value);
                    }
                    $fstruct_ready[stripslashes($key)] = stripslashes($value);
                }

                //searchform
                cmsPage::initTemplate('components', 'com_catalog_search')->
                        assign('id', $id)->
                        assign('cat', $cat)->
                        assign('fstruct', $fstruct_ready)->
                        display('com_catalog_search.tpl');

            } else { cmsCore::error404(); }
        }//search form

    }
    //////////////////////////// SEARCH BY FIRST LETTER OF TITLE ///////////////////////////////////////////////////////
    if ($do == 'findfirst') {

        $id = cmsCore::request('cat_id', 'int');

		$query = mb_substr(cmsCore::strClear(urldecode(cmsCore::request('text', 'html', ''))), 0, 1);

        $findsql = "SELECT i.* , IFNULL(AVG( r.points ),0) AS rating
                    FROM cms_uc_items i
                    LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = $id AND UPPER(LTRIM(i.title)) LIKE UPPER('$query%')
                    GROUP BY i.id";

        $do = 'cat';
        $advsearch = 0;

        $pagemode = 'findfirst';

    }

    //////////////////////////// SEARCH BY FIELD ////////////////////////////////////////////////////////////////////
    if ($do == 'find') {

        $id = cmsCore::request('cat_id', 'int');

        $query = cmsCore::strClear(urldecode(cmsCore::request('text', 'html', '')));

        $findsql = "SELECT i.* , IFNULL(AVG(r.points),0) AS rating
                    FROM cms_uc_items i
                    LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = $id AND i.fieldsdata LIKE '%$query%'
                    GROUP BY i.id";

        $do = 'cat';
        $advsearch = 0;

		$query = stripslashes($query);

        $pagemode = 'find';
    }

    //////////////////////////// LIST OF CATEGORIES ////////////////////////////////////////////////////////////////////
    if ($do == 'view'){ //List of all categories

        $cats_html = subCatsList();
        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['CATALOG'].'" href="'.HOST.'/rss/catalog/all/feed.rss">');
        cmsPage::initTemplate('components', 'com_catalog_index')->
                assign('cfg', $cfg)->
                assign('title', $pagetitle)->
                assign('cats_html', $cats_html)->
                display('com_catalog_index.tpl');

    }

    //////////////////////////// VIEW CATEGORY ///////////////////////////////////////////////////////////////////////
    if ($do == 'cat'){

        //get category data
        $sql = "SELECT * FROM cms_uc_cats WHERE id = $id";
        $catres = $inDB->query($sql);
        if (!$inDB->num_rows($catres)){ cmsCore::error404(); }

        $cat     = $inDB->fetch_assoc($catres);
        $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['CATALOG'].'" href="'.HOST.'/rss/catalog/'.$cat['id'].'/feed.rss">');

        //heading
        //PATHWAY ENTRY
        $path_list = $model->getCategoryPath($cat['NSLeft'], $cat['NSRight']);
        if ($path_list){
            foreach($path_list as $pcat){
                $inPage->addPathway($pcat['title'], '/catalog/'.$pcat['id']);
            }
        }
        $inPage->setTitle($cat['pagetitle'] ? $cat['pagetitle'] : $cat['title']);

        //subcategories
        $subcats = subCatsList($cat['id'], $cat['NSLeft'], $cat['NSRight']);

        //alphabetic list
        if ($cat['showabc']){ $alphabet = getAlphaList($cat['id']);	} else { $alphabet = ''; }

        //Tool links
        $shopcartlink = shopCartLink();

        //get items SQL
        if (!isset($findsql)){
            $sql = "SELECT i.* , IFNULL(AVG( r.points ), 0) AS rating, i.price as price
                    FROM cms_uc_items i
                    LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = $id
                    GROUP BY i.id";
        } else {
            $sql = $findsql;
            if (!$advsearch){ $inPage->addPathway(icms_ucfirst($query)); } else
            { $inPage->addPathway($_LANG['SEARCH_RESULT']); }
        }

        // сортировка
        if(cmsCore::inRequest('orderby')){
            $orderby = cmsCore::request('orderby', array('hits','rating','pubdate','title','price'), $cat['orderby']);
            cmsUser::sessionPut('uc_orderby', $orderby);
        } elseif(cmsUser::sessionGet('uc_orderby')){
            $orderby = cmsUser::sessionGet('uc_orderby');
        } else {
            $orderby = $cat['orderby'];
        }
        if(cmsCore::inRequest('orderto')){
            $orderto = cmsCore::request('orderto', array('asc','desc'), $cat['orderto']);
            cmsUser::sessionPut('uc_orderto', $orderto);
        } elseif(cmsUser::sessionGet('uc_orderto')){
            $orderto = cmsUser::sessionGet('uc_orderto');
        } else {
            $orderto = $cat['orderto'];
        }

        $sql .=  " ORDER BY ".$orderby." ".$orderto;

        //get total items count
        $result = $inDB->query($sql);
        $itemscount = $inDB->num_rows($result);

        //can user add items here?
        $is_cat_access = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id);
        $is_can_add = $is_cat_access || $inUser->is_admin;

        $tpl = cmsPage::initTemplate('components', 'com_catalog_view')->
                assign('id', $id)->
                assign('cat', $cat)->
                assign('subcats', $subcats)->
                assign('alphabet', $alphabet)->
                assign('shopcartlink', $shopcartlink)->
                assign('itemscount', $itemscount)->
                assign('is_can_add', $is_can_add)->
                assign('orderform', orderForm($orderby, $orderto, ($cat['view_type']=='shop')));

        //pagination
        if (!@$advsearch) { $perpage = $cat['perpage']; } else { $perpage='100'; }
        $page = $inCore->request('page', 'int', 1);

        //request items using pagination
        $sql .= " LIMIT ".(($page-1)*$perpage).", $perpage";
        $result = $inDB->query($sql) ;

        //search details, if needed
        $search_details = '';
        if (isset($findsql)){
            if ($advsearch){
                $search_details = '<div class="uc_queryform"><strong>'.$_LANG['SEARCH_RESULT'].' - </strong> '.$_LANG['FOUNDED'].': '.$itemscount.' | <a href="/catalog/'.$cat['id'].'">'.$_LANG['CANCEL_SEARCH'].'</a></div>';
            } else {
                $search_details = '<div class="uc_queryform"><strong>'.$_LANG['SEARCH_BY_TAG'].'</strong> "'.htmlspecialchars(icms_ucfirst(stripslashes($query))).'" ('.$_LANG['MATCHES'].': '.$itemscount.') <a href="/catalog/'.$cat['id'].'">'.$_LANG['CANCEL_SEARCH'].'</a></div>';
            }
        }

        $items = array();
        while($item = $inDB->fetch_assoc($result)){
            $item['ratingdata'] = ratingData($item['id']);
            $item['fdata'] = cmsCore::yamlToArray($item['fieldsdata']);
            $item['price'] = number_format(shopDiscountPrice($item['id'], $item['category_id'], $item['price']), 2, '.', ' ');
            $item['rating'] = cms_model_catalog::buildRating($item['ratingdata']['rating']);
            $item['is_new'] = isNew($item['id'], $cat['shownew'], $cat['newint']);
            $item['tagline'] = tagLine($item['tags'], $cat['id']);

            $item['can_edit'] = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;

            $item['fields'] = array();

            if (sizeof($fstruct)>0){
                $fields_show = 0;
                foreach($fstruct as $key=>$value){
                    if ($fields_show < $cat['fields_show']){

                        if ($item['fdata'][$key]){

                            if (mb_strstr($value, '/~h~/')){ $value = str_replace('/~h~/', '', $value); $is_html = true; } else { $is_html = false; }
                            if (mb_strstr($value, '/~m~/')){
                                $value = str_replace('/~m~/', '', $value);
                                $makelink = true;
                            } else {$makelink = false; }
                            if (!$is_html){
                                if (mb_strstr($value, '/~l~/')){
                                    if (@$item['fdata'][$key]!=''){
                                        $field = '<a class="uc_fieldlink" href="/load/url=-'.base64_encode($item['fdata'][$key]).'" target="_blank">'.str_replace('/~l~/', '', $value).'</a> ('.$inCore->fileDownloadCount($item['fdata'][$key]).')';
                                    }
                                } else {
                                    if ($makelink){
                                        $field = $model->getUCSearchLink($cat['id'], $item['fdata'][$key]);
                                    } else {
                                        $field = $item['fdata'][$key];
                                    }
                                }
                            } else {
                                $field = $item['fdata'][$key];
                            }

                            if (isset($query)) { if (mb_stristr($field, $query)) { $field .= '<span class="uc_findsame"> &larr; <i>'.$_LANG['MATCHE'].'</i></span>';} }
                            $fields_show++;

                            $item['fields'][stripslashes($value)] = stripslashes($field);

                        }

                    } else { break; }
                }
            }

            $items[] = $item;
        }

        if (!@$pagemode){
            $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/catalog/'.$id.'-%page%');
        } else {

            if ($pagemode=='findfirst'){
                $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/catalog/'.$id.'-%page%/find-first/'.urlencode(urlencode($query)));
            }

            if ($pagemode=='find'){
                $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/catalog/'.$id.'-%page%/find/'.urlencode(urlencode($query)));
            }

        }

        // SEO
        if($cat['NSLevel'] > 0){

            // meta description
            if($cat['meta_desc']){
                $meta_desc = $cat['meta_desc'];
            } elseif(mb_strlen(strip_tags($cat['description']))>=250){
                $meta_desc = crop($cat['description']);
            } else {
                $meta_desc = $cat['title'];
            }
            $inPage->setDescription($meta_desc);
            // meta keywords
            if($cat['meta_keys']){
                $meta_keys = $cat['meta_keys'];
            } elseif($items){
                foreach($items as $c){
                    $k[] = $c['title'];
                }
                $meta_keys = implode(', ', $k);
            } else {
                $meta_keys = $cat['title'];
            }
            $inPage->setKeywords($meta_keys);

        }

        $tpl->assign('cfg', $cfg)->
              assign('page', $page)->
              assign('search_details', $search_details)->
              assign('fstruct', $fstruct)->
              assign('items', $items)->
              assign('pagebar', $pagebar)->
              display('com_catalog_view.tpl');

        return true;

    }

    //////////////////////////// VIEW ITEM DETAILS ///////////////////////////////////////////////////////////////////////
    if ($do == 'item'){

        $id  = $inCore->request('id', 'int');
        $sql = "SELECT * FROM cms_uc_items WHERE id = '$id'";
        $itemres = $inDB->query($sql) ;

        if (!$inDB->num_rows($itemres)){ cmsCore::error404(); }

        $item = $inDB->fetch_assoc($itemres);

        if ((!$item['published'] || $item['on_moderate']) && !$inUser->is_admin){
            cmsCore::error404();
        }

        $fdata = cmsCore::yamlToArray($item['fieldsdata']);

        if ($item['meta_keys']) { $inPage->setKeywords($item['meta_keys']); }
        if ($item['meta_desc']) { $inPage->setDescription($item['meta_desc']); }

        $ratingdata = ratingData($id);

        $sql = "SELECT * FROM cms_uc_cats WHERE id = '{$item['category_id']}'";
        $catres = $inDB->query($sql) ;
        $cat = $inDB->fetch_assoc($catres);
        $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

        $is_cat_access = $inUser->id ?
                            $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id) : false;
        $item['can_edit'] = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;

        //PATHWAY ENTRY
        $path_list  = $model->getCategoryPath($cat['NSLeft'], $cat['NSRight']);

        if ($path_list){
            foreach($path_list as $pcat){
                $inPage->addPathway($pcat['title'], '/catalog/'.$pcat['id']);
            }
        }
        $inPage->addPathway($item['title'], '/catalog/item'.$item['id'].'.html');

        $inPage->setTitle($item['title']);


        if ($cat['view_type']=='shop'){

            $shopCartLink=shopCartLink();

        }

        //update hits
        $inDB->query("UPDATE cms_uc_items SET hits = hits + 1 WHERE id = '$id'") ;

        //print item details
        $fields = array();

        if (sizeof($fstruct)>0){
            foreach($fstruct as $key=>$value){
                if (@$fdata[$key]){
                    if (mb_strstr($value, '/~h~/')){
                        $value = str_replace('/~h~/', '', $value);
                        $htmlfield = true;
                    }
                    if (mb_strstr($value, '/~m~/')){
                        $value = str_replace('/~m~/', '', $value);
                        $makelink = true;
                    } else {$makelink = false; }
                    $field = (string)str_replace('<p>', '<p style="margin-top:0px; margin-bottom:5px">', $fdata[$key]);
                    if (mb_strstr($value, '/~l~/')){
                        $field = '<a class="uc_detaillink" href="/load/url=-'.base64_encode($field).'" target="_blank">'.str_replace('/~l~/', '', $value).'</a> ('.$inCore->fileDownloadCount($field).')';

                    } else {

                        if (isset($htmlfield)) {
                            if ($makelink) {
                                 $field = $model->getUCSearchLink($cat['id'], $field);
                            } else {
                                //PROCESS FILTERS, if neccessary
                                if ($cat['filters']){
                                    $filters = $inCore->getFilters();
                                    if ($filters){
                                        foreach($filters as $id=>$_data){
                                            require_once PATH.'/filters/'.$_data['link'].'/filter.php';
                                            $_data['link']($field);
                                        }
                                    }
                                }
                                $field =  stripslashes($field);
                            }
                        } else {
                            if ($makelink) {
                                 $field =  $model->getUCSearchLink($cat['id'], $field);
                            }
                        }

                    }
                    $fields[stripslashes($value)] = stripslashes($field);
                }
            }
        }
        if ($cat['view_type']=='shop'){
            $item['price'] = number_format(shopDiscountPrice($item['id'], $item['category_id'], $item['price']), 2, '.', ' ');
        }

        $user = $inDB->get_fields('cms_users', "id='{$item['user_id']}'", 'login, nickname');
        $getProfileLink = cmsUser::getProfileLink($user['login'], $user['nickname']);

        if ($cat['is_ratings']){
            $ratingForm = ratingForm($ratingdata, $item['id']);
        }

        cmsPage::initTemplate('components', 'com_catalog_item')->
                assign('shopCartLink', (isset($shopCartLink) ? $shopCartLink : ''))->
                assign('getProfileLink', $getProfileLink)->
                assign('tagline', tagLine($item['tags'], $cat['id']))->
                assign('item', $item)->
                assign('cat', $cat)->
                assign('fields', $fields)->
                assign('ratingForm', (isset($ratingForm) ? $ratingForm : ''))->
                display('com_catalog_item.tpl');

        if ($item['is_comments'] && $inCore->isComponentEnable('comments')) {
            cmsCore::includeComments();
            comments('catalog', $item['id'], array(), ($inUser->id == $item['user_id']));
        }

        return true;
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// S H O P /////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// ADD TO CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'addcart'){
        shopAddToCart($id, 1);
		$inCore->redirect('/catalog/viewcart.html');
    }
    ///////////////////////// VIEW CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'viewcart'){
        shopCart();
    }
    ///////////////////////// DELETE FROM CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'cartremove'){
        shopRemoveFromCart($id);
		$inCore->redirectBack();
    }
    ///////////////////////// CLEAR CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'clearcart'){
        shopClearCart();
        $inCore->redirectBack();
    }
    ///////////////////////// CLEAR CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'savecart'){
        $itemcounts =  $inCore->request('kolvo', 'array_int');
        if (is_array($itemcounts)){
            shopUpdateCart($itemcounts);
        }
        $inCore->redirectBack();
    }
    ///////////////////////// ORDER //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'order'){
        shopOrder($cfg);
    }
    ///////////////////////// ORDER //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'finish'){
        shopFinishOrder($cfg);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'add_item' || $do == 'edit_item'){

        $cat_id  = cmsCore::request('cat_id', 'int');
        $item_id = cmsCore::request('item_id', 'int', 0);

        if ($do == 'add_item'){

            $cat = $inDB->get_fields('cms_uc_cats', "id='$cat_id'", '*');
            if (!$cat){ cmsCore::error404(); }

            $inPage->setTitle($_LANG['ADD_ITEM']);

            if (!($model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id) || $inUser->is_admin)){
                cmsCore::error404();
            }

            $item  = array();
            $fdata = array();

            if ($cat['cost']=='') { $cat['cost'] = false; }
            if (IS_BILLING){
                cmsBilling::checkBalance('catalog', 'add_catalog_item', false, $cat['cost']);
            }

            $item['is_comments'] = 1;

        }

        if ($do == 'edit_item'){

            $inPage->setTitle($_LANG['EDIT_ITEM']);

            $item = $inDB->get_fields('cms_uc_items', "id='$item_id'", '*');
            if (!$item) { cmsCore::error404(); }

            $cat = $inDB->get_fields('cms_uc_cats', "id='{$item['category_id']}'", '*');
            if (!$cat){ cmsCore::error404(); }

            $is_cat_access  = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id);
            $is_can_edit    = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;
            if (!$is_can_edit) { cmsCore::error404(); }

            $fdata = cmsCore::yamlToArray($item['fieldsdata']);

        }

        $path_list  = $model->getCategoryPath($cat['NSLeft'], $cat['NSRight']);
        if ($path_list){
            foreach($path_list as $pcat){
                $inPage->addPathway($pcat['title'], '/catalog/'.$pcat['id']);
            }
        }
        if($do == 'add_item'){
            $inPage->addPathway($_LANG['ADD_ITEM']);
        } else {
            $inPage->addPathway($_LANG['EDIT_ITEM']);
        }

		$cats = $inCore->getListItems('cms_uc_cats', $cat['id'], 'id', 'ASC', 'parent_id > 0 AND published = 1');

        $fields = array();

        $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

        foreach($fstruct as $f_id=>$value){

            if (mb_strstr($value, '/~h~/')) { $ftype = 'html'; $value=str_replace('/~h~/', '', $value); }
            elseif (mb_strstr($value, '/~l~/')) { $ftype = 'link'; $value=str_replace('/~l~/', '', $value); } else { $ftype='text'; }

            if (mb_strstr($value, '/~m~/')) { $makelink = true; $value=str_replace('/~m~/', '', $value); }
            else { $makelink = false; }

            $next['ftype']    = stripslashes($ftype);
            $next['title']    = stripslashes($value);
            $next['makelink'] = stripslashes($makelink);

            if (!empty($fdata[$f_id])){
                $next['value']  = stripslashes($fdata[$f_id]);
            } else {
                $next['value']  = '';
            }

            $fields[$f_id] = $next;

        }

        cmsPage::initTemplate('components', 'com_catalog_add')->
                assign('do', $do)->
                assign('item', $item)->
                assign('fields', $fields)->
                assign('cat', $cat)->
                assign('cats', $cats)->
                assign('cfg', $cfg)->
                assign('is_admin', $inUser->is_admin)->
                assign('cat_id', $cat['id'])->
                display('com_catalog_add.tpl');

        return;

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'submit_item'){

        $opt     = cmsCore::request('opt', 'str', 'add');
        $new_cat_id = cmsCore::request('new_cat_id', 'int', 0);
        $cat_id = $new_cat_id ? $new_cat_id : cmsCore::request('cat_id', 'int', 0);

        $item_id = cmsCore::request('item_id', 'int', 0);

        $cat = $inDB->get_fields('cms_uc_cats', "id='$cat_id'", '*');
        if(!$cat){ cmsCore::error404(); }

        if ($opt == 'add'){

            if(!$inUser->is_admin &&
                    !$model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id)){
                cmsCore::error404();
            }

        } else {

            $item = $inDB->get_fields('cms_uc_items', "id='{$item_id}'", '*');
            if(!$item){ cmsCore::error404(); }

            if(!$inUser->is_admin &&
                    !($cat['can_edit'] && ($inUser->id == $item['user_id']) &&
                        $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id))){
                cmsCore::error404();
            }

        }

        $item['title'] = cmsCore::request('title', 'str');
        if (!$item['title']) { cmsCore::addSessionMessage($_LANG['NEED_TITLE'], 'error'); cmsCore::redirectBack(); }

        $item['category_id']    = $cat_id;
        $item['published']      = ($cfg['premod'] && !$inUser->is_admin ? 0 : 1);
        $item['on_moderate']    = ($cfg['premod'] && !$inUser->is_admin ? 1 : 0);

        $item['fdata']          = cmsCore::request('fdata', 'array', array());;
        foreach($item['fdata'] as $key=>$value) {
			$item['fdata'][$key] = cmsCore::badTagClear($value);
		}
        $item['fieldsdata']     = $inDB->escape_string(cmsCore::arrayToYaml($item['fdata']));

        $item['is_comments']    = $inUser->is_admin ? cmsCore::request('is_comments', 'int', 0) : $cfg['is_comments'];
        $item['tags']           = cmsCore::request('tags', 'str', '');
        $item['canmany']        = 1;
        $item['imageurl']       = ($opt == 'add' ? '' : $item['imageurl']);
        $item['price']          = 0;
        $item['canmany']        = 1;

        if($inUser->is_admin){
            $meta_desc = cmsCore::request('meta_desc', 'str', '');
            $meta_keys = cmsCore::request('meta_keys', 'str', '');
            $item['meta_desc']  = $meta_desc ? $meta_desc : $item['title'];
            $item['meta_keys']  = $meta_keys ? $meta_keys : $item['tags'];
        } else {
            $item['meta_desc']  = @$item['meta_desc'] ? $item['meta_desc'] : $item['title'];
            $item['meta_keys']  = @$item['meta_keys'] ? $item['meta_keys'] : $item['tags'];
        }

		if (cmsCore::inRequest('price')) {
			$price          = cmsCore::request('price', 'str', '');
			$price          = str_replace(',', '.', $price);
            $item['price']  = round($price, 2);
            $item['canmany']= cmsCore::request('canmany', 'int', 0);
		}

        if (cmsCore::request('delete_img', 'int', 0)){

            @unlink(PATH."/images/catalog/".$item['imageurl']);
            @unlink(PATH."/images/catalog/small/".$item['imageurl']);
            @unlink(PATH."/images/catalog/medium/".$item['imageurl']);

            $item['imageurl'] = '';

        }
        $file = $model->uploadPhoto($item['imageurl']);
        if($file){
            $item['imageurl'] = $file['filename'];
        }

        if ($opt=='add'){

            $item['pubdate'] = date('Y-m-d H:i');
            $item['user_id'] = $inUser->id;

            $item['id'] = $model->addItem($item);

            if (IS_BILLING){
                if ($cat['cost']=='') { $cat['cost'] = false; }
                cmsBilling::process('catalog', 'add_catalog_item', $cat['cost']);
            }

            if (!$cfg['premod'] || $inUser->is_admin) {

                cmsCore::callEvent('ADD_CATALOG_DONE', $item);

                //регистрируем событие
                cmsActions::log('add_catalog', array(
                    'object' => $item['title'],
                    'object_url' => '/catalog/item'.$item['id'].'.html',
                    'object_id' => $item['id'],
                    'target' => $cat['title'],
                    'target_url' => '/catalog/'.$cat['id'],
                    'target_id' => $cat['id'],
                    'description' => ''
                ));
            }
		}
        if ($opt=='edit'){
			$model->updateItem($item['id'], $item);
			cmsActions::updateLog('add_catalog', array('object' => $item['title']), $item['id']);
		}

        if ($inUser->id != 1 && $cfg['premod'] && $cfg['premod_msg']){

            $link = '<a href="/catalog/item'.$item['id'].'.html">'.$item['title'].'</a>';
            $user = '******'.cmsUser::getProfileURL($inUser->login).'">'.$inUser->nickname.'</a>';

            if ($opt=='add')  { $message = $_LANG['MSG_ITEM_SUBMIT']; }
            if ($opt=='edit') { $message = $_LANG['MSG_ITEM_EDITED']; }
            $message = str_replace('%user%', $user, $message);
            $message = str_replace('%link%', $link, $message);

            cmsUser::sendMessage(USER_UPDATER, 1, $message);

            cmsCore::addSessionMessage($_LANG['ITEM_PREMOD_NOTICE'], 'info');

            cmsCore::redirect('/catalog/'.$item['category_id']);

        }

        cmsCore::redirect('/catalog/item'.$item['id'].'.html');

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'accept_item'){

        $item_id = cmsCore::request('item_id', 'int');

        $item = $inDB->get_fields('cms_uc_items', "id='{$item_id}'", 'title, user_id, category_id');
        if (!$item || !$inUser->is_admin){ cmsCore::error404(); }

        $inDB->query("UPDATE cms_uc_items SET published=1, on_moderate=0 WHERE id='{$item_id}'");

		$cat = $inDB->get_fields('cms_uc_cats', 'id='.$item['category_id'], 'id, title');

        cmsCore::callEvent('ADD_CATALOG_DONE', $item);

		//регистрируем событие
		cmsActions::log('add_catalog', array(
				'object' => $item['title'],
				'user_id' => $item['user_id'],
				'object_url' => '/catalog/item'.$item_id.'.html',
				'object_id' => $item_id,
				'target' => $cat['title'],
				'target_url' => '/catalog/'.$cat['id'],
				'target_id' => $cat['id'],
				'description' => ''
		));

        $item_link  = '<a href="/catalog/item'.$item_id.'.html">'.$item['title'].'</a>';

        $message = str_replace('%link%', $item_link, $_LANG['MSG_ITEM_ACCEPTED']);

        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);

        cmsCore::redirectBack();

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'delete_item'){

        $item_id = cmsCore::request('item_id', 'int');

        $item = $inDB->get_fields('cms_uc_items', "id='{$item_id}'", '*');
        if(!$item){ cmsCore::error404(); }

        if (!($item['user_id']==$inUser->id || $inUser->is_admin)){ cmsCore::error404(); }

        $model->deleteItem($item_id);

        $message = str_replace('%item%', $item['title'], $_LANG['MSG_ITEM_REJECTED']);
        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);

        cmsCore::redirect('/catalog/'.$item['category_id']);

    }

}
Beispiel #9
0
function blog()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    cmsCore::loadClass('blog');
    $inBlog = cmsBlogs::getInstance();
    $inBlog->owner = 'site';
    global $_LANG;
    cmsCore::loadModel('blog');
    $model = new cms_model_blog();
    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) {
        cmsCore::loadClass('billing');
    }
    // Проверяем включени ли компонент
    if (!$model->config['component_enabled']) {
        cmsCore::error404();
    }
    //Получаем параметры
    $id = cmsCore::request('id', 'int', 0);
    $post_id = cmsCore::request('post_id', 'int', 0);
    $seolink = cmsCore::request('seolink', 'str', '');
    $do = cmsCore::request('do', 'str', 'blog');
    $page = cmsCore::request('page', 'int', 1);
    $cat_id = cmsCore::request('cat_id', 'int', 0);
    $ownertype = cmsCore::request('ownertype', 'str', '');
    $on_moderate = cmsCore::request('on_moderate', 'int', 0);
    $pagetitle = $inCore->menuTitle();
    $pagetitle = $pagetitle && $inCore->isMenuIdStrict() ? $pagetitle : $_LANG['RSS_BLOGS'];
    $inPage->addPathway($pagetitle, '/blog');
    $inPage->setTitle($pagetitle);
    $inPage->setDescription($pagetitle);
    $blog_id = 25;
    ////////// НАСТРОЙКИ БЛОГА ////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'config') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        // получаем блог
        $blog = $inBlog->getBlog($id);
        if (!$blog) {
            cmsCore::error404();
        }
        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        //Если нет запроса на сохранение, показываем форму настроек блога
        if (!cmsCore::inRequest('goadd')) {
            //Получаем список авторов блога
            $authors = $inBlog->getBlogAuthors($blog['id']);
            $smarty = $inCore->initSmarty('components', 'com_blog_config.tpl');
            $smarty->assign('blog', $blog);
            $smarty->assign('form_action', '/blog/' . $blog['id'] . '/editblog.html');
            $smarty->assign('authors_list', cmsUser::getAuthorsList($authors));
            $smarty->assign('users_list', cmsUser::getUsersList(false, $authors));
            $smarty->assign('is_restrictions', !$inUser->is_admin && $model->config['min_karma']);
            $smarty->assign('cfg', $model->config);
            $smarty->display('com_blog_config.tpl');
            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }
        //Если пришел запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            if (!cmsCore::validateForm()) {
                cmsCore::halt();
            }
            //Получаем настройки
            $title = cmsCore::request('title', 'str');
            $allow_who = cmsCore::request('allow_who', 'str', 'all');
            $ownertype = cmsCore::request('ownertype', 'str', 'single');
            $premod = cmsCore::request('premod', 'int', 0);
            $forall = cmsCore::request('forall', 'int', 1);
            $showcats = cmsCore::request('showcats', 'int', 1);
            $authors = cmsCore::request('authorslist', 'array_int', array());
            //Проверяем настройки
            if (mb_strlen($title) < 5) {
                $title = $blog['title'];
            }
            //Проверяем ограничения по карме (для смены типа блога)
            if ($model->config['min_karma'] && !$inUser->is_admin) {
                // если персональный блог
                if ($ownertype == 'single' && $inUser->karma < $model->config['min_karma_private']) {
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'] . ' <a href="/users/' . $inUser->id . '/karma.html">' . $_LANG['BLOG_KARMS'] . '</a> ' . $_LANG['FOR_CREATE_PERSON_BLOG'] . ' &mdash; ' . $model->config['min_karma_private'] . ', ' . $_LANG['BLOG_HEAVING'] . ' &mdash; ' . $inUser->karma));
                }
                // если коллективный блог
                if ($ownertype == 'multi' && $inUser->karma < $model->config['min_karma_public']) {
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'] . ' <a href="/users/' . $inUser->id . '/karma.html">' . $_LANG['BLOG_KARMS'] . '</a> ' . $_LANG['FOR_CREATE_TEAM_BLOG'] . ' &mdash; ' . $model->config['min_karma_public'] . ', ' . $_LANG['BLOG_HEAVING'] . ' &mdash; ' . $inUser->karma));
                }
            }
            //сохраняем авторов
            $inBlog->updateBlogAuthors($blog['id'], $authors);
            //сохраняем настройки блога
            $blog['seolink_new'] = $inBlog->updateBlog($blog['id'], array('title' => $title, 'allow_who' => $allow_who, 'showcats' => $showcats, 'ownertype' => $ownertype, 'premod' => $premod, 'forall' => $forall), $model->config['update_seo_link_blog']);
            $blog['seolink'] = $blog['seolink_new'] ? $blog['seolink_new'] : $blog['seolink'];
            if (stripslashes($title) != $blog['title']) {
                // обновляем записи постов
                cmsActions::updateLog('add_post', array('target' => $title, 'target_url' => $model->getBlogURL()), 0, $blog['id']);
                // обновляем запись добавления блога
                cmsActions::updateLog('add_blog', array('object' => $title, 'object_url' => $model->getBlogURL()), $blog['id']);
            }
            // Очищаем токен
            cmsUser::clearCsrfToken();
            cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL()));
        }
    }
    ////////// ПРОСМОТР БЛОГА ////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'blog') {
        // получаем блог
        $blog = $inBlog->getBlog($blog_id);
        if (!$blog) {
            cmsCore::error404();
        }
        // Права доступа
        $myblog = $inUser->id && $inUser->id == $blog['user_id'];
        // автор блога
        $is_writer = $inBlog->isUserBlogWriter($blog, $inUser->id);
        // может ли пользователь писать в блог
        // Заполняем head страницы
        $inPage->setTitle($blog['title']);
        //$inPage->addPathway($blog['title'], $model->getBlogURL($blog['seolink']));
        $inPage->setDescription($blog['title']);
        // rss в адресной строке
        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . htmlspecialchars(strip_tags($blog['title'])) . '" href="' . HOST . '/rss/blogs/' . $blog['id'] . '/feed.rss">');
        if ($myblog || $inUser->is_admin) {
            $inPage->addHeadJS('components/blog/js/blog.js');
        }
        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'] . '<br>' . $_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/');
        }
        // Если показываем посты на модерации, если запрашиваем их
        if ($on_moderate) {
            if (!$inUser->is_admin && !($myblog && $blog['ownertype'] == 'multi' && $blog['premod'])) {
                cmsCore::error404();
            }
            $inBlog->whereNotPublished();
            $inPage->setTitle($_LANG['POSTS_ON_MODERATE']);
            $inPage->addPathway($_LANG['POSTS_ON_MODERATE']);
            $blog['title'] .= ' - ' . $_LANG['POSTS_ON_MODERATE'];
        }
        //Получаем html-код ссылки на автора с иконкой его пола
        $blog['author'] = cmsUser::getGenderLink($blog['user_id']);
        // посты данного блога
        $inBlog->whereBlogIs($blog['id']);
        // кроме админов автора в списке только с доступом для всех
        if (!$inUser->is_admin && !$myblog) {
            $inBlog->whereOnlyPublic();
        }
        // если пришла категория
        if ($cat_id) {
            $all_total = $inBlog->getPostsCount($inUser->is_admin || $myblog);
            $inBlog->whereCatIs($cat_id);
        }
        // всего постов
        $total = $inBlog->getPostsCount($inUser->is_admin || $myblog);
        //устанавливаем сортировку
        $inDB->orderBy('p.pubdate', 'DESC');
        $inDB->limitPage($page, $model->config['perpage']);
        // сами посты
        $posts = $inBlog->getPosts($inUser->is_admin || $myblog, $model);
        if (!$posts && $page > 1) {
            cmsCore::error404();
        }
        //Если нужно, получаем список рубрик (категорий) этого блога
        $blogcats = $blog['showcats'] ? $inBlog->getBlogCats($blog['id']) : false;
        //Считаем количество постов, ожидающих модерации
        $on_moderate = ($inUser->is_admin || $myblog) && !$on_moderate ? $inBlog->getModerationCount($blog['id']) : false;
        // админлинки
        $blog['moderate_link'] = $model->getBlogURL() . '/moderate.html';
        $blog['blog_link'] = $model->getBlogURL();
        $blog['add_post_link'] = '/blog/newpost' . ($cat_id ? $cat_id : '') . '.html';
        //Генерируем панель со страницами
        if ($cat_id) {
            $pagination = cmsPage::getPagebar($total, $page, $model->config['perpage'], $blog['blog_link'] . '/page-%page%/cat-' . $cat_id);
        } else {
            $pagination = cmsPage::getPagebar($total, $page, $model->config['perpage'], $blog['blog_link'] . '/page-%page%');
        }
        $smarty = $inCore->initSmarty('components', 'com_blog_view.tpl');
        $smarty->assign('myblog', $myblog);
        $smarty->assign('is_config', true);
        $smarty->assign('is_admin', $inUser->is_admin);
        $smarty->assign('is_writer', $is_writer);
        $smarty->assign('on_moderate', $on_moderate);
        $smarty->assign('cat_id', $cat_id);
        $smarty->assign('blogcats', $blogcats);
        $smarty->assign('total', $total);
        $smarty->assign('all_total', isset($all_total) ? $all_total : 0);
        $smarty->assign('blog', $blog);
        $smarty->assign('posts', $posts);
        $smarty->assign('pagination', $pagination);
        $smarty->display('com_blog_view.tpl');
    }
    ////////// НОВЫЙ ПОСТ / РЕДАКТИРОВАНИЕ ПОСТА //////////////////////////////////////////////////////////////////
    if ($do == 'newpost' || $do == 'editpost') {
        // для редактирования сначала получаем пост
        if ($do == 'editpost') {
            $post = $inBlog->getPost($post_id);
            if (!$post) {
                cmsCore::error404();
            }
            $id = $post['blog_id'];
            $post['tags'] = cmsTagLine('blogpost', $post['id'], false);
        }
        // получаем блог
        $blog = $inBlog->getBlog($blog_id);
        if (!$blog) {
            cmsCore::error404();
        }
        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'] . '<br>' . $_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blog');
        }
        // Права доступа
        $myblog = $inUser->id && $inUser->id == $blog['user_id'];
        // автор блога
        $is_writer = $inBlog->isUserBlogWriter($blog, $inUser->id);
        // может ли пользователь писать в блог
        // если не его блог, пользователь не писатель и не админ, вне зависимости от авторства показываем 404
        if (!$myblog && !$is_writer && !$inUser->is_admin) {
            cmsCore::error404();
        }
        // проверяем является ли пользователь автором, если редактируем пост
        if ($do == 'editpost' && !$inUser->is_admin && $post['user_id'] != $inUser->id) {
            cmsCore::error404();
        }
        //Если еще не было запроса на сохранение
        if (!cmsCore::inRequest('goadd')) {
            $inPage->addPathway($blog['title'], $model->getBlogURL());
            //для нового поста
            if ($do == 'newpost') {
                if (IS_BILLING) {
                    cmsBilling::checkBalance('blogs', 'add_post');
                }
                $inPage->addPathway($_LANG['NEW_POST']);
                $inPage->setTitle($_LANG['NEW_POST']);
                $post = cmsUser::sessionGet('mod');
                if ($post) {
                    cmsUser::sessionDel('mod');
                } else {
                    $post['cat_id'] = $cat_id;
                    $post['comments'] = 1;
                }
            }
            //для редактирования поста
            if ($do == 'editpost') {
                $inPage->addPathway($post['title'], $model->getPostURL('', $post['seolink']));
                $inPage->addPathway($_LANG['EDIT_POST']);
                $inPage->setTitle($_LANG['EDIT_POST']);
            }
            $inPage->initAutocomplete();
            $autocomplete_js = $inPage->getAutocompleteJS('tagsearch', 'tags');
            //получаем рубрики блога
            $cat_list = cmsCore::getListItems('cms_blog_cats', $post['cat_id'], 'id', 'ASC', "blog_id = '{$blog['id']}'");
            //получаем код панелей bbcode и смайлов
            $bb_toolbar = cmsPage::getBBCodeToolbar('message', $model->config['img_on'], 'blogs', 'post', $post_id);
            $smilies = cmsPage::getSmilesPanel('message');
            $inCore->initAutoGrowText('#message');
            //показываем форму
            $smarty = $inCore->initSmarty('components', 'com_blog_edit_post.tpl');
            $smarty->assign('blog', $blog);
            $smarty->assign('pagetitle', $do == 'editpost' ? $_LANG['EDIT_POST'] : $_LANG['NEW_POST']);
            $smarty->assign('mod', $post);
            $smarty->assign('cat_list', $cat_list);
            $smarty->assign('bb_toolbar', $bb_toolbar);
            $smarty->assign('smilies', $smilies);
            $smarty->assign('is_admin', $inUser->is_admin);
            $smarty->assign('myblog', $myblog);
            $smarty->assign('user_can_iscomments', cmsUser::isUserCan('comments/iscomments'));
            $smarty->assign('autocomplete_js', $autocomplete_js);
            $smarty->display('com_blog_edit_post.tpl');
        }
        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            $error = false;
            //Получаем параметры
            $mod['title'] = cmsCore::request('title', 'str');
            $mod['content'] = cmsCore::request('content', 'html');
            $mod['feel'] = cmsCore::request('feel', 'str', '');
            $mod['music'] = cmsCore::request('music', 'str', '');
            $mod['cat_id'] = cmsCore::request('cat_id', 'int');
            $mod['allow_who'] = cmsCore::request('allow_who', 'str', $blog['allow_who']);
            $mod['tags'] = cmsCore::request('tags', 'str', '');
            $mod['comments'] = cmsCore::request('comments', 'int', 1);
            $mod['published'] = $myblog || !$blog['premod'] ? 1 : 0;
            $mod['blog_id'] = $blog['id'];
            //Проверяем их
            if (mb_strlen($mod['title']) < 2) {
                cmsCore::addSessionMessage($_LANG['POST_ERR_TITLE'], 'error');
                $errors = true;
            }
            if (mb_strlen($mod['content']) < 5) {
                cmsCore::addSessionMessage($_LANG['POST_ERR_TEXT'], 'error');
                $errors = true;
            }
            // Если есть ошибки, возвращаемся назад
            if ($errors) {
                cmsUser::sessionPut('mod', $mod);
                cmsCore::redirectBack();
            }
            //Если нет ошибок
            //добавляем новый пост...
            if ($do == 'newpost') {
                if (IS_BILLING) {
                    cmsBilling::process('blogs', 'add_post');
                }
                $mod['pubdate'] = date('Y-m-d H:i:s');
                $mod['user_id'] = $inUser->id;
                // добавляем пост, получая его id и seolink
                $added = $inBlog->addPost($mod);
                if ($mod['published']) {
                    if ($blog['allow_who'] != 'nobody' && $mod['allow_who'] != 'nobody') {
                        cmsActions::log('add_post', array('object' => $mod['title'], 'object_url' => $model->getPostURL('', $added['seolink']), 'object_id' => $added['id'], 'target' => $blog['title'], 'target_url' => $model->getBlogURL(), 'target_id' => $blog['id'], 'description' => '', 'is_friends_only' => (int) ($blog['allow_who'] == 'friends' || $mod['allow_who'] == 'friends')));
                    }
                    cmsCore::addSessionMessage($_LANG['POST_CREATED'], 'success');
                    cmsCore::redirect($model->getPostURL('', $added['seolink']));
                }
                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_POST_SUBMIT']);
                    $message = str_replace('%post%', '<a href="' . $model->getPostURL('', $added['seolink']) . '">' . $mod['title'] . '</a>', $message);
                    $message = str_replace('%blog%', '<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>', $message);
                    cmsUser::sendMessage(USER_UPDATER, $blog['user_id'], $message);
                    cmsCore::addSessionMessage($_LANG['POST_PREMODER_TEXT'], 'info');
                    cmsCore::redirect($model->getBlogURL());
                }
            }
            //...или сохраняем пост после редактирования
            if ($do == 'editpost') {
                if ($model->config['update_date']) {
                    $mod['pubdate'] = date('Y-m-d H:i:s');
                }
                $mod['edit_times'] = (int) $post['edit_times'] + 1;
                $new_post_seolink = $inBlog->updatePost($post['id'], $mod, $model->config['update_seo_link']);
                $post['seolink'] = is_string($new_post_seolink) ? $new_post_seolink : $post['seolink'];
                cmsActions::updateLog('add_post', array('object' => $mod['title'], 'pubdate' => $model->config['update_date'] ? $mod['pubdate'] : $post['pubdate'], 'object_url' => $model->getPostURL('', $post['seolink'])), $post['id']);
                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_POST_UPDATE']);
                    $message = str_replace('%post%', '<a href="' . $model->getPostURL('', $post['seolink']) . '">' . $mod['title'] . '</a>', $message);
                    $message = str_replace('%blog%', '<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>', $message);
                    cmsUser::sendMessage(USER_UPDATER, $blog['user_id'], $message);
                    cmsCore::addSessionMessage($_LANG['POST_PREMODER_TEXT'], 'info');
                } else {
                    cmsCore::addSessionMessage($_LANG['POST_UPDATED'], 'success');
                }
                cmsCore::redirect($model->getPostURL('', $post['seolink']));
            }
        }
    }
    ////////// НОВАЯ РУБРИКА / РЕДАКТИРОВАНИЕ РУБРИКИ //////////////////////////////////////////////////////
    if ($do == 'newcat' || $do == 'editcat') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        // Для редактирования сначала получаем рубрику
        if ($do == 'editcat') {
            $cat = $inBlog->getBlogCategory($cat_id);
            if (!$cat) {
                cmsCore::halt();
            }
            $id = $cat['blog_id'];
        }
        // получаем блог
        $blog = $inBlog->getBlog($id);
        if (!$blog) {
            cmsCore::halt();
        }
        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        //Если нет запроса на сохранение
        if (!cmsCore::inRequest('goadd')) {
            $smarty = $inCore->initSmarty('components', 'com_blog_edit_cat.tpl');
            $smarty->assign('mod', $cat);
            $smarty->assign('form_action', $do == 'newcat' ? '/blog/' . $blog['id'] . '/newcat.html' : '/blog/editcat' . $cat['id'] . '.html');
            $smarty->display('com_blog_edit_cat.tpl');
            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }
        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            if (!cmsCore::validateForm()) {
                cmsCore::halt();
            }
            $new_cat['title'] = cmsCore::request('title', 'str', '');
            $new_cat['description'] = cmsCore::request('description', 'str', '');
            $new_cat['blog_id'] = $blog['id'];
            if (mb_strlen($new_cat['title']) < 3) {
                cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CAT_ERR_TITLE']));
            }
            //новая рубрика
            if ($do == 'newcat') {
                $cat['id'] = $inBlog->addBlogCategory($new_cat);
                cmsCore::addSessionMessage($_LANG['CAT_IS_ADDED'], 'success');
            }
            //редактирование рубрики
            if ($do == 'editcat') {
                $inBlog->updateBlogCategory($cat['id'], $new_cat);
                cmsCore::addSessionMessage($_LANG['CAT_IS_UPDATED'], 'success');
            }
            cmsUser::clearCsrfToken();
            cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL(1, $cat['id'])));
        }
    }
    ///////////////////////// УДАЛЕНИЕ РУБРИКИ /////////////////////////////////////////////////////////////////////////
    if ($do == 'delcat') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $cat = $inBlog->getBlogCategory($cat_id);
        if (!$cat) {
            cmsCore::halt();
        }
        $blog = $inBlog->getBlog($cat['blog_id']);
        if (!$blog) {
            cmsCore::halt();
        }
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        if (!cmsCore::validateForm()) {
            cmsCore::halt();
        }
        $inBlog->deleteBlogCategory($cat['id']);
        cmsCore::addSessionMessage($_LANG['CAT_IS_DELETED'], 'success');
        cmsUser::clearCsrfToken();
        cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL()));
    }
    ////////////////////////// ПРОСМОТР ПОСТА /////////////////////////////////////////////////////////////////////////
    if ($do == 'post') {
        $post = $inBlog->getPost($seolink);
        if (!$post) {
            cmsCore::error404();
        }
        $blog = $inBlog->getBlog($post['blog_id']);
        if (!$blog) {
            cmsCore::error404();
        }
        // право просмотра блога
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'] . '<br>' . $_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blog');
        }
        // право просмотра самого поста
        if (!cmsUser::checkUserContentAccess($post['allow_who'], $post['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_POST'] . '<br>' . $_LANG['CLOSED_POST_TEXT'], 'error');
            cmsCore::redirect($model->getBlogURL());
        }
        if ($inUser->id) {
            $inPage->addHeadJS('components/blog/js/blog.js');
        }
        $inPage->addPathway($blog['title'], $model->getBlogURL());
        $inPage->setTitle($post['title']);
        $inPage->addPathway($post['title']);
        $inPage->setDescription($post['title']);
        if ($post['cat_id']) {
            $cat = $inBlog->getBlogCategory($post['cat_id']);
        }
        $post['tags'] = cmsTagBar('blogpost', $post['id']);
        $is_author = $inUser->id && $inUser->id == $post['user_id'];
        $smarty = $inCore->initSmarty('components', 'com_blog_view_post.tpl');
        $smarty->assign('post', $post);
        $smarty->assign('blog', $blog);
        $smarty->assign('cat', $cat);
        $smarty->assign('is_author', $is_author);
        $smarty->assign('myblog', $inUser->id && $inUser->id == $blog['user_id']);
        $smarty->assign('is_admin', $inUser->is_admin);
        $smarty->assign('karma_form', cmsKarmaForm('blogpost', $post['id'], $post['rating'], $is_author));
        $smarty->assign('navigation', $inBlog->getPostNavigation($post['id'], $blog['id'], $model, $blog['seolink']));
        $smarty->display('com_blog_view_post.tpl');
        if ($inCore->isComponentInstalled('comments') && $post['comments']) {
            cmsCore::includeComments();
            comments('blog', $post['id']);
        }
    }
    ///////////////////////// УДАЛЕНИЕ ПОСТА /////////////////////////////////////////////////////////////////////////////
    if ($do == 'delpost') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $post = $inBlog->getPost($post_id);
        if (!$post) {
            cmsCore::halt();
        }
        $blog = $inBlog->getBlog($post['blog_id']);
        if (!$blog) {
            cmsCore::halt();
        }
        // удалять могут авторы, авторы блога, админы
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin && $inUser->id != $post['user_id']) {
            cmsCore::halt();
        }
        if (!cmsCore::validateForm()) {
            cmsCore::halt();
        }
        $inBlog->deletePost($post['id']);
        if ($inUser->id != $post['user_id']) {
            cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'] . ' <b>&laquo;' . $post['title'] . '&raquo;</b> ' . $_LANG['WAS_DELETED_FROM_BLOG'] . ' <b>&laquo;<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>&raquo;</b>');
        }
        cmsCore::addSessionMessage($_LANG['POST_IS_DELETED'], 'success');
        cmsUser::clearCsrfToken();
        cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL()));
    }
    ///////////////////////// ПУБЛИКАЦИЯ ПОСТА /////////////////////////////////////////////////////////////////////////
    if ($do == 'publishpost') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $post = $inBlog->getPost($post_id);
        if (!$post) {
            cmsCore::halt();
        }
        $blog = $inBlog->getBlog($post['blog_id']);
        if (!$blog) {
            cmsCore::halt();
        }
        // публикуют авторы блога и админы
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        $inBlog->publishPost($post_id);
        if ($blog['allow_who'] == 'all' && $post['allow_who'] == 'all') {
            cmsCore::callEvent('ADD_POST_DONE', $post);
        }
        $post['seolink'] = $model->getPostURL('', $post['seolink']);
        if ($blog['allow_who'] != 'nobody' && $post['allow_who'] != 'nobody') {
            cmsActions::log('add_post', array('object' => $post['title'], 'user_id' => $post['user_id'], 'object_url' => $post['seolink'], 'object_id' => $post['id'], 'target' => $blog['title'], 'target_url' => $model->getBlogURL(), 'target_id' => $blog['id'], 'description' => '', 'is_friends_only' => (int) ($blog['allow_who'] == 'friends' || $post['allow_who'] == 'friends')));
        }
        cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'] . ' <b>&laquo;<a href="' . $post['seolink'] . '">' . $post['title'] . '</a>&raquo;</b> ' . $_LANG['PUBLISHED_IN_BLOG'] . ' <b>&laquo;<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>&raquo;</b>');
        cmsCore::halt('ok');
    }
    ////////// VIEW POPULAR POSTS ////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'best') {
        $inPage->setTitle($_LANG['POPULAR_IN_BLOGS']);
        $inPage->addPathway($_LANG['POPULAR_IN_BLOGS']);
        $inPage->setDescription($_LANG['POPULAR_IN_BLOGS']);
        // кроме админов в списке только с доступом для всех
        if (!$inUser->is_admin) {
            $inBlog->whereOnlyPublic();
        }
        // ограничиваем по рейтингу если надо
        if ($model->config['list_min_rating']) {
            $inBlog->ratingGreaterThan($model->config['list_min_rating']);
        }
        // всего постов
        $total = $inBlog->getPostsCount($inUser->is_admin);
        //устанавливаем сортировку
        $inDB->orderBy('p.rating', 'DESC');
        $inDB->limitPage($page, $model->config['perpage']);
        // сами посты
        $posts = $inBlog->getPosts($inUser->is_admin, $model);
        if (!$posts && $page > 1) {
            cmsCore::error404();
        }
        $smarty = $inCore->initSmarty('components', 'com_blog_view_posts.tpl');
        $smarty->assign('pagetitle', $_LANG['POPULAR_IN_BLOGS']);
        $smarty->assign('total', $total);
        $smarty->assign('ownertype', $ownertype);
        $smarty->assign('posts', $posts);
        $smarty->assign('pagination', cmsPage::getPagebar($total, $page, $model->config['perpage'], '/blogs/popular-%page%.html'));
        $smarty->assign('cfg', $model->config);
        $smarty->display('com_blog_view_posts.tpl');
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    $inCore->executePluginRoute($do);
}