示例#1
0
            
            <label><input type="checkbox" id="is_access" name="is_access" onclick="checkAccesList()" value="1" <?php echo $public; ?> /> <?php echo $_LANG['AD_ALL_GROUPS']; ?></label>
            
            <div class="help-block"><?php echo $_LANG['AD_SELECT_MULTIPLE_CTRL']; ?>.</div>
        </div>
        
        <div class="form-group">
            <label><?php echo $_LANG['AD_FORUM_MODERATORS']; ?>:</label>
            <?php
            if ($mod['moder_list']) {
                $public = '';
                $style  = '';

                $moder_list = $inCore->yamlToArray($mod['moder_list']);
                if ($moder_list) {
                    $moder_list = cmsUser::getAuthorsList($moder_list, $moder_list);
                }
            }

            echo '<select id="users_list" class="form-control" name="users_list">';
            echo cmsUser::getUsersList();
            echo '</select> <div><a class="ajaxlink" href="javascript:" onclick="addModer()">'. $_LANG['AD_ADD_SELECTED'] .'</a></div>';
            ?>

            <select id="moder_list" class="form-control" name="moder_list[]" size="8" multiple>
                <?php if ($moder_list) { echo $moder_list; } ?>
            </select>  <div><a class="ajaxlink" href="javascript:" onclick="deleteModer()"><?php echo $_LANG['AD_DELETE_SELECTED']; ?></a></div>
            <div class="help-block"><?php echo $_LANG['AD_FORUM_HINT']; ?>.</div>
        </div>
        
        <div class="form-group">
示例#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();
    }

}
示例#3
0
        <tr>
            <td width="606">
                <p id="nomembers" style="display:<?php 
    @$mod['clubtype'] == 'public' ? 'block' : 'none';
    ?>
">Клуб открыт для всех, поэтому каждый зарегистрированный пользователь может стать его участником.</p>
                <div id="members">
                    <table width="100%" border="0" align="center" cellpadding="10" cellspacing="0" style="display:<?php 
    @$mod['clubtype'] == 'public' ? 'none' : 'block';
    ?>
">
                        <tr>
                            <td align="center" valign="top"><strong>Участники клуба: </strong><br/>
                                <select name="memberslist[]" size="12" multiple="multiple" id="memberslist" style="width:200px">
                                    <?php 
    echo cmsUser::getAuthorsList($members);
    ?>
                            </select>                    </td>
                            <td align="center"><div>
                                    <input name="member_add" type="button" id="member_add" value="&lt;&lt;" />
                                </div>
                                <div>
                                    <input name="member_remove" type="button" id="member_remove" value="&gt;&gt;" style="margin-top:4px" />
                            </div></td>
                            <td align="center" valign="top"><strong>Все пользователи:</strong><br/>
                                <select name="userslist2" size="12" multiple="multiple" id="userslist2" style="width:200px">
                                    <?php 
    echo cmsUser::getUsersList(false, array_merge($moderators, $members));
    ?>
                                </select>
                            </td>
示例#4
0
function clubs() {
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB   = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();

    global $_LANG;

    $model = new cms_model_clubs();

    $inPhoto = $model->initPhoto();

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

	// js только авторизованным
	if($inUser->id){
		$inPage->addHeadJS('components/clubs/js/clubs.js');
	}

	$pagetitle = $inCore->getComponentTitle();

	$id   = cmsCore::request('id', 'int', 0);
	$do   = $inCore->do;
	$page = cmsCore::request('page', 'int', 1);

	$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);
	$inPage->addPathway($pagetitle, '/clubs');
    $inPage->addHeadJsLang(array('NO_PUBLISH','EDIT_PHOTO','YOU_REALLY_DELETE_PHOTO','YOU_REALLY_DELETE_ALBUM','RENAME_ALBUM','ALBUM_TITLE','ADD_PHOTOALBUM','REALY_EXIT_FROM_CLUB','JOINING_CLUB','SEND_MESSAGE','CREATE','CREATE_CLUB','SEND_INVITE_CLUB','YOU_NO_SELECT_USER'));

//////////////////////// КЛУБЫ ПОЛЬЗОВАТЕЛЯ/////////////////////////////////////
if ($do == 'user_clubs') {
    if (!cmsCore::isAjax()) { return false; }

    $inPage->displayLangJS(array('CREATE','CREATE_CLUB'));

    $user_id = cmsCore::request('user_id', 'int', $inUser->id);

    $user = cmsUser::getShortUserData($user_id);
    if (!$user) { return false; }

    // получаем клубы, в которых пользователь админ
    $model->whereAdminIs($user['id']);
   	$inDB->orderBy('c.pubdate', 'DESC');
    $clubs = $model->getClubs();

    // получаем клубы, в которых состоит пользователь
    $inDB->addSelect('uc.role');
    $inDB->addJoin("INNER JOIN cms_user_clubs uc ON uc.club_id = c.id AND uc.user_id = '{$user['id']}'");
   	$inDB->orderBy('uc.role', 'DESC, uc.pubdate DESC');
    $inclubs = $model->getClubs();

	cmsPage::initTemplate('components', 'com_clubs_user')->
            assign('can_create', (($inUser->id == $user['id']) && ($model->config['cancreate'] || $inUser->is_admin)))->
            assign('clubs', array_merge($clubs, $inclubs))->
            assign('user', $user)->
            assign('my_profile', $user['id'] == $inUser->id)->
            display();

}
//////////////////////// ВСЕ КЛУБЫ /////////////////////////////////////////////
if ($do=='view'){

	$inDB->orderBy('is_vip', 'DESC, rating DESC');
	$inDB->limitPage($page, $model->config['perpage']);

	$total = $model->getClubsCount();

        $clubs = $model->getClubs();
	if (!$clubs && $page > 1) { return false; }
        
        if ($page > 1) {
            foreach ($clubs as $c) {
                $keys[] = $c['title'];
            }
            $inPage->setKeywords(implode(',', $keys));
        }

	cmsPage::initTemplate('components', 'com_clubs_view')->
            assign('pagetitle', $pagetitle)->
            assign('can_create', ($inUser->id && $model->config['cancreate'] || $inUser->is_admin))->
            assign('clubs', $clubs)->
            assign('total', $total)->
            assign('pagination', cmsPage::getPagebar($total, $page, $model->config['perpage'], '/clubs/page-%page%'))->
            display();

}
/////////////////////// ПРОСМОТР КЛУБА /////////////////////////////////////////
if ($do=='club'){
    $club = $model->getClub($id);
    if (!$club) { return false; }

    if (!$club['published'] && !$inUser->is_admin) { return false; }

    $inPage->setTitle($club['pagetitle'] ? $club['pagetitle'] : $club['title']);
    $inPage->setKeywords($club['meta_keys'] ? $club['meta_keys'] : $club['title']);
    if (!$club['meta_desc']) {
        if ($club['description']) {
            $inPage->setDescription(crop($club['description']));
        } else {
            $inPage->setDescription($club['title']);
        }
    } else {
        $inPage->setDescription($club['meta_desc']);
    }
        
    $inPage->addPathway($club['title']);
    $inPage->addHeadJsLang(array('NEW_POST_ON_WALL','CONFIRM_DEL_POST_ON_WALL'));

    // Инициализируем участников клуба
    $model->initClubMembers($club['id']);
    // права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub('member');

	// Приватный или публичный клуб
    $is_access = true;
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        $is_access = false;
    }

	// Общее количество участников
    $club['members'] = $model->club_total_members;
	// Общее количество участников
    $club['moderators'] = $model->club_total_moderators;

	// Массив членов клуба
	if($club['members']){
		$inDB->limit($model->config['club_perpage']);
		$club['members_list'] = $model->getClubMembers($club['id'], 'member');
	} else { $club['members_list'] =  array(); }

	// Массив модераторов клуба
	if($club['moderators']){
		$club['moderators_list'] = $model->getClubMembers($club['id'], 'moderator');
	}

	// Стена клуба
	// количество записей на стене берем из настроек
	$inDB->limitPage(1, $model->config['wall_perpage']);
    $club['wall_html'] = cmsUser::getUserWall($club['id'], 'clubs', ($is_moder || $is_admin), ($is_moder || $is_admin));

	/////////////////////////////////////////////
	//////////// ПОСТЫ БЛОГА КЛУБА //////////////
	/////////////////////////////////////////////
	if ($club['enabled_blogs']){

		$inBlog = $model->initBlog();

		$inBlog->whereBlogUserIs($club['id']);

		$club['total_posts'] = $inBlog->getPostsCount($is_admin || $is_moder);

		$inDB->addSelect('b.user_id as bloglink');

		$inDB->orderBy('p.pubdate', 'DESC');

		$inDB->limit($model->config['club_posts_perpage']);

		$club['blog_posts'] = $inBlog->getPosts(($is_admin || $is_moder), $model, true);

	}

	/////////////////////////////////////////////
	//////////// ФОТОАЛЬБОМЫ КЛУБА //////////////
	/////////////////////////////////////////////
	if ($club['enabled_photos']){

		// Общее количество альбомов
		$club['all_albums'] = $inDB->rows_count('cms_photo_albums', "NSDiffer = 'club{$club['id']}' AND user_id = '{$club['id']}' AND parent_id > 0");

		// получаем альбомы
		if($club['all_albums']){
			$inDB->limit($model->config['club_album_perpage']);
			$inDB->orderBy('f.pubdate', 'DESC');
			$club['photo_albums'] = $inPhoto->getAlbums(0, 'club'.$club['id']);
		} else {
			$club['photo_albums'] = array();
		}

	}

	// Получаем плагины
        $plugins = cmsCore::callTabEventPlugins('GET_SINGLE_CLUB', $club);

	cmsPage::initTemplate('components', 'com_clubs_view_club')->
            assign('club', $club)->
            assign('is_access', $is_access)->
            assign('user_id', $inUser->id)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('plugins', $plugins)->
            assign('is_member', $is_member)->
            assign('is_photo_karma_enabled', ((($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false))->
            assign('is_blog_karma_enabled', ((($inUser->karma >= $club['blog_min_karma']) && $is_member) ? true : false))->
            assign('cfg', $model->config)->
            display();

}
///////////////////////// СОЗДАНИЕ КЛУБА ///////////////////////////////////////
if ($do == 'create'){

    if(!cmsCore::isAjax()) { return false; }

    if(!$inUser->id){ return false; }

    $can_create = $model->canCreate();

	// показываем форму
    if (!cmsCore::inRequest('create') ){

        cmsPage::initTemplate('components', 'com_clubs_create')->
                assign('can_create', $can_create)->
                assign('last_message', $model->last_message)->
                display();

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

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

        if (!$can_create){ return false; }

        $title    = $inCore->request('title', 'str');
        $clubtype = $inCore->request('clubtype', 'str');

        if (!$title || !in_array($clubtype, array('public','private'))){
			cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CLUB_REQ_TITLE']));
		}

		if ($inDB->get_field('cms_clubs', "LOWER(title) = '".mb_strtolower($title)."'", 'id')){
			cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CLUB_EXISTS']));
		}

		if(!cmsUser::checkCsrfToken()) { return false; }

		$club_id = $model->addClub(array('admin_id'=>$inUser->id,
										 'title'=>$title,
										 'clubtype'=>$clubtype,
										 'create_karma'=>$inUser->karma,
										 'enabled_blogs'=>$model->config['enabled_blogs'],
										 'enabled_photos'=>$model->config['enabled_photos']));

		if($club_id){
			//регистрируем событие
			cmsActions::log('add_club', array(
						'object' => $title,
						'object_url' => '/clubs/'.$club_id,
						'object_id' => $club_id,
						'target' => '',
						'target_url' => '',
						'target_id' => 0,
						'description' => ''
			));
		}

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

		cmsCore::jsonOutput(array('error' => false,
								'club_id' => $club_id));

    }

}

///////////////////////// НАСТРОЙКИ КЛУБА //////////////////////////////////////
if ($do == 'config'){

    if (!$inUser->id){ return false; }

    $club = $model->getClub($id);
    if (!$club){ return false; }

    // Инициализируем участников клуба
    $model->initClubMembers($club['id']);
    // настраивать клуб могут только администраторы
    $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    if (!$is_admin){ return false; }

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

        if (!cmsUser::checkCsrfToken()) { return false; }

        $description = cmsCore::badTagClear(cmsCore::request('description', 'html', ''));
        $new_club['description']      = $inDB->escape_string($description);
        $new_club['title']            = cmsCore::request('title', 'str', $club['title']);
        $new_club['clubtype']         = cmsCore::request('clubtype', 'str', 'public');
        $new_club['maxsize']          = cmsCore::request('maxsize', 'int', 0);
        $new_club['blog_min_karma']   = cmsCore::request('blog_min_karma', 'int', 0);
        $new_club['photo_min_karma']  = cmsCore::request('photo_min_karma', 'int', 0);
        $new_club['album_min_karma']  = cmsCore::request('album_min_karma', 'int', 0);
        $new_club['blog_premod']      = cmsCore::request('blog_premod', 'int', 0);
        $new_club['photo_premod']     = cmsCore::request('photo_premod', 'int', 0);
        $new_club['join_karma_limit'] = cmsCore::request('join_karma_limit', 'int', 0);
        $new_club['join_min_karma']   = cmsCore::request('join_min_karma', 'int', 0);
        if ($model->config['seo_user_access'] || $inUser->is_admin) {
            $new_club['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
            $new_club['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
            $new_club['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
        }

        // загружаем изображение клуба
        $new_imageurl = $model->uploadClubImage($club['imageurl']);
        $new_club['imageurl'] = @$new_imageurl['filename'] ? $new_imageurl['filename'] : $club['imageurl'];

        // Сохраняем
        $model->updateClub($club['id'], $new_club);

        // Обновляем ленту активности
        cmsActions::updateLog('add_club', array('object' => $new_club['title']), $club['id']);
        cmsActions::updateLog('add_club_user', array('object' => $new_club['title']), $club['id']);

        if ($inUser->is_admin && IS_BILLING){
            $is_vip    = cmsCore::request('is_vip', 'int', 0);
            $join_cost = cmsCore::request('join_cost', 'int', 0);
            $model->setVip($club['id'], $is_vip, $join_cost);
        }

        $moders  = cmsCore::request('moderslist', 'array_int', array());
        $members = cmsCore::request('memberslist', 'array_int', array());

        $all_users = array_merge($members, $moders);

        // Сохраняем пользователей
        $model->clubSaveUsers($club['id'], $all_users);
        $model->clubSetRole($club['id'], $moders, 'moderator');

        // Кешируем количество
        $model->setClubMembersCount($club['id']);

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

        cmsCore::redirect('/clubs/'.$club['id']);

    }

    if (!cmsCore::inRequest('save')){

        // Заголовки и пафвей
        $inPage->addPathway($club['title'], '/clubs/'.$club['id']);
        $inPage->addPathway($_LANG['CONFIG_CLUB']);
        $inPage->setTitle($_LANG['CONFIG_CLUB']);

		// Список друзей, отсутствующих в клубе
		$friends_list = '';
		// массив id друзей не в клубе
		$friends_ids  = array();

		// Получаем список друзей
		$friends = cmsUser::getFriends($inUser->id);
		// Получаем список участников
		$members = $model->getClubMembersIds();
		// Формируем список друзей, которые еще не в клубе
		foreach($friends as $key=>$friend){
			if (!in_array($friend['id'], $members) && $friend['id'] != $club['admin_id']){
				$friends_list .= '<option value="'.$friend['id'].'">'.$friend['nickname'].'</option>';
				$friends_ids[] = $friend['id'];
			}
		}

		// Получаем модераторов клуба
		$moderators = $model->getClubMembersIds('moderator');
		// формируем список друзья не в клубе + участники клуба кроме модераторов
		$fr_plus_members = $members ? array_merge($friends_ids, $members) : $friends_ids;
		// Убираем модераторов если они есть
		$fr_plus_members = $moderators ? array_diff($fr_plus_members, $moderators) : $fr_plus_members;

		// Формируем список option друзей (которые еще не в этом клубе) и участников
		if ($fr_plus_members) { $fr_members_list = cmsUser::getAuthorsList($fr_plus_members); } else { $fr_members_list = ''; }
		// Формируем список option участников клуба
        if ($moderators) { $moders_list = cmsUser::getAuthorsList($moderators); } else { $moders_list = ''; }
        if ($members) { $members_list = cmsUser::getAuthorsList($members); } else { $members_list = ''; }

        cmsPage::initTemplate('components', 'com_clubs_config')->
            assign('club', $club)->
            assign('moders_list', $moders_list)->
            assign('members_list', $members_list)->
            assign('friends_list', $friends_list)->
            assign('fr_members_list', $fr_members_list)->
            assign('is_billing', IS_BILLING)->
            assign('is_admin', $inUser->is_admin)->
            assign('cfg', $model->config)->
            display();
    }

}
///////////////////////// ВЫХОД ИЗ КЛУБА ///////////////////////////////////////////
if ($do == 'leave'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// Выйти из клуба могут только его участники
    $is_admin  = $inUser->id == $club['admin_id'];
    $is_member = $model->checkUserRightsInClub();
	if ($is_admin || !$is_member){ cmsCore::halt(); }

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

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

		cmsCore::callEvent('LEAVE_CLUB', $club);

        $model->removeUserFromClub($club['id'], $inUser->id);
		// Пересчитываем рейтинг
        $model->setClubRating($club['id']);
		// Кешируем (пересчитываем) количество участников
		$model->setClubMembersCount($club['id']);
		// Добавляем событие в ленте активности
		cmsActions::removeObjectLog('add_club_user', $club['id'], $inUser->id);
		cmsCore::addSessionMessage($_LANG['YOU_LEAVE_CLUB'].'"'.$club['title'].'"', 'success');

		cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/clubs/'.$club['id']));

    }

}
///////////////////////// ВСТУПЛЕНИЕ В КЛУБ ////////////////////////////////////
if ($do == 'join'){

	if (!$inUser->id){ cmsCore::halt(); }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	// В приватный клуб участников добавляет администратор
    if ($club['clubtype']=='private'){ cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// проверяем наличие пользователя в клубе
    $is_admin  = $inUser->id == $club['admin_id'];
    $is_member = $model->checkUserRightsInClub();
	if ($is_admin || $is_member){ cmsCore::halt(); }

    // Проверяем ограничения на количество участников
    if ($club['maxsize'] && ($model->club_total_members >= $club['maxsize']) && !$inUser->is_admin){
        cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['CLUB_SIZE_LIMIT']));
    }
    // Проверяем ограничения по карме на вступление
    if($club['join_karma_limit'] && ($inUser->karma < $club['join_min_karma']) && !$inUser->is_admin){

        cmsCore::jsonOutput(array('error' => true, 'text'  => '<p><strong>'.$_LANG['NEED_KARMA_TEXT'].'</strong></p><p>'.$_LANG['NEEDED'].' '.$club['join_min_karma'].', '.$_LANG['HAVE_ONLY'].' '.$inUser->karma.'.</p><p>'.$_LANG['WANT_SEE'].' <a href="/users/'.$inUser->id.'/karma.html">'.$_LANG['HISTORY_YOUR_KARMA'].'</a>?</p>'));

    }

    //
    // Обработка заявки
    //
    if (cmsCore::inRequest('confirm')){

		cmsCore::callEvent('JOIN_CLUB', $club);

        //списываем оплату если клуб платный
        if (IS_BILLING && $club['is_vip'] && $club['join_cost'] && !$inUser->is_admin){
            if ($inUser->balance >= $club['join_cost']){
                //если средств на балансе хватает
                cmsBilling::pay($inUser->id, $club['join_cost'], sprintf($_LANG['VIP_CLUB_BUY_JOIN'], $club['title']));
            } else {
                //недостаточно средств, создаем тикет
                //и отправляем оплачивать
                $billing_ticket = array(
                    'action' => sprintf($_LANG['VIP_CLUB_BUY_JOIN'], $club['title']),
                    'cost'   => $club['join_cost'],
                    'amount' => $club['join_cost'] - $inUser->balance,
                    'url'    => $_SERVER['REQUEST_URI'].'?confirm=1'
                );
                cmsUser::sessionPut('billing_ticket', $billing_ticket);
				cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/billing/pay'));
            }
        }

        //добавляем пользователя в клуб
        $model->addUserToClub($club['id'], $inUser->id);
		// Пересчитываем рейтинг клуба
        $model->setClubRating($club['id']);
		// Кешируем (пересчитываем) количество участников
		$model->setClubMembersCount($club['id']);

		//регистрируем событие
		cmsActions::log('add_club_user', array(
						'object' => $club['title'],
						'object_url' => '/clubs/'.$club['id'],
						'object_id' => $club['id'],
						'target' => '',
						'target_url' => '',
						'target_id' => 0,
						'description' => ''
		));

		cmsCore::addSessionMessage($_LANG['YOU_JOIN_CLUB'].'"'.$club['title'].'"', 'success');

		if($_SERVER['REQUEST_URI'] != '/clubs/'.$club['id'].'/join.html'){
			cmsCore::redirect('/clubs/'.$club['id']);
		} else {
	        cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/clubs/'.$club['id']));
		}

    }

    //
    // Форма подтверждения заявки
    //
    if (!cmsCore::inRequest('confirm')){

        $text = '<p>'.$_LANG['YOU_REALY_JOIN_TO'].' <strong>"'.$club['title'].'"</strong>?</p>';
        if ($club['is_vip'] && $club['join_cost'] && !$inUser->is_admin){
            $text .= '<p>'.$_LANG['VIP_CLUB_JOIN_COST'].' &mdash; <strong>'.$club['join_cost'].' '.$_LANG['BILLING_POINT10'].'</strong></p>';
        }

        cmsCore::jsonOutput(array('error' => false, 'text'  => $text));

    }

}
///////////////////// РАССЫЛКА СООБЩЕНИЯ УЧАСТНИКАМ ////////////////////////////
if ($do == 'send_message'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// Расылать могут только участники и администраторы
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
	if (!$is_admin){ cmsCore::halt(); }

	if (!cmsCore::inRequest('gosend')){

        $inPage->setRequestIsAjax();

		cmsPage::initTemplate('components', 'com_clubs_messages_member')->
                assign('club', $club)->
                assign('bbcodetoolbar', cmsPage::getBBCodeToolbar('message'))->
                assign('smilestoolbar', cmsPage::getSmilesPanel('message'))->
                display();

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

	} else {

		// Здесь не эскейпим, в методе sendMessage эскейпится
		$message = cmsCore::parseSmiles(cmsCore::request('content', 'html', ''), true);

		$moderators_list = $model->getClubMembersIds('moderator');
		$members_list    = $model->getClubMembersIds();
		$result_list 	 = cmsCore::inRequest('only_mod') ? $moderators_list : $members_list;

		if (mb_strlen($message)<3){
			cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['ERR_SEND_MESS']));
		}
		if (!$result_list){
			cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['ERR_SEND_MESS_NO_MEMBERS']));
		}

        if (!cmsUser::checkCsrfToken()) { return false; }

		$message = str_replace('%club%', '<a href="/clubs/'.$club['id'].'">'.$club['title'].'</a>', $_LANG['MESSAGE_FROM ADMIN']).$message;

		cmsUser::sendMessages(USER_UPDATER, $result_list, $message);

		$info = cmsCore::inRequest('only_mod') ? $_LANG['SEND_MESS_TO_MODERS_OK'] : $_LANG['SEND_MESS_TO_MEMBERS_OK'];

		cmsCore::jsonOutput(array('error' => false, 'text' => $info));

	}

}

///////////////////////// ПРИГЛАСИТЬ ДРУЗЕЙ В КЛУБ /////////////////////////////
if ($do == 'join_member'){

    if (!$inUser->id) { return false; }

    if (!cmsCore::isAjax()) { return false; }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	if (!$club['published'] && !$inUser->is_admin) { cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// Расылать могут только участники и администраторы
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_member = $model->checkUserRightsInClub();
	if (!$is_admin && !$is_member){ cmsCore::halt(); }
	// В приватный клуб приглашения не рассылаем
    if ($club['clubtype']=='private'){ cmsCore::halt(); }

	// Получаем список друзей
	$friends = cmsUser::getFriends($inUser->id);
	// Получаем список участников
	$members = $model->getClubMembersIds();
	// Проверяем наличие друга в списке участников клуба или является ли он администратором
	foreach($friends as $key=>$friend){
		if (in_array($friend['id'], $members) || $friend['id'] == $club['admin_id']) { unset($friends[$key]); }
	}
	// Если нет друзей или все друзья уже в этом клубе, то выводим ошибку и возвращаемся назад
	if (!$friends){
		cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['SEND_INVITE_ERROR']));
	}

	// показываем форму для приглашения
	if (!cmsCore::inRequest('join')){

		// Выводим шаблон
		cmsPage::initTemplate('components', 'com_clubs_join_member')->
                assign('club', $club)->
                assign('friends', $friends)->
                display();

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

	} else { // Приглашаем

	  	$users = cmsCore::request('users', 'array_int', array());

		if ($users){

			$club_link = '<a href="/clubs/'.$club['id'].'">'.$club['title'].'</a>';
			$user_link = cmsUser::getProfileLink($inUser->login, $inUser->nickname);
			$link_join = '<a href="/clubs/'.$club['id'].'">'.$_LANG['JOIN_CLUB'] .'</a>';

			$message   = str_replace(array('%user%','%club%','%link_join%'),
                                     array($user_link,$club_link,$link_join), $_LANG['INVITE_CLUB_TEXT']);

			cmsUser::sendMessages(USER_UPDATER, $users, $message);

		}

		cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['SEND_INVITE_OK']));

	}

}
///////////////////////// ПРОСМОТР УЧАСТНИКОВ //////////////////////////////////
if ($do=='members'){

	$club = $model->getClub($id);
	if(!$club){ return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

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

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub();

	// Приватный или публичный клуб
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        return false;
    }

	// Общее количество участников
    $total_members = $model->club_total_members;

	// Массив членов клуба
	if($total_members){
		$inDB->limitPage($page, $model->config['member_perpage']);
		$members = $model->getClubMembers($club['id']);
		if(!$members) { return false; }
	} else { return false; }

	$pagebar = cmsPage::getPagebar($total_members, $page, $model->config['member_perpage'], '/clubs/%id%/members-%page%', array('id'=>$club['id']));

	cmsPage::initTemplate('components', 'com_clubs_view_member')->
            assign('pagebar', $pagebar)->
            assign('page', $page)->
            assign('members', $members)->
            assign('club', $club)->
            assign('total_members', $total_members)->
            display();

}
////////////////////////////// ВСЕ АЛЬБОМЫ КЛУБА  //////////////////////////////
if ($do=='view_albums'){

	$club = $model->getClub($id);
	if(!$club){ return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	$pagetitle = $_LANG['PHOTOALBUMS'].' - '.$club['title'];

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

    // Инициализируем участников клуба
    $model->initClubMembers($club['id']);
    // права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub('member');

    $is_karma_enabled = (($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false;

	// Приватный или публичный клуб
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        return false;
    }

	$inDB->orderBy('f.pubdate', 'DESC');
	$club['photo_albums'] = $inPhoto->getAlbums(0, 'club'.$club['id']);
	if(!$club['photo_albums']) { return false; }
        
        // SEO
        $inPage->setDescription($pagetitle);
        $keys = array($club['title'], $_LANG['PHOTOALBUMS']);
        foreach ($club['photo_albums'] as $p) {
            $keys[] = $p['title'];
        }
        $inPage->setKeywords(implode(',', $keys));

	cmsPage::initTemplate('components', 'com_clubs_albums')->
            assign('club', $club)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('is_karma_enabled', $is_karma_enabled)->
            assign('show_title', true)->
            assign('pagetitle', $pagetitle)->
            display();

}
///////////////////////// ПРОСМОТР АЛЬБОМА КЛУБА ///////////////////////////////
if ($do=='view_album'){

	// Получаем альбом
	$album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null);
	if (!$album) { return false; }

	// Неопубликованные альбомы показываем только админам
	if (!$album['published'] && !$inUser->is_admin) { return false; }
        
        if ($album['NSDiffer'] != 'club'. $album['user_id']) { return false; }

	// получаем клуб
	$club = $model->getClub($album['user_id']);
	if(!$club) { return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub();

	// Приватный или публичный клуб
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        return false;
    }

	$hidden = (bool)($is_admin || $is_moder);

	// Устанавливаем альбом
	$inPhoto->whereAlbumIs($album['id']);

    // Общее количество фото по заданным выше условиям
    $total = $inPhoto->getPhotosCount($hidden);

    //устанавливаем сортировку
    $inDB->orderBy('f.id', 'DESC');

    //устанавливаем номер текущей страницы и кол-во фото на странице
    $inDB->limitPage($page, $model->config['photo_perpage']);

    $photos = $inPhoto->getPhotos($hidden);
    if (!$photos && $page > 1) { cmsCore::error404(); }

    $inPage->addPathway($club['title'], '/clubs/'.$club['id']);
    $inPage->addPathway($album['title'], '/clubs/photoalbum'.$album['id']);
    $inPage->setTitle($album['title']);
    $inPage->setDescription($album['title'].' - '.$_LANG['CLUB_PHOTO_ALBUM'].' "'.$club['title'].'"');
    
    $keys = array($album['title'], $club['title']);
    if ($photos) {
        foreach ($photos as $p) {
            $keys[] = $p['title'];
        }
    }
    $inPage->setKeywords(implode(',', $keys));

    cmsPage::initTemplate('components', 'com_clubs_view_album')->
            assign('club', $club)->
            assign('total', $total)->
            assign('album', $album)->
            assign('photos', $photos)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('is_member', $is_member)->
            assign('cfg', $model->config)->
            assign('pagebar', cmsPage::getPagebar($total, $page, $model->config['photo_perpage'], '/clubs/photoalbum'.$album['id'].'/page-%page%'))->
            display();

}
///////////////////////// УДАЛЕНИЕ АЛЬБОМА /////////////////////////////////////
if ($do=='delete_album'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

    if(!cmsUser::checkCsrfToken()) { return false; }

	$album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null);
	if (!$album) { cmsCore::halt(); }

	$club = $model->getClub($album['user_id']);
	if(!$club) { cmsCore::halt(); }

	$model->initClubMembers($club['id']);

    $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder = $model->checkUserRightsInClub('moderator');

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

	$inPhoto->deleteAlbum($album['id'], 'club'.$club['id'], $model->initUploadClass());

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

	cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/'.$club['id']));

}
//////////////////////////////// ПРОСМОТР ФОТО /////////////////////////////////
if ($do=='view_photo'){

	// Получаем фото
	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { return false; }

	$photo = cmsCore::callEvent('VIEW_CLUB_PHOTO', $photo);

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub();
	$is_author = $photo['user_id'] == $inUser->id;

	if (!$photo['published'] && !$is_admin && !$is_moder) { return false; }

	// Фото приватного клуба показываем только участникам
    if ($club['clubtype']=='private' && !$is_member && !$is_admin){ return false; }

    $inPage->addPathway($club['title'], '/clubs/'. $club['id']);
    $inPage->addPathway($photo['cat_title'], '/clubs/photoalbum'.$photo['album_id']);
    $inPage->addPathway($photo['title']);
    $inPage->setTitle($photo['pagetitle'] ? $photo['pagetitle'] : $photo['title']);
    $inPage->setKeywords($photo['meta_keys'] ? $photo['meta_keys'] : $photo['title']);
    if (!$photo['meta_desc']) {
        if ($photo['description']) {
            $inPage->setDescription(crop($photo['description']));
        } else {
            $inPage->setDescription($photo['title']);
        }
    } else {
        $inPage->setDescription($photo['meta_desc']);
    } 

	// ссылки вперед назад
	$photo['nextid'] = $inDB->get_fields('cms_photo_files', 'id<'.$photo['id'].' AND album_id = '.$photo['album_id'], 'id, file, title', 'id DESC');
	$photo['previd'] = $inDB->get_fields('cms_photo_files', 'id>'.$photo['id'].' AND album_id = '.$photo['album_id'], 'id, file, title', 'id ASC');

	// кнопки голосования
	$photo['karma_buttons'] = cmsKarmaButtons('club_photo', $photo['id'], $photo['rating'], $is_author);

	// Обновляем кол-во просмотров
	if(!$is_author){
		$inDB->setFlag('cms_photo_files', $photo['id'], 'hits', $photo['hits']+1);
	}

	// выводим в шаблон
    cmsPage::initTemplate('components', 'com_clubs_view_photo')->
            assign('club', $club)->
            assign('photo', $photo)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('is_exists_original', (file_exists(PATH.'/images/photos/'. $photo['file'])))->
            assign('is_author', $is_author)->
            display();

	//если есть, выводим комментарии
	if ($photo['comments'] && $inCore->isComponentEnable('comments')) {
            cmsCore::includeComments();
            comments('club_photo', $photo['id'], array(), $is_author);
	}

}
////////////////////////////// УДАЛИТЬ ФОТО ////////////////////////////////////
if ($do=='delete_photo'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	if(!cmsUser::checkCsrfToken()) { return false; }

	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { cmsCore::halt(); }

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder = $model->checkUserRightsInClub('moderator');

	// удалять могут только модераторы и администраторы
	if(!$is_admin && !$is_moder) { cmsCore::halt(); }

	$inPhoto->deletePhoto($photo, $model->initUploadClass());

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

	cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/photoalbum'.$photo['album_id']));

}
///////////////////////// РЕДАКТИРОВАТЬ ФОТО ///////////////////////////////////
if ($do=='edit_photo'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { cmsCore::halt(); }

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { cmsCore::halt(); }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
	$is_author = $photo['user_id'] == $inUser->id;

	if(!$is_admin && !$is_moder && !$is_author) { cmsCore::halt(); }

	if (!cmsCore::inRequest('edit_photo')){

		cmsPage::initTemplate('components', 'com_photos_edit')->
                assign('photo', $photo)->
                assign('form_action', '/clubs/editphoto'.$photo['id'].'.html')->
                assign('no_tags', true)->
                assign('is_admin', ($is_admin || $is_moder))->
                display();

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

	} else {

		$mod['title']       = cmsCore::request('title', 'str', '');
		$mod['title']       = $mod['title'] ? $mod['title'] : $photo['title'];
		$mod['description'] = cmsCore::request('description', 'str', '');
		$mod['comments']    = ($is_admin || $is_moder) ? cmsCore::request('comments', 'int') : $photo['comments'];
                
                if ($model->config['seo_user_access'] || $inUser->is_admin) {
                    $mod['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
                    $mod['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
                    $mod['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
                }

		$file = $model->initUploadClass()->uploadPhoto($photo['file']);
		$mod['file'] = $file['filename'] ? $file['filename'] : $photo['file'];

		$inPhoto->updatePhoto($mod, $photo['id']);

		$description = '<a href="/clubs/photo'.$photo['id'].'.html" class="act_photo"><img border="0" src="/images/photos/small/'.$mod['file'].'" /></a>';

		cmsActions::updateLog('add_photo_club', array('object' => $mod['title'], 'description' => $description), $photo['id']);

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

		cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/photo'.$photo['id'].'.html'));

	}

}
/////////////////////////////// PHOTO PUBLISH //////////////////////////////////
if ($do=='publish_photo'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { cmsCore::halt(); }

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { cmsCore::halt(); }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');

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

	$inPhoto->publishPhoto($photo['id']);

	$description = $club['clubtype']=='private' ? '' :
				   '<a href="/clubs/photo'.$photo['id'].'.html" class="act_photo"><img border="0" src="/images/photos/small/'.$photo['file'].'" /></a>';

	cmsActions::log('add_photo_club', array(
		  'object' => $photo['title'],
		  'object_url' => '/clubs/photo'.$photo['id'].'.html',
		  'object_id' => $photo['id'],
          'user_id' => $photo['user_id'],
		  'target' => $club['title'],
		  'target_id' => $photo['album_id'],
		  'target_url' => '/clubs/'.$club['id'],
		  'description' => $description
	));

	cmsCore::halt('ok');

}
///////////////////////// ЗАГРУЗКА ФОТО ////////////////////////////////////////
if ($do=='add_photo'){

	// Неавторизованных просим авторизоваться
	if (!$inUser->id) { cmsUser::goToLogin(); }

	$do_photo = cmsCore::request('do_photo', 'str', 'addphoto');

	$album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null);
	if (!$album) { return false; }

	if (!$album['published'] && !$inUser->is_admin) { return false; }

	$club = $model->getClub($album['user_id']);
	if(!$club) { return false; }

	// если фотоальбомы запрещены
	if(!$club['enabled_photos']){ return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub('member');

    $is_karma_enabled = (($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false;

    if(!$is_karma_enabled && !$is_admin && !$is_moder) {
        cmsCore::addSessionMessage('<p><strong>'.$_LANG['NEED_KARMA_PHOTO'].'</strong></p><p>'.$_LANG['NEEDED'].' '.$club['photo_min_karma'].', '.$_LANG['HAVE_ONLY'].' '.$inUser->karma.'.</p><p>'.$_LANG['WANT_SEE'].' <a href="/users/'.$inUser->id.'/karma.html">'.$_LANG['HISTORY_YOUR_KARMA'].'</a>?</p>', 'error');
        cmsCore::redirectBack();
    }

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

    return include 'components/clubs/add_photo.php';
}
///////////////////////// БЛОГИ КЛУБОВ /////////////////////////////////////////
if ($do == 'club_blogs') {
    $bdo     = cmsCore::request('bdo', 'str', 'view_clubs_posts');
    $post_id = cmsCore::request('post_id', 'int', 0);
    $cat_id  = cmsCore::request('cat_id', 'int', 0);
    $seolink = cmsCore::request('seolink', 'str', '');
    $on_moderate = cmsCore::request('on_moderate', 'int', 0);

    $inBlog = $model->initBlog();
    $inPage->addHeadJsLang(array('NEW_CAT','RENAME_CAT','YOU_REALY_DELETE_CAT','YOU_REALY_DELETE_POST','NO_PUBLISHED'));

    return include 'components/clubs/club_blogs.php';
}

}
示例#5
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);
}