示例#1
0
function cmsTagBar($target, $item_id, $selected=''){
    if ($tagline = cmsTagLine($target, $item_id, true, $selected)){
        return '<div class="taglinebar"><span class="label">Теги: </span><span class="tags">'.$tagline.'</span></div>';
    } else {
        return '';
    }
}
示例#2
0
文件: plugin.php 项目: Acsac/CMS-RuDi
    private function eventGetArticle($item) {
        global $_LANG;

        $item_id = $item['id'];
        $tag_arr = explode(', ', cmsTagLine('content', $item_id, false));
        $id_target = array();

        // Получаем id назначения таких же тегов, не более пяти на каждый
        foreach ($tag_arr as $tag) {
            $sql = "SELECT item_id FROM cms_tags WHERE tag = '$tag' AND item_id<>'$item_id' AND target='content' LIMIT 5";
            $rs = cmsCore::c('db')->query($sql) ;
            if (cmsCore::c('db')->num_rows($rs)) {
                while ($tagitem = cmsCore::c('db')->fetch_assoc($rs)) {
                    $id_target[]= $tagitem['item_id'];
                }
            }
        }

        if (count($id_target)) {
            $id_target	= array_unique($id_target);
            $id_target 	= array_slice($id_target, 0, $this->config['P_LIMIT']);
            if ($this->config['P_UNSORT']) { shuffle($id_target); }

            $morecontent = '';
            foreach ($id_target as $n) {
                $con = cmsTagItemLink('content', $n);
                if ($con) {
                    $morecontent .= '<p>'. $con ."</p>";
                }
            }
            if ($morecontent) { $item['content'] .= '<h4>'. $_LANG['P_SIMILAR_ARTICLES'] .':</h4>'. $morecontent; }
        }
        
        return $item;
    }
示例#3
0
function cmsTagBar($target, $item_id, $selected = '')
{
    global $_LANG;
    if ($tagline = cmsTagLine($target, $item_id, true, $selected)) {
        return '<div class="taglinebar"><i class="fa fa-tags fa-lg"></i> <span class="label">' . $_LANG['TAGS'] . ': </span><span class="tags">' . $tagline . '</span></div>';
    } else {
        return '';
    }
}
示例#4
0
 /**
  * Получает посты по условиям
  * @param bool $show_all
  * @param obj $ownerModel
  * @return array $posts
  */
 public function getPosts($show_all = false, $ownerModel, $is_short = false)
 {
     $pub_where = $show_all ? '1=1' : 'p.published = 1';
     if (isset($this->owner)) {
         $pub_where .= " AND b.owner = '{$this->owner}'";
     }
     $sql = "SELECT p.*,\r\n                       u.nickname as author, u.login, u.is_deleted,\r\n                       b.allow_who as blog_allow_who,\r\n                       b.seolink as bloglink,\r\n                       b.title as blog_title,\r\n                       b.owner as owner {$this->inDB->select}\r\n                FROM cms_blog_posts p\r\n\t\t\t\tINNER JOIN cms_blogs b ON b.id = p.blog_id\r\n\t\t\t\tLEFT JOIN cms_users u ON u.id = p.user_id\r\n\t\t\t\t{$this->inDB->join}\r\n                WHERE {$pub_where}\r\n\t\t\t\t      {$this->inDB->where}\r\n                {$this->inDB->group_by}\r\n                {$this->inDB->order_by}\n";
     if ($this->inDB->limit) {
         $sql .= "LIMIT {$this->inDB->limit}";
     }
     $result = $this->inDB->query($sql);
     $this->inDB->resetConditions();
     if (!$this->inDB->num_rows($result)) {
         return false;
     }
     $posts = array();
     while ($post = $this->inDB->fetch_assoc($result)) {
         $post['fpubdate'] = cmsCore::dateFormat($post['pubdate']);
         $post['url'] = $ownerModel->getPostURL($post['bloglink'], $post['seolink']);
         $post['blog_url'] = $ownerModel->getBlogURL($post['bloglink']);
         //Разбиваем текст поста на 2 части по тегу [cut=...] и оставляем только первую из них
         if (mb_strstr($post['content_html'], '[cut')) {
             $post['content_html'] = $this->getPostShort($post['content_html'], $post['url']);
         }
         if (!$is_short) {
             $post['tagline'] = cmsTagLine($this->getTarget('tags'), $post['id']);
         }
         // если захотим получать аватар владельца
         if (isset($post['imageurl'])) {
             $post['author_avatar'] = cmsUser::getUserAvatarUrl($post['user_id'], 'small', $post['imageurl'], $post['is_deleted']);
         }
         $posts[] = $post;
     }
     return cmsCore::callEvent('GET_POSTS', $posts);
 }
示例#5
0
function content()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    $model = new cms_model_content();
    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) {
        cmsCore::loadClass('billing');
    }
    global $_LANG;
    $id = cmsCore::request('id', 'int', 0);
    $do = $inCore->do;
    $seolink = cmsCore::strClear(urldecode(cmsCore::request('seolink', 'html', '')));
    if (is_numeric($seolink)) {
        cmsCore::error404();
    }
    $page = cmsCore::request('page', 'int', 1);
    ///////////////////////////////////// VIEW CATEGORY ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'view') {
        $cat = $inDB->getNsCategory('cms_category', $seolink);
        // если не найдена категория и мы не на главной, 404
        if (!$cat && $inCore->menuId() !== 1) {
            cmsCore::error404();
        }
        // языки
        $cat = translations::process(cmsConfig::getConfig('lang'), 'content_category', $cat);
        // Плагины
        $cat = cmsCore::callEvent('GET_CONTENT_CAT', $cat);
        // Неопубликованные показываем только админам
        if (!$cat['published'] && !$inUser->is_admin) {
            cmsCore::error404();
        }
        // Проверяем доступ к категории
        if (!$inCore->checkUserAccess('category', $cat['id'])) {
            cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
            cmsCore::redirect('/content');
        }
        // если не корень категорий
        if ($cat['NSLevel'] > 0) {
            $inPage->setTitle($cat['pagetitle'] ? $cat['pagetitle'] : $cat['title']);
            $pagetitle = $cat['title'];
            $showdate = $cat['showdate'];
            $showcomm = $cat['showcomm'];
            $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . htmlspecialchars($cat['title']) . '" href="' . HOST . '/rss/content/' . $cat['id'] . '/feed.rss">');
        }
        // Если корневая категория
        if ($cat['NSLevel'] == 0) {
            if ($model->config['hide_root']) {
                cmsCore::error404();
            }
            $inPage->setTitle($_LANG['CATALOG_ARTICLES']);
            $pagetitle = $_LANG['CATALOG_ARTICLES'];
            $showdate = 1;
            $showcomm = 1;
        }
        // Получаем дерево категорий
        $path_list = $inDB->getNsCategoryPath('cms_category', $cat['NSLeft'], $cat['NSRight'], 'id, title, NSLevel, seolink, url');
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'content_category', $path_list);
            foreach ($path_list as $pcat) {
                if (!$inCore->checkUserAccess('category', $pcat['id'])) {
                    cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
                    cmsCore::redirect('/content');
                }
                $inPage->addPathway($pcat['title'], $model->getCategoryURL(null, $pcat['seolink']));
            }
        }
        // Получаем подкатегории
        $subcats_list = $model->getSubCats($cat['id']);
        // Привязанный фотоальбом
        $cat_photos = $model->getCatPhotoAlbum($cat['photoalbum']);
        // Получаем статьи
        // Редактор/администратор
        $is_editor = $cat['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd') || $inUser->is_admin;
        // Условия
        $model->whereCatIs($cat['id']);
        // Общее количество статей
        $total = $model->getArticlesCount($is_editor);
        // Сортировка и разбивка на страницы
        $inDB->orderBy($cat['orderby'], $cat['orderto']);
        $inDB->limitPage($page, $model->config['perpage']);
        // Получаем статьи
        $content_list = $total ? $model->getArticlesList(!$is_editor) : array();
        $inDB->resetConditions();
        if (!$content_list && $page > 1) {
            cmsCore::error404();
        }
        $pagebar = cmsPage::getPagebar($total, $page, $model->config['perpage'], $model->getCategoryURL(null, $cat['seolink'], 0, true));
        $template = $cat['tpl'] ? $cat['tpl'] : 'com_content_view.tpl';
        if ($cat['NSLevel'] > 0) {
            // meta description
            if ($cat['meta_desc']) {
                $meta_desc = $cat['meta_desc'];
            } elseif (mb_strlen(strip_tags($cat['description'])) >= 250) {
                $meta_desc = crop($cat['description']);
            } else {
                $meta_desc = $cat['title'];
            }
            $inPage->setDescription($meta_desc);
            // meta keywords
            if ($cat['meta_keys']) {
                $meta_keys = $cat['meta_keys'];
            } elseif ($content_list) {
                foreach ($content_list as $c) {
                    $k[] = $c['title'];
                }
                $meta_keys = implode(', ', $k);
            } else {
                $meta_keys = $cat['title'];
            }
            $inPage->setKeywords($meta_keys);
        }
        cmsPage::initTemplate('components', $template)->assign('cat', $cat)->assign('is_homepage', (bool) ($inCore->menuId() == 1))->assign('showdate', $showdate)->assign('showcomm', $showcomm)->assign('pagetitle', $pagetitle)->assign('subcats', $subcats_list)->assign('cat_photos', $cat_photos)->assign('articles', $content_list)->assign('pagebar', $pagebar)->display($template);
    }
    ///////////////////////////////////// READ ARTICLE ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'read') {
        // Получаем статью
        $article = $model->getArticle($seolink);
        if (!$article) {
            cmsCore::error404();
        }
        $article = translations::process(cmsConfig::getConfig('lang'), 'content_content', $article);
        $article = cmsCore::callEvent('GET_ARTICLE', $article);
        $is_admin = $inUser->is_admin;
        $is_author = $inUser->id == $article['user_id'];
        $is_author_del = cmsUser::isUserCan('content/delete');
        $is_editor = $article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd');
        // если статья не опубликована или дата публикации позже, 404
        if ((!$article['published'] || strtotime($article['pubdate']) > time()) && !$is_admin && !$is_editor && !$is_author) {
            cmsCore::error404();
        }
        if (!$inCore->checkUserAccess('material', $article['id'])) {
            cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
            cmsCore::redirect($model->getCategoryURL(null, $article['catseolink']));
        }
        // увеличиваем кол-во просмотров
        if (@(!$is_author)) {
            $inDB->setFlag('cms_content', $article['id'], 'hits', $article['hits'] + 1);
        }
        // Картинка статьи
        $article['image'] = file_exists(PATH . '/images/photos/medium/article' . $article['id'] . '.jpg') ? 'article' . $article['id'] . '.jpg' : '';
        // Заголовок страницы
        $article['pagetitle'] = $article['pagetitle'] ? $article['pagetitle'] : $article['title'];
        // Тело статьи в зависимости от настроек
        $article['content'] = $model->config['readdesc'] ? $article['description'] . $article['content'] : $article['content'];
        // Дата публикации
        $article['pubdate'] = cmsCore::dateFormat($article['pubdate']);
        // Шаблон статьи
        $article['tpl'] = $article['tpl'] ? $article['tpl'] : 'com_content_read.tpl';
        $inPage->setTitle($article['pagetitle']);
        // Получаем дерево категорий
        $path_list = $article['showpath'] ? $inDB->getNsCategoryPath('cms_category', $article['leftkey'], $article['rightkey'], 'id, title, NSLevel, seolink, url') : array();
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'content_category', $path_list);
            foreach ($path_list as $pcat) {
                if (!$inCore->checkUserAccess('category', $pcat['id'])) {
                    cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
                    cmsCore::redirect('/content');
                }
                $inPage->addPathway($pcat['title'], $model->getCategoryURL(null, $pcat['seolink']));
            }
        }
        $inPage->addPathway($article['title']);
        // Мета теги KEYWORDS и DESCRIPTION
        if ($article['meta_keys']) {
            $inPage->setKeywords($article['meta_keys']);
        } else {
            if (mb_strlen($article['content']) > 30) {
                $inPage->setKeywords(cmsCore::getKeywords(cmsCore::strClear($article['content'])));
            }
        }
        if (mb_strlen($article['meta_desc'])) {
            $inPage->setDescription($article['meta_desc']);
        }
        // Выполняем фильтры
        $article['content'] = cmsCore::processFilters($article['content']);
        // Разбивка статей на страницы
        $pt_pages = array();
        if (!empty($GLOBALS['pt'])) {
            foreach ($GLOBALS['pt'] as $num => $page_title) {
                $pt_pages[$num]['title'] = $page_title;
                $pt_pages[$num]['url'] = $model->getArticleURL(null, $article['seolink'], $num + 1);
            }
        }
        // Рейтинг статьи
        if ($model->config['rating'] && $article['canrate']) {
            $karma = cmsKarma('content', $article['id']);
            $karma_points = cmsKarmaFormatSmall($karma['points']);
            $btns = cmsKarmaButtonsText('content', $article['id'], $karma['points'], $is_author);
        }
        cmsPage::initTemplate('components', $article['tpl'])->assign('article', $article)->assign('cfg', $model->config)->assign('page', $page)->assign('is_pages', !empty($GLOBALS['pt']))->assign('pt_pages', $pt_pages)->assign('is_admin', $is_admin)->assign('is_editor', $is_editor)->assign('is_author', $is_author)->assign('is_author_del', $is_author_del)->assign('tagbar', cmsTagBar('content', $article['id']))->assign('karma_points', @$karma_points)->assign('karma_votes', @$karma['votes'])->assign('karma_buttons', @$btns)->display($article['tpl']);
        // Комментарии статьи
        if ($article['published'] && $article['comments'] && $inCore->isComponentInstalled('comments')) {
            cmsCore::includeComments();
            comments('article', $article['id'], array(), $is_author);
        }
    }
    ///////////////////////////////////// ADD ARTICLE //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'addarticle' || $do == 'editarticle') {
        $is_add = cmsUser::isUserCan('content/add');
        // может добавлять статьи
        $is_auto_add = cmsUser::isUserCan('content/autoadd');
        // добавлять статьи без модерации
        if (!$is_add && !$is_auto_add) {
            cmsCore::error404();
        }
        // Для редактирования получаем статью и проверяем доступ
        if ($do == 'editarticle') {
            // Получаем статью
            $item = $model->getArticle($id);
            if (!$item) {
                cmsCore::error404();
            }
            $pubcats = array();
            // доступ к редактированию админам, авторам и редакторам
            if (!$inUser->is_admin && $item['user_id'] != $inUser->id && !($item['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd'))) {
                cmsCore::error404();
            }
        }
        // Для добавления проверяем не вводили ли мы данные ранее
        if ($do == 'addarticle') {
            $item = cmsUser::sessionGet('article');
            if ($item) {
                cmsUser::sessionDel('article');
            }
            // Категории, в которые разрешено публиковать
            $pubcats = $model->getPublicCats();
            if (!$pubcats) {
                cmsCore::addSessionMessage($_LANG['ADD_ARTICLE_ERR_CAT'], 'error');
                cmsCore::redirectBack();
            }
        }
        // не было запроса на сохранение, показываем форму
        if (!cmsCore::inRequest('add_mod')) {
            $dynamic_cost = false;
            // Если добавляем статью
            if ($do == 'addarticle') {
                $pagetitle = $_LANG['ADD_ARTICLE'];
                $inPage->setTitle($pagetitle);
                $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
                $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
                $inPage->addPathway($_LANG['MY_ARTICLES'], '/content/my.html');
                $inPage->addPathway($pagetitle);
                // поддержка биллинга
                if (IS_BILLING) {
                    $action = cmsBilling::getAction('content', 'add_content');
                    foreach ($pubcats as $p => $pubcat) {
                        if ($pubcat['cost']) {
                            $dynamic_cost = true;
                        } else {
                            $pubcats[$p]['cost'] = $action['point_cost'][$inUser->group_id];
                        }
                    }
                    cmsBilling::checkBalance('content', 'add_content', $dynamic_cost);
                }
            }
            // Если редактируем статью
            if ($do == 'editarticle') {
                $pagetitle = $_LANG['EDIT_ARTICLE'];
                $inPage->setTitle($pagetitle);
                $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
                if ($item['user_id'] != $inUser->id) {
                    $user = $inDB->get_fields('cms_users', "id='{$item['user_id']}'", 'login, nickname');
                    $inPage->addPathway($user['nickname'], cmsUser::getProfileURL($user['login']));
                } else {
                    $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
                }
                $inPage->addPathway($_LANG['MY_ARTICLES'], '/content/my.html');
                $inPage->addPathway($pagetitle);
                $item['tags'] = cmsTagLine('content', $item['id'], false);
                $item['image'] = file_exists(PATH . '/images/photos/small/article' . $item['id'] . '.jpg') ? 'article' . $item['id'] . '.jpg' : '';
                if (!$is_auto_add) {
                    cmsCore::addSessionMessage($_LANG['ATTENTION'] . ': ' . $_LANG['EDIT_ARTICLE_PREMODER'], 'info');
                }
            }
            $inPage->initAutocomplete();
            $autocomplete_js = $inPage->getAutocompleteJS('tagsearch', 'tags');
            $item = cmsCore::callEvent('PRE_EDIT_ARTICLE', @$item ? $item : array());
            cmsPage::initTemplate('components', 'com_content_edit')->assign('mod', $item)->assign('do', $do)->assign('cfg', $model->config)->assign('pubcats', $pubcats)->assign('pagetitle', $pagetitle)->assign('is_admin', $inUser->is_admin)->assign('is_billing', IS_BILLING)->assign('dynamic_cost', $dynamic_cost)->assign('autocomplete_js', $autocomplete_js)->display('com_content_edit.tpl');
        }
        // Пришел запрос на сохранение статьи
        if (cmsCore::inRequest('add_mod')) {
            $errors = false;
            $article['category_id'] = cmsCore::request('category_id', 'int', 1);
            $article['user_id'] = $item['user_id'] ? $item['user_id'] : $inUser->id;
            $article['title'] = cmsCore::request('title', 'str', '');
            $article['tags'] = cmsCore::request('tags', 'str', '');
            $article['description'] = cmsCore::request('description', 'html', '');
            $article['content'] = cmsCore::request('content', 'html', '');
            $article['description'] = cmsCore::badTagClear($article['description']);
            $article['content'] = cmsCore::badTagClear($article['content']);
            $article['published'] = $is_auto_add ? 1 : 0;
            if ($do == 'editarticle') {
                $article['published'] = $item['published'] == 0 ? $item['published'] : $article['published'];
            }
            $article['pubdate'] = $do == 'editarticle' ? $item['pubdate'] : date('Y-m-d H:i');
            $article['enddate'] = $do == 'editarticle' ? $item['enddate'] : $article['pubdate'];
            $article['is_end'] = $do == 'editarticle' ? $item['is_end'] : 0;
            $article['showtitle'] = $do == 'editarticle' ? $item['showtitle'] : 1;
            $article['meta_desc'] = $do == 'addarticle' ? mb_strtolower($article['title']) : $inDB->escape_string($item['meta_desc']);
            $article['meta_keys'] = $do == 'addarticle' ? $inCore->getKeywords($article['content']) : $inDB->escape_string($item['meta_keys']);
            $article['showdate'] = $do == 'editarticle' ? $item['showdate'] : 1;
            $article['showlatest'] = $do == 'editarticle' ? $item['showlatest'] : 1;
            $article['showpath'] = $do == 'editarticle' ? $item['showpath'] : 1;
            $article['comments'] = $do == 'editarticle' ? $item['comments'] : 1;
            $article['canrate'] = $do == 'editarticle' ? $item['canrate'] : 1;
            $article['pagetitle'] = '';
            if ($do == 'editarticle') {
                $article['tpl'] = $item['tpl'];
            }
            if (mb_strlen($article['title']) < 2) {
                cmsCore::addSessionMessage($_LANG['REQ_TITLE'], 'error');
                $errors = true;
            }
            if (mb_strlen($article['content']) < 10) {
                cmsCore::addSessionMessage($_LANG['REQ_CONTENT'], 'error');
                $errors = true;
            }
            if ($errors) {
                // При добавлении статьи при ошибках сохраняем введенные поля
                if ($do == 'addarticle') {
                    cmsUser::sessionPut('article', $article);
                }
                cmsCore::redirectBack();
            }
            $article['description'] = $inDB->escape_string($article['description']);
            $article['content'] = $inDB->escape_string($article['content']);
            $article = cmsCore::callEvent('AFTER_EDIT_ARTICLE', $article);
            // добавление статьи
            if ($do == 'addarticle') {
                $article_id = $model->addArticle($article);
            }
            // загрузка фото
            $file = 'article' . (@$article_id ? $article_id : $item['id']) . '.jpg';
            if (cmsCore::request('delete_image', 'int', 0)) {
                @unlink(PATH . "/images/photos/small/{$file}");
                @unlink(PATH . "/images/photos/medium/{$file}");
            }
            // Загружаем класс загрузки фото
            cmsCore::loadClass('upload_photo');
            $inUploadPhoto = cmsUploadPhoto::getInstance();
            // Выставляем конфигурационные параметры
            $inUploadPhoto->upload_dir = PATH . '/images/photos/';
            $inUploadPhoto->small_size_w = $model->config['img_small_w'];
            $inUploadPhoto->medium_size_w = $model->config['img_big_w'];
            $inUploadPhoto->thumbsqr = $model->config['img_sqr'];
            $inUploadPhoto->is_watermark = $model->config['watermark'];
            $inUploadPhoto->input_name = 'picture';
            $inUploadPhoto->filename = $file;
            // Процесс загрузки фото
            $inUploadPhoto->uploadPhoto();
            // операции после добавления/редактирования статьи
            // добавление статьи
            if ($do == 'addarticle') {
                // Получаем добавленную статью
                $article = $model->getArticle($article_id);
                if (!$article['published']) {
                    cmsCore::addSessionMessage($_LANG['ARTICLE_PREMODER_TEXT'], 'info');
                    // отсылаем уведомление администраторам
                    $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_ARTICLE_SUBMIT']);
                    $message = str_replace('%link%', $link, $message);
                    cmsUser::sendMessageToGroup(USER_UPDATER, cmsUser::getAdminGroups(), $message);
                } else {
                    //регистрируем событие
                    cmsActions::log('add_article', array('object' => $article['title'], 'object_url' => $model->getArticleURL(null, $article['seolink']), 'object_id' => $article['id'], 'target' => $article['cat_title'], 'target_url' => $model->getCategoryURL(null, $article['catseolink']), 'target_id' => $article['category_id'], 'description' => ''));
                    if (IS_BILLING) {
                        $category_cost = $article['cost'] === '' ? false : (int) $article['cost'];
                        cmsBilling::process('content', 'add_content', $category_cost);
                    }
                    cmsUser::checkAwards($inUser->id);
                }
                cmsCore::addSessionMessage($_LANG['ARTICLE_SAVE'], 'info');
                cmsCore::redirect('/my.html');
            }
            // Редактирование статьи
            if ($do == 'editarticle') {
                $model->updateArticle($item['id'], $article, true);
                cmsActions::updateLog('add_article', array('object' => $article['title']), $item['id']);
                if (!$article['published']) {
                    $link = '<a href="' . $model->getArticleURL(null, $item['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_ARTICLE_EDITED']);
                    $message = str_replace('%link%', $link, $message);
                    cmsUser::sendMessageToGroup(USER_UPDATER, cmsUser::getAdminGroups(), $message);
                }
                $mess = $article['published'] ? $_LANG['ARTICLE_SAVE'] : $_LANG['ARTICLE_SAVE'] . ' ' . $_LANG['ARTICLE_PREMODER_TEXT'];
                cmsCore::addSessionMessage($mess, 'info');
                cmsCore::redirect($model->getArticleURL(null, $item['seolink']));
            }
        }
    }
    ///////////////////////// PUBLISH ARTICLE /////////////////////////////////////////////////////////////////////////////
    if ($do == 'publisharticle') {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $article = $model->getArticle($id);
        if (!$article) {
            cmsCore::error404();
        }
        // Редактор с правами на добавление без модерации или администраторы могут публиковать
        if (!($article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd')) && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $inDB->setFlag('cms_content', $article['id'], 'published', 1);
        cmsCore::callEvent('ADD_ARTICLE_DONE', $article);
        if (IS_BILLING) {
            $author = $inDB->get_fields('cms_users', "id='{$article['user_id']}'", '*');
            $category_cost = $article['cost'] === '' ? false : (int) $article['cost'];
            cmsBilling::process('content', 'add_content', $category_cost, $author);
        }
        //регистрируем событие
        cmsActions::log('add_article', array('object' => $article['title'], 'user_id' => $article['user_id'], 'object_url' => $model->getArticleURL(null, $article['seolink']), 'object_id' => $article['id'], 'target' => $article['cat_title'], 'target_url' => $model->getCategoryURL(null, $article['catseolink']), 'target_id' => $article['cat_id'], 'description' => ''));
        $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
        $message = str_replace('%link%', $link, $_LANG['MSG_ARTICLE_ACCEPTED']);
        cmsUser::sendMessage(USER_UPDATER, $article['user_id'], $message);
        cmsUser::checkAwards($article['user_id']);
        cmsCore::redirectBack();
    }
    ///////////////////////////////////// DELETE ARTICLE ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'deletearticle') {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $article = $model->getArticle($id);
        if (!$article) {
            cmsCore::error404();
        }
        // права доступа
        $is_author = cmsUser::isUserCan('content/delete') && $article['user_id'] == $inUser->id;
        $is_editor = $article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd');
        if (!$is_author && !$is_editor && !$inUser->is_admin) {
            cmsCore::error404();
        }
        if (!cmsCore::inRequest('goadd')) {
            $inPage->setTitle($_LANG['ARTICLE_REMOVAL']);
            $inPage->addPathway($_LANG['ARTICLE_REMOVAL']);
            $confirm['title'] = $_LANG['ARTICLE_REMOVAL'];
            $confirm['text'] = $_LANG['ARTICLE_REMOVAL_TEXT'] . ' <a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>?';
            $confirm['action'] = $_SERVER['REQUEST_URI'];
            $confirm['yes_button'] = array();
            $confirm['yes_button']['type'] = 'submit';
            $confirm['yes_button']['name'] = 'goadd';
            cmsPage::initTemplate('components', 'action_confirm')->assign('confirm', $confirm)->display('action_confirm.tpl');
        } else {
            $model->deleteArticle($article['id']);
            if ($_SERVER['HTTP_REFERER'] == '/my.html') {
                cmsCore::addSessionMessage($_LANG['ARTICLE_DELETED'], 'info');
                cmsCore::redirectBack();
            } else {
                // если удалили как администратор или редактор и мы не авторы статьи, отсылаем сообщение автору
                if (($is_editor || $inUser->is_admin) && $article['user_id'] != $inUser->id) {
                    $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%link%', $link, $article['published'] ? $_LANG['MSG_ARTICLE_DELETED'] : $_LANG['MSG_ARTICLE_REJECTED']);
                    cmsUser::sendMessage(USER_UPDATER, $article['user_id'], $message);
                } else {
                    cmsCore::addSessionMessage($_LANG['ARTICLE_DELETED'], 'info');
                }
                cmsCore::redirect($model->getCategoryURL(null, $article['catseolink']));
            }
        }
    }
    ///////////////////////////////////// MY ARTICLES ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'my') {
        if (!cmsUser::isUserCan('content/add')) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['MY_ARTICLES']);
        $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
        $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
        $inPage->addPathway($_LANG['MY_ARTICLES']);
        $perpage = 15;
        // Условия
        $model->whereUserIs($inUser->id);
        // Общее количество статей
        $total = $model->getArticlesCount(false);
        // Сортировка и разбивка на страницы
        $inDB->orderBy('con.pubdate', 'DESC');
        $inDB->limitPage($page, $perpage);
        // Получаем статьи
        $content_list = $total ? $model->getArticlesList(false) : array();
        $inDB->resetConditions();
        cmsPage::initTemplate('components', 'com_content_my')->assign('articles', $content_list)->assign('total', $total)->assign('user_can_delete', cmsUser::isUserCan('content/delete'))->assign('pagebar', cmsPage::getPagebar($total, $page, $perpage, '/content/my%page%.html'))->display('com_content_my.tpl');
    }
    ///////////////////////////////////// BEST ARTICLES ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'best') {
        $inPage->setTitle($_LANG['ARTICLES_RATING']);
        $inPage->addPathway($_LANG['ARTICLES_RATING']);
        // Только статьи, за которые можно голосовать
        $inDB->where("con.canrate = 1");
        // Сортировка и разбивка на страницы
        $inDB->orderBy('con.rating', 'DESC');
        $inDB->limitPage(1, 30);
        // Получаем статьи
        $content_list = $model->getArticlesList();
        cmsPage::initTemplate('components', 'com_content_rating')->assign('articles', $content_list)->display('com_content_rating.tpl');
    }
}
示例#6
0
function photos()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    cmsCore::loadClass('photo');
    $inPhoto = cmsPhoto::getInstance();
    global $_LANG;
    $model = new cms_model_photos();
    $pagetitle = $inCore->menuTitle();
    $root_album_id = $inDB->getNsRootCatId('cms_photo_albums');
    $id = cmsCore::request('id', 'int', $root_album_id);
    $do = $inCore->do;
    $page = cmsCore::request('page', 'int', 1);
    $inPage->addPathway($inCore->getComponentTitle(), '/photos');
    // только авторизованные пользуются js
    if ($inUser->id) {
        $inPage->addHeadJS('components/photos/js/photos.js');
        $inPage->addHeadJsLang(array('NO_PUBLISH', 'EDIT_PHOTO', 'YOU_REALLY_DELETE_PHOTO', 'MOVE_PHOTO'));
    }
    $inPage->setDescription($model->config['meta_desc'] ? $model->config['meta_desc'] : $pagetitle);
    $inPage->setKeywords($model->config['meta_keys'] ? $model->config['meta_keys'] : $pagetitle);
    /////////////////////////////// Просмотр альбома ///////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'view') {
        $album = $inDB->getNsCategory('cms_photo_albums', $id, null);
        if (!$album && $inCore->menuId() !== 1) {
            cmsCore::error404();
        }
        // Неопубликованные альбомы показываем только админам
        if (!$album['published'] && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $album = cmsCore::callEvent('GET_PHOTO_ALBUM', $album);
        // если не корневой альбом
        if ($album['id'] != $root_album_id) {
            $path_list = $inDB->getNsCategoryPath('cms_photo_albums', $album['NSLeft'], $album['NSRight'], 'id, title, NSLevel');
            if ($path_list) {
                foreach ($path_list as $pcat) {
                    $inPage->addPathway($pcat['title'], '/photos/' . $pcat['id']);
                }
            }
            $pagetitle = $pagetitle && $inCore->isMenuIdStrict() ? $pagetitle : $album['title'] . ' - ' . $_LANG['PHOTOGALLERY'];
            $inPage->setTitle($album['pagetitle'] ? $album['pagetitle'] : $pagetitle);
        } else {
            $pagetitle = $pagetitle && $inCore->isMenuIdStrict() ? $pagetitle : $_LANG['PHOTOGALLERY'];
            $inPage->setTitle($pagetitle);
            $album['title'] = $pagetitle;
        }
        //Формируем подкатегории альбома
        $inDB->orderBy('f.' . $model->config['orderby'], $model->config['orderto']);
        $subcats = $inPhoto->getAlbums($album['id']);
        // Сортировка фотографий
        $orderby = cmsCore::getSearchVar('orderby', $album['orderby']);
        $orderto = cmsCore::getSearchVar('orderto', $album['orderto']);
        if (!in_array($orderby, array('title', 'pubdate', 'rating', 'hits'))) {
            $orderby = $album['orderby'];
        }
        if (!in_array($orderto, array('desc', 'asc'))) {
            $orderto = $album['orderto'];
        }
        // Устанавливаем альбом
        $inPhoto->whereAlbumIs($album['id']);
        // Общее количество фото по заданным выше условиям
        $total = $inPhoto->getPhotosCount($inUser->is_admin);
        //устанавливаем сортировку
        $inDB->orderBy('f.' . $orderby, $orderto);
        //устанавливаем номер текущей страницы и кол-во фото на странице
        $inDB->limitPage($page, $album['perpage']);
        $photos = $inPhoto->getPhotos($inUser->is_admin, $album['showdate']);
        if (!$photos && $page > 1) {
            cmsCore::error404();
        }
        if ($album['id'] != $root_album_id) {
            // meta description
            if ($album['meta_desc']) {
                $meta_desc = $album['meta_desc'];
            } elseif (mb_strlen(strip_tags($album['description'])) >= 250) {
                $meta_desc = crop($album['description']);
            } else {
                $meta_desc = $album['title'];
            }
            $inPage->setDescription($meta_desc);
            // meta keywords
            if ($album['meta_keys']) {
                $meta_keys = $album['meta_keys'];
            } elseif ($photos) {
                foreach ($photos as $p) {
                    $k[] = $p['title'];
                }
                $meta_keys = implode(', ', $k);
            } else {
                $meta_keys = $album['title'];
            }
            $inPage->setKeywords($meta_keys);
        }
        cmsPage::initTemplate('components', 'com_photos_view')->assign('root_album_id', $root_album_id)->assign('cfg', $model->config)->assign('album', $album)->assign('can_add_photo', $album['public'] && $inUser->id || $inUser->is_admin)->assign('subcats', $subcats)->assign('photos', $photos)->assign('pagebar', cmsPage::getPagebar($total, $page, $album['perpage'], '/photos/' . $album['id'] . '-%page%'))->assign('total', $total)->assign('orderby', $orderby)->assign('orderto', $orderto)->display('com_photos_view.tpl');
        // если есть фотограйии в альбоме и включены комментарии в альбоме, то показываем их
        if ($album['is_comments'] && $photos && $inCore->isComponentInstalled('comments')) {
            cmsCore::includeComments();
            comments('palbum', $album['id']);
        }
    }
    /////////////////////////////// VIEW PHOTO ///////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'viewphoto') {
        // получаем фото
        $photo = cmsCore::callEvent('GET_PHOTO', $inPhoto->getPhoto($id));
        if (!$photo) {
            cmsCore::error404();
        }
        // Если фото клуба редиректим на новый алрес
        if (mb_strstr($photo['NSDiffer'], 'club')) {
            cmsCore::redirect('/clubs/photo' . $photo['id'] . '.html', '301');
        }
        $is_author = $photo['user_id'] == $inUser->id && $inUser->id;
        // неопубликованное фото видно админам и автору
        if (!$photo['published'] && !$inUser->is_admin && !$is_author) {
            cmsCore::error404();
        }
        $path_list = $inDB->getNsCategoryPath('cms_photo_albums', $photo['NSLeft'], $photo['NSRight'], 'id, title, NSLevel');
        if ($path_list) {
            foreach ($path_list as $pcat) {
                $inPage->addPathway($pcat['title'], '/photos/' . $pcat['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']);
        }
        // Обновляем количество просмотров фотографии
        if (!$is_author) {
            $inDB->setFlag('cms_photo_files', $photo['id'], 'hits', $photo['hits'] + 1);
        }
        //навигация
        if ($photo['album_nav']) {
            $nextid = $inDB->get_fields('cms_photo_files', 'id<' . $photo['id'] . ' AND album_id = ' . $photo['album_id'] . ' AND published=1', 'id, file', 'id DESC');
            $previd = $inDB->get_fields('cms_photo_files', 'id>' . $photo['id'] . ' AND album_id = ' . $photo['album_id'] . ' AND published=1', 'id, file', 'id ASC');
        } else {
            $previd = false;
            $nextid = false;
        }
        $photo['karma_buttons'] = cmsKarmaButtons('photo', $photo['id'], $photo['rating'], $is_author);
        $photo['genderlink'] = cmsUser::getGenderLink($photo['user_id'], $photo['nickname'], $photo['gender'], $photo['login']);
        cmsPage::initTemplate('components', 'com_photos_view_photo')->assign('photo', $photo)->assign('bbcode', '[IMG]' . HOST . '/images/photos/medium/' . $photo['file'] . '[/IMG]')->assign('previd', $previd)->assign('nextid', $nextid)->assign('cfg', $model->config)->assign('is_author', $is_author)->assign('is_admin', $inUser->is_admin)->assign('tagbar', $photo['a_tags'] ? cmsTagBar('photo', $photo['id']) : '')->display('com_photos_view_photo.tpl');
        //выводим комментарии, если они разрешены и фото опубликовано
        if ($photo['comments'] && $inCore->isComponentInstalled('comments')) {
            cmsCore::includeComments();
            comments('photo', $photo['id'], array(), $is_author);
        }
    }
    /////////////////////////////// PHOTO UPLOAD  ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'addphoto') {
        // Неавторизованных просим авторизоваться
        if (!$inUser->id) {
            cmsUser::goToLogin();
        }
        $do_photo = cmsCore::request('do_photo', 'str', 'addphoto');
        // получаем альбом
        $album = $inDB->getNsCategory('cms_photo_albums', $id);
        if (!$album) {
            cmsCore::error404();
        }
        if (!$album['published'] && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $album = cmsCore::callEvent('GET_PHOTO_ALBUM', $album);
        // права доступа
        // загружаем только в разрешенные альбомы
        if (!$album['public'] && !$inUser->is_admin) {
            cmsCore::error404();
        }
        // Смотрим ограничения загрузки в сутки
        $today_uploaded = $album['uplimit'] ? $model->loadedByUser24h($inUser->id, $album['id']) : 0;
        if (!$inUser->is_admin && $album['uplimit'] && $today_uploaded >= $album['uplimit']) {
            cmsCore::addSessionMessage('<strong>' . $_LANG['MAX_UPLOAD_IN_DAY'] . '</strong> ' . $_LANG['CAN_UPLOAD_TOMORROW'], 'error');
            cmsCore::redirectBack();
        }
        // глубиномер
        $path_list = $inDB->getNsCategoryPath('cms_photo_albums', $album['NSLeft'], $album['NSRight'], 'id, title, NSLevel');
        if ($path_list) {
            foreach ($path_list as $pcat) {
                $inPage->addPathway($pcat['title'], '/photos/' . $pcat['id']);
            }
        }
        include 'components/photos/add_photo.php';
    }
    /////////////////////////////// PHOTO EDIT ///////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'editphoto') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        // получаем фото
        $photo = cmsCore::callEvent('GET_PHOTO', $inPhoto->getPhoto($id));
        if (!$photo) {
            cmsCore::halt();
        }
        if (mb_strstr($photo['NSDiffer'], 'club')) {
            cmsCore::halt();
        }
        $is_author = $photo['user_id'] == $inUser->id && $inUser->id;
        if (!$inUser->is_admin && !$is_author) {
            cmsCore::halt();
        }
        if (cmsCore::inRequest('edit_photo')) {
            $mod['title'] = cmsCore::request('title', 'str', '');
            $mod['title'] = $mod['title'] ? $mod['title'] : $photo['title'];
            $mod['description'] = cmsCore::request('description', 'str', '');
            $mod['tags'] = cmsCore::request('tags', 'str', '');
            $mod['comments'] = $inUser->is_admin ? 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($inDB->getNsCategory('cms_photo_albums', $photo['album_id']))->uploadPhoto($photo['file']);
            $mod['file'] = $file['filename'] ? $file['filename'] : $photo['file'];
            $inPhoto->updatePhoto($mod, $photo['id']);
            $description = '<a href="/photos/photo' . $photo['id'] . '.html" class="act_photo"><img src="/images/photos/small/' . $mod['file'] . '" alt="' . htmlspecialchars(stripslashes($mod['title'])) . '" /></a>';
            cmsActions::updateLog('add_photo', array('object' => $mod['title'], 'description' => $description), $photo['id']);
            cmsCore::addSessionMessage($_LANG['PHOTO_SAVED'], 'success');
            cmsCore::jsonOutput(array('error' => false, 'redirect' => '/photos/photo' . $photo['id'] . '.html'));
        } else {
            $photo['tags'] = cmsTagLine('photo', $photo['id'], false);
            cmsPage::initTemplate('components', 'com_photos_edit')->assign('photo', $photo)->assign('form_action', '/photos/editphoto' . $photo['id'] . '.html')->assign('no_tags', false)->assign('is_admin', $inUser->is_admin)->assign('cfg', $model->config)->display('com_photos_edit.tpl');
            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }
    }
    /////////////////////////////// PHOTO MOVE /////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'movephoto') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $photo = cmsCore::callEvent('GET_PHOTO', $inPhoto->getPhoto($id));
        if (!$photo) {
            cmsCore::halt();
        }
        if (mb_strstr($photo['NSDiffer'], 'club')) {
            cmsCore::halt();
        }
        if (!$inUser->is_admin) {
            cmsCore::halt();
        }
        if (!cmsCore::inRequest('move_photo')) {
            cmsPage::initTemplate('components', 'com_photos_move')->assign('form_action', '/photos/movephoto' . $photo['id'] . '.html')->assign('html', $inPhoto->getAlbumsOption('', $photo['album_id']))->display('com_photos_move.tpl');
            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        } else {
            $album = cmsCore::callEvent('GET_PHOTO_ALBUM', $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int')));
            if (!$album) {
                cmsCore::halt();
            }
            if (!$album['public'] && !$inUser->is_admin) {
                cmsCore::error404();
            }
            // Смотрим ограничения загрузки в сутки
            $today_uploaded = $album['uplimit'] ? $model->loadedByUser24h($inUser->id, $album['id']) : 0;
            if (!$inUser->is_admin && $album['uplimit'] && $today_uploaded >= $album['uplimit']) {
                cmsCore::jsonOutput(array('error' => true, 'text' => '<strong>' . $_LANG['MAX_UPLOAD_IN_DAY'] . '</strong> ' . $_LANG['CAN_UPLOAD_TOMORROW']));
            }
            $inDB->query("UPDATE cms_photo_files SET album_id = '{$album['id']}' WHERE id = '{$photo['id']}'");
            cmsActions::updateLog('add_photo', array('target' => $album['title'], 'target_url' => '/photos/' . $album['id'], 'target_id' => $album['id']), $photo['id']);
            cmsCore::addSessionMessage($_LANG['PHOTO_MOVED'], 'info');
            cmsCore::jsonOutput(array('error' => false, 'redirect' => '/photos/' . $album['id']));
        }
    }
    /////////////////////////////// PHOTO DELETE /////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'delphoto') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::halt();
        }
        $photo = cmsCore::callEvent('GET_PHOTO', $inPhoto->getPhoto($id));
        if (!$photo) {
            cmsCore::halt();
        }
        if (mb_strstr($photo['NSDiffer'], 'club')) {
            cmsCore::halt();
        }
        $is_author = $photo['user_id'] == $inUser->id && $inUser->id;
        if (!$inUser->is_admin && !$is_author) {
            cmsCore::halt();
        }
        $inPhoto->deletePhoto($photo, $model->initUploadClass($inDB->getNsCategory('cms_photo_albums', $photo['album_id'])));
        cmsCore::addSessionMessage($_LANG['PHOTO_DELETED'], 'success');
        cmsUser::clearCsrfToken();
        cmsCore::jsonOutput(array('error' => false, 'redirect' => '/photos/' . $photo['album_id']));
    }
    /////////////////////////////// PHOTO PUBLISH /////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'publish_photo') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $photo = cmsCore::callEvent('GET_PHOTO', $inPhoto->getPhoto($id));
        if (!$photo) {
            cmsCore::halt();
        }
        if (!$inUser->is_admin) {
            cmsCore::halt();
        }
        $inPhoto->publishPhoto($photo['id']);
        cmsCore::callEvent('ADD_PHOTO_DONE', $photo);
        $description = '<a href="/photos/photo' . $photo['id'] . '.html" class="act_photo"><img src="/images/photos/small/' . $photo['file'] . '" alt="' . htmlspecialchars(stripslashes($photo['title'])) . '" /></a>';
        cmsActions::log('add_photo', array('object' => $photo['title'], 'object_url' => '/photos/photo' . $photo['id'] . '.html', 'object_id' => $photo['id'], 'user_id' => $photo['user_id'], 'target' => $photo['cat_title'], 'target_id' => $photo['album_id'], 'target_url' => '/photos/' . $photo['album_id'], 'description' => $description));
        cmsCore::halt('ok');
    }
    /////////////////////////////// VIEW LATEST/BEST PHOTOS //////////////////////////////////////////////////////////////////////////////
    if (in_array($do, array('latest', 'best'))) {
        if ($do == 'latest') {
            $inDB->orderBy('f.pubdate', 'DESC');
            $pagetitle = $pagetitle && $inCore->isMenuIdStrict() ? $pagetitle : $_LANG['NEW_PHOTO_IN_GALLERY'];
        } else {
            $inDB->orderBy('f.rating', 'DESC');
            $pagetitle = $pagetitle && $inCore->isMenuIdStrict() ? $pagetitle : $_LANG['BEST_PHOTOS'];
        }
        $inDB->limit($model->config['best_latest_perpage']);
        // выбираем категории фото
        $inDB->addJoin("INNER JOIN cms_photo_albums a ON a.id = f.album_id AND a.published = 1 AND a.NSDiffer = ''");
        $inDB->addSelect('a.title as cat_title');
        $photos = $inPhoto->getPhotos(false, 'with_comments');
        if (!$photos) {
            cmsCore::error404();
        }
        $inPage->addPathway($pagetitle);
        $inPage->setTitle($pagetitle);
        cmsPage::initTemplate('components', 'com_photos_bl')->assign('maxcols', $model->config['best_latest_maxcols'])->assign('pagetitle', $pagetitle)->assign('photos', $photos)->display('com_photos_bl.tpl');
    }
    /////////////////////////////// /////////////////////////////// ////////////////
}
示例#7
0
function applet_content() {
    $inCore = cmsCore::getInstance();
    cmsCore::m('content');
    
    global $_LANG;

    //check access
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/content', $adminAccess)) { cpAccessDenied(); }

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

    cmsCore::c('page')->setTitle($_LANG['AD_ARTICLES']);
    cpAddPathway($_LANG['AD_ARTICLES'], 'index.php?view=tree');

    $do = cmsCore::request('do', 'str', 'add');
    $id = cmsCore::request('id', 'int', -1);

    if ($do == 'arhive_on') {
        cmsCore::c('db')->setFlag('cms_content', $id, 'is_arhive', '1');
        cmsCore::addSessionMessage($_LANG['AD_ARTICLES_TO_ARHIVE'], 'success');
        cmsCore::redirectBack();
    }

    if ($do == 'move') {
        $item_id = cmsCore::request('id', 'int', 0);
        $cat_id  = cmsCore::request('cat_id', 'int', 0);

        $dir     = cmsCore::request('dir', 'str');
        $step    = 1;

        cmsCore::m('content')->moveItem($item_id, $cat_id, $dir, $step);
        cmsCore::halt(1);
    }

    if ($do == 'move_to_cat') {
        $items     = cmsCore::request('item', 'array_int');
        $to_cat_id = cmsCore::request('obj_id', 'int', 0);

        if ($items && $to_cat_id) {
            $last_ordering = (int)cmsCore::c('db')->get_field('cms_content', "category_id = '". $to_cat_id ."' ORDER BY ordering DESC", 'ordering');
            foreach ($items as $item_id) {
                $article = cmsCore::m('content')->getArticle($item_id);
                if (!$article) { continue; }
                $last_ordering++;
                
                cmsCore::m('content')->updateArticle(
                    $article['id'],
                    array(
                        'category_id' => $to_cat_id,
                        'ordering' => $last_ordering,
                        'url' => $article['url'],
                        'title' => cmsCore::c('db')->escape_string($article['title']),
                        'id' => $article['id'],
                        'user_id' => $article['user_id']
                    )
                );
            }
            
            cmsCore::addSessionMessage($_LANG['AD_ARTICLES_TO'], 'success');
        }

        cmsCore::redirect('?view=tree&cat_id='. $to_cat_id);
    }

    if ($do == 'show') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) { cmsCore::c('db')->setFlag('cms_content', $id, 'published', '1'); }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_content', cmsCore::request('item', 'array_int'), 'published', '1');
            cmsCore::redirectBack();
        }
    }

    if ($do == 'hide') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) { cmsCore::c('db')->setFlag('cms_content', $id, 'published', '0'); }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_content', cmsCore::request('item', 'array_int'), 'published', '0');
            cmsCore::redirectBack();
        }
    }

    if ($do == 'delete') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) {
                cmsCore::m('content')->deleteArticle($id);
                cmsCore::addSessionMessage($_LANG['AD_ARTICLE_REMOVE'], 'success');
            }
        } else {
            cmsCore::m('content')->deleteArticles(cmsCore::request('item', 'array_int'));
            cmsCore::addSessionMessage($_LANG['AD_ARTICLES_REMOVE'], 'success');
        }
        cmsCore::redirectBack();
    }

    if ($do == 'update'){
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }
        
        if (cmsCore::inRequest('id')) {
            $id                     = cmsCore::request('id', 'int', 0);
            $article['category_id'] = cmsCore::request('category_id', 'int', 1);
            $article['title']       = cmsCore::request('title', 'str');
            $article['url']         = cmsCore::request('url', 'str');
            $article['showtitle']   = cmsCore::request('showtitle', 'int', 0);
            $article['description'] = cmsCore::request('description', 'html', '');
            $article['description'] = cmsCore::c('db')->escape_string($article['description']);
            $article['content']     = cmsCore::request('content', 'html', '');
            $article['content']     = cmsCore::c('db')->escape_string($article['content']);
            $article['published']   = cmsCore::request('published', 'int', 0);

            $article['showdate']    = cmsCore::request('showdate', 'int', 0);
            $article['showlatest']  = cmsCore::request('showlatest', 'int', 0);
            $article['showpath']    = cmsCore::request('showpath', 'int', 0);
            $article['comments']    = cmsCore::request('comments', 'int', 0);
            $article['canrate']     = cmsCore::request('canrate', 'int', 0);

            $enddate                = explode('.', cmsCore::request('enddate', 'str'));
            $article['enddate']     = $enddate[2] .'-'. $enddate[1] .'-'. $enddate[0];

            $article['is_end']      = cmsCore::request('is_end', 'int', 0);
            $article['pagetitle']   = cmsCore::request('pagetitle', 'str', '');

            $article['tags']        = cmsCore::request('tags', 'str');

            $olddate                = cmsCore::request('olddate', 'str', '');
            $pubdate                = cmsCore::request('pubdate', 'str', '');

            $article['user_id']     = cmsCore::request('user_id', 'int', cmsCore::c('user')->id);

            $article['tpl']         = cmsCore::request('tpl', 'str', 'com_content_read');

            if ($olddate != $pubdate) {
                $date = explode('.', $pubdate);
                $article['pubdate'] = $date[2] .'-'. $date[1] .'-'. $date[0] .' '.  date('H:i');
            }

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

            switch($autokeys){
                case 1: $article['meta_keys'] = $inCore->getKeywords($article['content']);
                        $article['meta_desc'] = $article['title'];
                        break;

                case 2: $article['meta_desc'] = strip_tags($article['description']);
                        $article['meta_keys'] = $article['tags'];
                        break;

                case 3: $article['meta_desc'] = cmsCore::request('meta_desc', 'str');
                        $article['meta_keys'] = cmsCore::request('meta_keys', 'str');
                        break;
            }

            cmsCore::m('content')->updateArticle($id, $article);

            if (!cmsCore::request('is_public', 'int', 0)) {
                $showfor = cmsCore::request('showfor', 'array_int', array());
                cmsCore::setAccess($id, $showfor, 'material');
            } else {
                cmsCore::clearAccess($id, 'material');
            }

            cmsCore::m('content')->uploadArticeImage($id, cmsCore::request('delete_image', 'int', 0));

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

            if (!isset($_SESSION['editlist']) || count($_SESSION['editlist']) == 0) {
                cmsCore::redirect('?view=tree&cat_id='.$article['category_id']);
            } else {
                cmsCore::redirect('?view=content&do=edit');
            }
        }
    }

    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }
        
        $article['category_id'] = cmsCore::request('category_id', 'int', 1);
        $article['title']       = cmsCore::request('title', 'str');
        $article['url']         = cmsCore::request('url', 'str');
        $article['showtitle']   = cmsCore::request('showtitle', 'int', 0);
        $article['description'] = cmsCore::request('description', 'html', '');
        $article['description'] = cmsCore::c('db')->escape_string($article['description']);
        $article['content']     = cmsCore::request('content', 'html', '');
        $article['content']    	= cmsCore::c('db')->escape_string($article['content']);

        $article['published']   = cmsCore::request('published', 'int', 0);

        $article['showdate']    = cmsCore::request('showdate', 'int', 0);
        $article['showlatest']  = cmsCore::request('showlatest', 'int', 0);
        $article['showpath']    = cmsCore::request('showpath', 'int', 0);
        $article['comments']    = cmsCore::request('comments', 'int', 0);
        $article['canrate']     = cmsCore::request('canrate', 'int', 0);

        $enddate                = explode('.', cmsCore::request('enddate', 'str'));
        $article['enddate']     = $enddate[2] .'-'. $enddate[1] .'-'. $enddate[0];
        $article['is_end']      = cmsCore::request('is_end', 'int', 0);
        $article['pagetitle']   = cmsCore::request('pagetitle', 'str', '');

        $article['tags']        = cmsCore::request('tags', 'str');

        $article['pubdate']     = cmsCore::request('pubdate', 'str');
        $date                   = explode('.', $article['pubdate']);
        $article['pubdate']     = $date[2] .'-'. $date[1] .'-'. $date[0] .' '. date('H:i');

        $article['user_id']     = cmsCore::request('user_id', 'int', cmsCore::c('user')->id);

        $article['tpl']         = cmsCore::request('tpl', 'str', 'com_content_read');

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

        switch ($autokeys) {
            case 1: $article['meta_keys'] = $inCore->getKeywords($article['content']);
                    $article['meta_desc'] = $article['title'];
                    break;

            case 2: $article['meta_desc'] = strip_tags($article['description']);
                    $article['meta_keys'] = $article['tags'];
                    break;

            case 3: $article['meta_desc'] = cmsCore::request('meta_desc', 'str');
                    $article['meta_keys'] = cmsCore::request('meta_keys', 'str');
                    break;
        }

        $article['id'] = cmsCore::m('content')->addArticle($article);

        if (!cmsCore::request('is_public', 'int', 0)) {
            $showfor = cmsCore::request('showfor', 'array_int', array());
            cmsCore::setAccess($article['id'], $showfor, 'material');
        }

        $inmenu = cmsCore::request('createmenu', 'str', '');

        if ($inmenu) {
            createMenuItem($inmenu, $article['id'], $article['title']);
        }

        cmsCore::m('content')->uploadArticeImage($article['id']);

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

        cmsCore::redirect('?view=tree&cat_id='. $article['category_id']);
    }

    if ($do == 'add' || $do == 'edit') {
        $toolmenu = array(
            array( 'icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:document.addform.submit();' ),
            array( 'icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'javascript:history.go(-1);' )
        );

        cpToolMenu($toolmenu);
        $menu_list = cpGetList('menu');

        if ($do == 'add') {
            echo '<h3>'. $_LANG['AD_CREATE_ARTICLE'] .'</h3>';
            cpAddPathway($_LANG['AD_CREATE_ARTICLE'], 'index.php?view=content&do=add');
            
            $mod = array(
                'category_id' => cmsCore::request('to', 'int'),
                'showpath' => 1,
                'tpl' => 'com_content_read'
            );
        } else {
            if (isset($_REQUEST['item'])){
                $_SESSION['editlist'] = $_REQUEST['item'];
            }

            $ostatok = '';

            if (isset($_SESSION['editlist'])) {
                $id = array_shift($_SESSION['editlist']);
                if (count($_SESSION['editlist'])==0) {
                    unset($_SESSION['editlist']);
                } else {
                    $ostatok = '('. $_LANG['AD_NEXT_IN'] . count($_SESSION['editlist']) .')';
                }
            } else {
                $id = (int)$_REQUEST['id'];
            }

            $sql = "SELECT *, (TO_DAYS(enddate) - TO_DAYS(CURDATE())) as daysleft, DATE_FORMAT(pubdate, '%d.%m.%Y') as pubdate, DATE_FORMAT(enddate, '%d.%m.%Y') as enddate
                     FROM cms_content
                     WHERE id = ". $id ." LIMIT 1";
            $result = cmsCore::c('db')->query($sql) ;
            if (cmsCore::c('db')->num_rows($result)) {
                $mod = cmsCore::c('db')->fetch_assoc($result);
                if (!empty($mod['images'])) {
                    $mod['images'] = json_decode($mod['images'], true);
                }
            }

            echo '<h3>'. $_LANG['AD_EDIT_ARTICLE'] . $ostatok .'</h3>';
            cpAddPathway($mod['title'], 'index.php?view=content&do=edit&id='. $mod['id']);
        }
        
        $ajaxUploader = cmsCore::c('page')->initAjaxUpload(
            'plupload',
            array(
                'component' => 'content',
                'target_id' => cmsCore::getArrVal($mod, 'id', 0),
                'insertEditor' => 'content'
            ),
            cmsCore::getArrVal($mod, 'images', false)
        );
        
        $tab_plugins = cmsCore::callTabEventPlugins('ADMIN_CONTENT_TABS', !empty($mod['id']) ? $mod : array());
?>
<form id="addform" name="addform" method="post" action="index.php" enctype="multipart/form-data">
    <input type="hidden" name="csrf_token" value="<?php echo cmsUser::getCsrfToken(); ?>" />
    <input type="hidden" name="view" value="content" />

    <table class="table">
        <tr>
            <!-- главная ячейка -->
            <td valign="top">
                <table width="100%" cellpadding="0" cellspacing="4" border="0">
                    <tr>
                        <td valign="top">
                            <label><?php echo $_LANG['AD_ARTICLE_NAME']; ?></label>
                            <div>
                                <table width="100%" cellpadding="0" cellspacing="0" border="0">
                                    <tr>
                                        <td><input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($mod['title']);?>" /></td>
                                        <td style="width:15px;padding-left:10px;padding-right:10px;">
                                            <input type="checkbox" class="uittip" title="<?php echo $_LANG['AD_VIEW_TITLE']; ?>" name="showtitle" <?php if ($mod['showtitle'] || $do=='add') { echo 'checked="checked"'; } ?> value="1">
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </td>
                        <td width="130" valign="top">
                            <label><?php echo $_LANG['AD_PUBLIC_DATE']; ?></label>
                            <div>
                                <input type="text" id="pubdate" class="form-control" name="pubdate" style="width:100px;display: inline-block" <?php if(@!$mod['pubdate']) { echo 'value="'.date('d.m.Y').'"'; } else { echo 'value="'.$mod['pubdate'].'"'; } ?>/>

                                <input type="hidden" name="olddate" value="<?php echo @$mod['pubdate']?>" />
                            </div>
                        </td>
                        <td width="16" valign="bottom" style="padding-bottom:10px">
                            <input type="checkbox" id="showdate" class="uittip" name="showdate" title="<?php echo $_LANG['AD_VIEW_DATE_AND_AUTHOR']; ?>" value="1" <?php if ($mod['showdate'] || $do=='add') { echo 'checked="checked"'; } ?>/>
                        </td>
                        <td width="160" valign="top">
                            <label><?php echo $_LANG['AD_ARTICLE_TEMPLATE']; ?></label>
                            <div><input type="text" class="form-control" style="width:160px" name="tpl" value="<?php echo @$mod['tpl'];?>"></div>
                        </td>
                    </tr>
                </table>
                    
                <div class="form-group">
                    <label><?php echo $_LANG['AD_ARTICLE_NOTICE']; ?></label>
                    <div><?php $inCore->insertEditor('description', $mod['description'], '200', '100%'); ?></div>
                </div>

                <div class="form-group">
                    <label><?php echo $_LANG['AD_ARTICLE_TEXT']; ?></label>
                    <?php insertPanel(); ?>
                    <div><?php $inCore->insertEditor('content', $mod['content'], '400', '100%'); ?></div>
                </div>
                    
                <div class="form-group">
                    <label><?php echo $_LANG['AD_ARTICLE_TAGS']; ?></label>
                    <input type="text" id="tags" class="form-control" name="tags" value="<?php if (isset($mod['id'])) { echo cmsTagLine('content', $mod['id'], false); } ?>" />
                </div>

                <div>
                    <label>
                        <input type="radio" name="autokeys" <?php if ($do == 'add' && $cfg['autokeys']) { ?>checked="checked"<?php } ?> value="1"/>
                        <?php echo $_LANG['AD_AUTO_GEN_KEY']; ?>
                    </label>
                </div>
                <div>
                    <label>
                        <input type="radio" name="autokeys" value="2" />
                        <?php echo $_LANG['AD_TAGS_AS_KEY']; ?>
                    </label>
                </div>
                <div>
                    <label>
                        <input type="radio" name="autokeys" id="autokeys3" value="3" <?php if ($do == 'edit' || !$cfg['autokeys']) { ?>checked="checked"<?php } ?>/>
                        <?php echo $_LANG['AD_MANUAL_KEY']; ?>
                    </label>
                </div>
                    
                <?php if ($cfg['af_on'] && $do=='add') { ?>
                <div>
                    <label>
                        <input type="checkbox" name="noforum" id="noforum" value="1" />
                        <?php echo $_LANG['AD_NO_CREATE_THEME']; ?>
                    </label>
                </div>
                <?php } ?>
            </td>

            <!-- боковая ячейка -->
            <td valign="top" style="width:450px">
                <div class="uitabs">
                    <ul id="tabs">
                        <li><a href="#upr_publish"><span><?php echo $_LANG['AD_TAB_PUBLISH']; ?></span></a></li>
                        <li><a href="#upr_restrictions"><span><?php echo $_LANG['AD_RESTRICTIONS']; ?></span></a></li>
                        <li><a href="#upr_photos"><span><?php echo $_LANG['AD_PHOTOS']; ?></span></a></li>
                        <?php if (!empty($tab_plugins)){ foreach ($tab_plugins as $tab_plugin){ ?>
                            <li><a href="<?php if ($tab_plugin['ajax_link']){ echo $tab_plugin['ajax_link']; }else{ echo '#upr_'. $tab_plugin['name']; } ?>" title="<?php echo $tab_plugin['name']; ?>"><span><?php echo $tab_plugin['title']; ?></span></a></li>
                        <?php }} ?>
                    </ul>
                        
                    <div id="upr_publish">
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="published" id="published" value="1" <?php if ($mod['published'] || $do=='add') { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_PUBLIC_ARTICLE']; ?>
                            </label>
                        </div>
                            
                        <div class="form-group">
                            <select id="category_id" class="form-control" style="height:200px" name="category_id" size="10">
                                <option value="1" <?php if (@$mod['category_id']==1 || !isset($mod['category_id'])) { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_ROOT_CATEGORY'] ; ?></option>
                                <?php
                                    if (isset($mod['category_id'])){
                                        echo $inCore->getListItemsNS('cms_category', $mod['category_id']);
                                    } else {
                                        echo $inCore->getListItemsNS('cms_category');
                                    }
                                ?>
                            </select>
                            <select id="showpath" name="showpath" class="form-control">
                                <option value="0" <?php if (@!$mod['showpath']) { echo 'selected="selected"'; } ?>><?php echo $_LANG['AD_PATHWAY_NAME_ONLY']; ?></option>
                                <option value="1" <?php if (@$mod['showpath']) { echo 'selected="selected"'; } ?>><?php echo $_LANG['AD_PATHWAY_FULL']; ?></option>
                            </select>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_ARTICLE_URL']; ?></label>
                            <input type="text" class="form-control" name="url" value="<?php echo $mod['url']; ?>" />
                            <div class="help-block"><?php echo $_LANG['AD_IF_UNKNOWN_PAGETITLE']; ?></div>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_ARTICLE_AUTHOR']; ?></label>
                            <select id="user_id" class="form-control" name="user_id">
                            <?php
                                if (isset($mod['user_id'])) {
                                    echo $inCore->getListItems('cms_users', $mod['user_id'], 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
                                } else {
                                    echo $inCore->getListItems('cms_users', cmsCore::c('user')->id, 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
                                }
                            ?>
                            </select>
                        </div>
                            
                        <h4><?php echo $_LANG['AD_PUBLIC_PARAMETRS']; ?></h4>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="showlatest" value="1" <?php if ($mod['showlatest'] || $do=='add') { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_VIEW_NEW_ARTICLES']; ?>
                            </label>
                            <label>
                                <input type="checkbox" name="comments" value="1" <?php if ($mod['comments'] || $do=='add') { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_ENABLE_COMMENTS']; ?>
                            </label>
                            <label>
                                <input type="checkbox" name="canrate" value="1" <?php if ($mod['canrate']) { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_ENABLE_RATING']; ?>
                            </label>
                        </div>
                            
                        <h4>SEO</h4>
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_PAGE_TITLE']; ?></label>
                            <input type="text" class="form-control" name="pagetitle" value="<?php if (isset($mod['pagetitle'])) { echo htmlspecialchars($mod['pagetitle']); } ?>" />
                            <div class="help-block"><?php echo $_LANG['AD_IF_UNKNOWN']; ?></div>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['KEYWORDS']; ?></label>
                            <textarea class="form-control" name="meta_keys" rows="4"><?php echo htmlspecialchars($mod['meta_keys']);?></textarea>
                            <div class="help-block"><?php echo $_LANG['AD_FROM_COMMA']; ?></div>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['DESCRIPTION']; ?></label>
                            <textarea class="form-control" name="meta_desc" rows="6"><?php echo htmlspecialchars($mod['meta_desc']);?></textarea>
                            <div class="help-block"><?php echo $_LANG['AD_LESS_THAN']; ?></div>
                        </div>
                            
                        <?php if ($do=='add'){ ?>
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_CREATE_LINK']; ?></label>
                            <select class="form-control" name="createmenu">
                                <option value="0" selected="selected"><?php echo $_LANG['AD_DONT_CREATE_LINK']; ?></option>
                            <?php foreach ($menu_list as $menu) { ?>
                                <option value="<?php echo $menu['id']; ?>">
                                    <?php echo $menu['title']; ?>
                                </option>
                            <?php } ?>
                            </select>
                        </div>
                        <?php } ?>
                    </div>
                        
                    <div id="upr_restrictions">
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_ARTICLE_TIME']; ?></label>
                            <select class="form-control" name="is_end" onchange="if($(this).val() == 1){ $('#final_time').show(); }else {$('#final_time').hide();}">
                                <option value="0" <?php if (@!$mod['is_end']) { echo 'selected="selected"'; } ?>><?php echo $_LANG['AD_UNLIMITED']; ?></option>
                                <option value="1" <?php if (@$mod['is_end']) { echo 'selected="selected"'; } ?>><?php echo $_LANG['AD_TO_FINAL_TIME']; ?></option>
                            </select>
                        </div>
                            
                        <div id="final_time" class="form-group" <?php if (@!$mod['is_end']) { echo 'style="display: none"'; } ?>>
                            <label><?php echo $_LANG['AD_FINAL_TIME']; ?></label>
                            <input type="text" id="enddate" class="form-control" name="enddate" <?php if(@!$mod['is_end']) { echo 'value="'.date('d.m.Y').'"'; } else { echo 'value="'. $mod['enddate'] .'"'; } ?> />
                            <div class="help-block"><?php echo $_LANG['AD_CALENDAR_FORMAT']; ?></div>
                        </div>
                            
                        <div class="form-group">
                            <?php
                                $sql    = "SELECT * FROM cms_user_groups";
                                $result = cmsCore::c('db')->query($sql) ;

                                $style  = 'disabled="disabled"';
                                $public = 'checked="checked"';

                                if ($do == 'edit') {
                                    $sql2 = "SELECT * FROM cms_content_access WHERE content_id = ".$mod['id']." AND content_type = 'material'";
                                    $result2 = cmsCore::c('db')->query($sql2);
                                    $ord = array();

                                    if (cmsCore::c('db')->num_rows($result2)){
                                        $public = '';
                                        $style = '';
                                        while ($r = cmsCore::c('db')->fetch_assoc($result2)){
                                            $ord[] = $r['group_id'];
                                        }
                                    }
                                }
                            ?>
                            <label>
                                <input name="is_public" type="checkbox" id="is_public" onclick="checkGroupList()" value="1" <?php echo $public?> />
                                <?php echo $_LANG['AD_SHARE']; ?>
                            </label>
                            <div class="help-block"><?php echo $_LANG['AD_IF_NOTED']; ?></div>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_GROUPS_VIEW']; ?></label>
                            <?php
                                echo '<select id="showin" class="form-control" name="showfor[]" size="6" multiple="multiple" '.$style.'>';

                                if (cmsCore::c('db')->num_rows($result)){
                                    while ($item = cmsCore::c('db')->fetch_assoc($result)){
                                        echo '<option value="'.$item['id'].'"';
                                        if ($do=='edit'){
                                            if (in_array($item['id'], $ord)){
                                                echo 'selected="selected"';
                                            }
                                        }

                                        echo '>';
                                        echo $item['title'].'</option>';
                                    }
                                }

                                echo '</select>';
                            ?>
                            <div class="help-block"><?php echo $_LANG['AD_SELECT_MULTIPLE_CTRL']; ?></div>
                        </div>
                    </div>
                        
                    <div id="upr_photos">
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_PHOTO']; ?></label>
                                
                            <?php
                                if ($do == 'edit' && file_exists(PATH.'/images/photos/small/article'. $mod['id'] .'.jpg')){
                            ?>
                            <div style="margin-top:3px;margin-bottom:3px;padding:10px;border:solid 1px gray;text-align:center">
                                <img src="/images/photos/small/article<?php echo $id; ?>.jpg" border="0" />
                            </div>
                            <label>
                                <input type="checkbox" name="delete_image" value="1" />
                                <?php echo $_LANG['AD_PHOTO_REMOVE']; ?>
                            </label>
                            <?php
                                }
                            ?>

                            <input type="file" class="form-control" name="picture" />
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_INSERTED_IMAGES']; ?></label>
                            <?php echo $ajaxUploader; ?>
                        </div>
                    </div>
                        
                    <?php foreach ($tab_plugins as $tab_plugin) { ?>
                        <div id="upr_<?php echo $tab_plugin['name']; ?>"><?php echo $tab_plugin['html']; ?></div>
                    <?php } ?>
                </div>
            </td>
        </tr>
    </table>

    <div>
        <input type="submit" class="btn btn-primary" name="add_mod" <?php if ($do == 'add') { echo 'value="'. $_LANG['AD_CREATE_CONTENT'] .'"'; } else { echo 'value="'. $_LANG['AD_SAVE_CONTENT'] .'"'; } ?> />
        <input type="button" class="btn btn-default" name="back" value="<?php echo $_LANG['CANCEL']; ?>" onclick="window.history.back();"/>
        <input type="hidden" name="do" <?php if ($do == 'add') { echo 'value="submit"'; } else { echo 'value="update"'; } ?> />
        <?php
            if ($do == 'edit') {
                echo '<input type="hidden" name="id" value="'. $mod['id'] .'" />';
            }
        ?>
    </div>
</form>
    <?php
    }
}
示例#8
0
<?php
if(!defined('VALID_CMS')) { die('ACCESS DENIED'); }

/////////////////////////////// ДОБАВЛЕНИЕ ПОСТА ////////////////////////////////////
if (in_array($bdo, array('newpost', 'editpost'))) {
    if ($bdo=='editpost') {
        $post = $inBlog->getPost($post_id);
        
        if (!$post) { cmsCore::error404(); }
        
        $post['tags'] = cmsTagLine($inBlog->getTarget('tags'), $post['id'], false);

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

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

	}

	if($bdo=='newpost'){

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

		$blog = $inBlog->getBlogByUserId($club['id']);
		if (!$blog) { cmsCore::error404(); }

	}

	// если блоги запрещены
示例#9
0
function blog()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    cmsCore::loadClass('blog');
    $inBlog = cmsBlogs::getInstance();
    $inBlog->owner = 'site';
    global $_LANG;
    cmsCore::loadModel('blog');
    $model = new cms_model_blog();
    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) {
        cmsCore::loadClass('billing');
    }
    // Проверяем включени ли компонент
    if (!$model->config['component_enabled']) {
        cmsCore::error404();
    }
    //Получаем параметры
    $id = cmsCore::request('id', 'int', 0);
    $post_id = cmsCore::request('post_id', 'int', 0);
    $seolink = cmsCore::request('seolink', 'str', '');
    $do = cmsCore::request('do', 'str', 'blog');
    $page = cmsCore::request('page', 'int', 1);
    $cat_id = cmsCore::request('cat_id', 'int', 0);
    $ownertype = cmsCore::request('ownertype', 'str', '');
    $on_moderate = cmsCore::request('on_moderate', 'int', 0);
    $pagetitle = $inCore->menuTitle();
    $pagetitle = $pagetitle && $inCore->isMenuIdStrict() ? $pagetitle : $_LANG['RSS_BLOGS'];
    $inPage->addPathway($pagetitle, '/blog');
    $inPage->setTitle($pagetitle);
    $inPage->setDescription($pagetitle);
    $blog_id = 25;
    ////////// НАСТРОЙКИ БЛОГА ////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'config') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        // получаем блог
        $blog = $inBlog->getBlog($id);
        if (!$blog) {
            cmsCore::error404();
        }
        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        //Если нет запроса на сохранение, показываем форму настроек блога
        if (!cmsCore::inRequest('goadd')) {
            //Получаем список авторов блога
            $authors = $inBlog->getBlogAuthors($blog['id']);
            $smarty = $inCore->initSmarty('components', 'com_blog_config.tpl');
            $smarty->assign('blog', $blog);
            $smarty->assign('form_action', '/blog/' . $blog['id'] . '/editblog.html');
            $smarty->assign('authors_list', cmsUser::getAuthorsList($authors));
            $smarty->assign('users_list', cmsUser::getUsersList(false, $authors));
            $smarty->assign('is_restrictions', !$inUser->is_admin && $model->config['min_karma']);
            $smarty->assign('cfg', $model->config);
            $smarty->display('com_blog_config.tpl');
            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }
        //Если пришел запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            if (!cmsCore::validateForm()) {
                cmsCore::halt();
            }
            //Получаем настройки
            $title = cmsCore::request('title', 'str');
            $allow_who = cmsCore::request('allow_who', 'str', 'all');
            $ownertype = cmsCore::request('ownertype', 'str', 'single');
            $premod = cmsCore::request('premod', 'int', 0);
            $forall = cmsCore::request('forall', 'int', 1);
            $showcats = cmsCore::request('showcats', 'int', 1);
            $authors = cmsCore::request('authorslist', 'array_int', array());
            //Проверяем настройки
            if (mb_strlen($title) < 5) {
                $title = $blog['title'];
            }
            //Проверяем ограничения по карме (для смены типа блога)
            if ($model->config['min_karma'] && !$inUser->is_admin) {
                // если персональный блог
                if ($ownertype == 'single' && $inUser->karma < $model->config['min_karma_private']) {
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'] . ' <a href="/users/' . $inUser->id . '/karma.html">' . $_LANG['BLOG_KARMS'] . '</a> ' . $_LANG['FOR_CREATE_PERSON_BLOG'] . ' &mdash; ' . $model->config['min_karma_private'] . ', ' . $_LANG['BLOG_HEAVING'] . ' &mdash; ' . $inUser->karma));
                }
                // если коллективный блог
                if ($ownertype == 'multi' && $inUser->karma < $model->config['min_karma_public']) {
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'] . ' <a href="/users/' . $inUser->id . '/karma.html">' . $_LANG['BLOG_KARMS'] . '</a> ' . $_LANG['FOR_CREATE_TEAM_BLOG'] . ' &mdash; ' . $model->config['min_karma_public'] . ', ' . $_LANG['BLOG_HEAVING'] . ' &mdash; ' . $inUser->karma));
                }
            }
            //сохраняем авторов
            $inBlog->updateBlogAuthors($blog['id'], $authors);
            //сохраняем настройки блога
            $blog['seolink_new'] = $inBlog->updateBlog($blog['id'], array('title' => $title, 'allow_who' => $allow_who, 'showcats' => $showcats, 'ownertype' => $ownertype, 'premod' => $premod, 'forall' => $forall), $model->config['update_seo_link_blog']);
            $blog['seolink'] = $blog['seolink_new'] ? $blog['seolink_new'] : $blog['seolink'];
            if (stripslashes($title) != $blog['title']) {
                // обновляем записи постов
                cmsActions::updateLog('add_post', array('target' => $title, 'target_url' => $model->getBlogURL()), 0, $blog['id']);
                // обновляем запись добавления блога
                cmsActions::updateLog('add_blog', array('object' => $title, 'object_url' => $model->getBlogURL()), $blog['id']);
            }
            // Очищаем токен
            cmsUser::clearCsrfToken();
            cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL()));
        }
    }
    ////////// ПРОСМОТР БЛОГА ////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'blog') {
        // получаем блог
        $blog = $inBlog->getBlog($blog_id);
        if (!$blog) {
            cmsCore::error404();
        }
        // Права доступа
        $myblog = $inUser->id && $inUser->id == $blog['user_id'];
        // автор блога
        $is_writer = $inBlog->isUserBlogWriter($blog, $inUser->id);
        // может ли пользователь писать в блог
        // Заполняем head страницы
        $inPage->setTitle($blog['title']);
        //$inPage->addPathway($blog['title'], $model->getBlogURL($blog['seolink']));
        $inPage->setDescription($blog['title']);
        // rss в адресной строке
        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . htmlspecialchars(strip_tags($blog['title'])) . '" href="' . HOST . '/rss/blogs/' . $blog['id'] . '/feed.rss">');
        if ($myblog || $inUser->is_admin) {
            $inPage->addHeadJS('components/blog/js/blog.js');
        }
        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'] . '<br>' . $_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/');
        }
        // Если показываем посты на модерации, если запрашиваем их
        if ($on_moderate) {
            if (!$inUser->is_admin && !($myblog && $blog['ownertype'] == 'multi' && $blog['premod'])) {
                cmsCore::error404();
            }
            $inBlog->whereNotPublished();
            $inPage->setTitle($_LANG['POSTS_ON_MODERATE']);
            $inPage->addPathway($_LANG['POSTS_ON_MODERATE']);
            $blog['title'] .= ' - ' . $_LANG['POSTS_ON_MODERATE'];
        }
        //Получаем html-код ссылки на автора с иконкой его пола
        $blog['author'] = cmsUser::getGenderLink($blog['user_id']);
        // посты данного блога
        $inBlog->whereBlogIs($blog['id']);
        // кроме админов автора в списке только с доступом для всех
        if (!$inUser->is_admin && !$myblog) {
            $inBlog->whereOnlyPublic();
        }
        // если пришла категория
        if ($cat_id) {
            $all_total = $inBlog->getPostsCount($inUser->is_admin || $myblog);
            $inBlog->whereCatIs($cat_id);
        }
        // всего постов
        $total = $inBlog->getPostsCount($inUser->is_admin || $myblog);
        //устанавливаем сортировку
        $inDB->orderBy('p.pubdate', 'DESC');
        $inDB->limitPage($page, $model->config['perpage']);
        // сами посты
        $posts = $inBlog->getPosts($inUser->is_admin || $myblog, $model);
        if (!$posts && $page > 1) {
            cmsCore::error404();
        }
        //Если нужно, получаем список рубрик (категорий) этого блога
        $blogcats = $blog['showcats'] ? $inBlog->getBlogCats($blog['id']) : false;
        //Считаем количество постов, ожидающих модерации
        $on_moderate = ($inUser->is_admin || $myblog) && !$on_moderate ? $inBlog->getModerationCount($blog['id']) : false;
        // админлинки
        $blog['moderate_link'] = $model->getBlogURL() . '/moderate.html';
        $blog['blog_link'] = $model->getBlogURL();
        $blog['add_post_link'] = '/blog/newpost' . ($cat_id ? $cat_id : '') . '.html';
        //Генерируем панель со страницами
        if ($cat_id) {
            $pagination = cmsPage::getPagebar($total, $page, $model->config['perpage'], $blog['blog_link'] . '/page-%page%/cat-' . $cat_id);
        } else {
            $pagination = cmsPage::getPagebar($total, $page, $model->config['perpage'], $blog['blog_link'] . '/page-%page%');
        }
        $smarty = $inCore->initSmarty('components', 'com_blog_view.tpl');
        $smarty->assign('myblog', $myblog);
        $smarty->assign('is_config', true);
        $smarty->assign('is_admin', $inUser->is_admin);
        $smarty->assign('is_writer', $is_writer);
        $smarty->assign('on_moderate', $on_moderate);
        $smarty->assign('cat_id', $cat_id);
        $smarty->assign('blogcats', $blogcats);
        $smarty->assign('total', $total);
        $smarty->assign('all_total', isset($all_total) ? $all_total : 0);
        $smarty->assign('blog', $blog);
        $smarty->assign('posts', $posts);
        $smarty->assign('pagination', $pagination);
        $smarty->display('com_blog_view.tpl');
    }
    ////////// НОВЫЙ ПОСТ / РЕДАКТИРОВАНИЕ ПОСТА //////////////////////////////////////////////////////////////////
    if ($do == 'newpost' || $do == 'editpost') {
        // для редактирования сначала получаем пост
        if ($do == 'editpost') {
            $post = $inBlog->getPost($post_id);
            if (!$post) {
                cmsCore::error404();
            }
            $id = $post['blog_id'];
            $post['tags'] = cmsTagLine('blogpost', $post['id'], false);
        }
        // получаем блог
        $blog = $inBlog->getBlog($blog_id);
        if (!$blog) {
            cmsCore::error404();
        }
        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'] . '<br>' . $_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blog');
        }
        // Права доступа
        $myblog = $inUser->id && $inUser->id == $blog['user_id'];
        // автор блога
        $is_writer = $inBlog->isUserBlogWriter($blog, $inUser->id);
        // может ли пользователь писать в блог
        // если не его блог, пользователь не писатель и не админ, вне зависимости от авторства показываем 404
        if (!$myblog && !$is_writer && !$inUser->is_admin) {
            cmsCore::error404();
        }
        // проверяем является ли пользователь автором, если редактируем пост
        if ($do == 'editpost' && !$inUser->is_admin && $post['user_id'] != $inUser->id) {
            cmsCore::error404();
        }
        //Если еще не было запроса на сохранение
        if (!cmsCore::inRequest('goadd')) {
            $inPage->addPathway($blog['title'], $model->getBlogURL());
            //для нового поста
            if ($do == 'newpost') {
                if (IS_BILLING) {
                    cmsBilling::checkBalance('blogs', 'add_post');
                }
                $inPage->addPathway($_LANG['NEW_POST']);
                $inPage->setTitle($_LANG['NEW_POST']);
                $post = cmsUser::sessionGet('mod');
                if ($post) {
                    cmsUser::sessionDel('mod');
                } else {
                    $post['cat_id'] = $cat_id;
                    $post['comments'] = 1;
                }
            }
            //для редактирования поста
            if ($do == 'editpost') {
                $inPage->addPathway($post['title'], $model->getPostURL('', $post['seolink']));
                $inPage->addPathway($_LANG['EDIT_POST']);
                $inPage->setTitle($_LANG['EDIT_POST']);
            }
            $inPage->initAutocomplete();
            $autocomplete_js = $inPage->getAutocompleteJS('tagsearch', 'tags');
            //получаем рубрики блога
            $cat_list = cmsCore::getListItems('cms_blog_cats', $post['cat_id'], 'id', 'ASC', "blog_id = '{$blog['id']}'");
            //получаем код панелей bbcode и смайлов
            $bb_toolbar = cmsPage::getBBCodeToolbar('message', $model->config['img_on'], 'blogs', 'post', $post_id);
            $smilies = cmsPage::getSmilesPanel('message');
            $inCore->initAutoGrowText('#message');
            //показываем форму
            $smarty = $inCore->initSmarty('components', 'com_blog_edit_post.tpl');
            $smarty->assign('blog', $blog);
            $smarty->assign('pagetitle', $do == 'editpost' ? $_LANG['EDIT_POST'] : $_LANG['NEW_POST']);
            $smarty->assign('mod', $post);
            $smarty->assign('cat_list', $cat_list);
            $smarty->assign('bb_toolbar', $bb_toolbar);
            $smarty->assign('smilies', $smilies);
            $smarty->assign('is_admin', $inUser->is_admin);
            $smarty->assign('myblog', $myblog);
            $smarty->assign('user_can_iscomments', cmsUser::isUserCan('comments/iscomments'));
            $smarty->assign('autocomplete_js', $autocomplete_js);
            $smarty->display('com_blog_edit_post.tpl');
        }
        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            $error = false;
            //Получаем параметры
            $mod['title'] = cmsCore::request('title', 'str');
            $mod['content'] = cmsCore::request('content', 'html');
            $mod['feel'] = cmsCore::request('feel', 'str', '');
            $mod['music'] = cmsCore::request('music', 'str', '');
            $mod['cat_id'] = cmsCore::request('cat_id', 'int');
            $mod['allow_who'] = cmsCore::request('allow_who', 'str', $blog['allow_who']);
            $mod['tags'] = cmsCore::request('tags', 'str', '');
            $mod['comments'] = cmsCore::request('comments', 'int', 1);
            $mod['published'] = $myblog || !$blog['premod'] ? 1 : 0;
            $mod['blog_id'] = $blog['id'];
            //Проверяем их
            if (mb_strlen($mod['title']) < 2) {
                cmsCore::addSessionMessage($_LANG['POST_ERR_TITLE'], 'error');
                $errors = true;
            }
            if (mb_strlen($mod['content']) < 5) {
                cmsCore::addSessionMessage($_LANG['POST_ERR_TEXT'], 'error');
                $errors = true;
            }
            // Если есть ошибки, возвращаемся назад
            if ($errors) {
                cmsUser::sessionPut('mod', $mod);
                cmsCore::redirectBack();
            }
            //Если нет ошибок
            //добавляем новый пост...
            if ($do == 'newpost') {
                if (IS_BILLING) {
                    cmsBilling::process('blogs', 'add_post');
                }
                $mod['pubdate'] = date('Y-m-d H:i:s');
                $mod['user_id'] = $inUser->id;
                // добавляем пост, получая его id и seolink
                $added = $inBlog->addPost($mod);
                if ($mod['published']) {
                    if ($blog['allow_who'] != 'nobody' && $mod['allow_who'] != 'nobody') {
                        cmsActions::log('add_post', array('object' => $mod['title'], 'object_url' => $model->getPostURL('', $added['seolink']), 'object_id' => $added['id'], 'target' => $blog['title'], 'target_url' => $model->getBlogURL(), 'target_id' => $blog['id'], 'description' => '', 'is_friends_only' => (int) ($blog['allow_who'] == 'friends' || $mod['allow_who'] == 'friends')));
                    }
                    cmsCore::addSessionMessage($_LANG['POST_CREATED'], 'success');
                    cmsCore::redirect($model->getPostURL('', $added['seolink']));
                }
                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_POST_SUBMIT']);
                    $message = str_replace('%post%', '<a href="' . $model->getPostURL('', $added['seolink']) . '">' . $mod['title'] . '</a>', $message);
                    $message = str_replace('%blog%', '<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>', $message);
                    cmsUser::sendMessage(USER_UPDATER, $blog['user_id'], $message);
                    cmsCore::addSessionMessage($_LANG['POST_PREMODER_TEXT'], 'info');
                    cmsCore::redirect($model->getBlogURL());
                }
            }
            //...или сохраняем пост после редактирования
            if ($do == 'editpost') {
                if ($model->config['update_date']) {
                    $mod['pubdate'] = date('Y-m-d H:i:s');
                }
                $mod['edit_times'] = (int) $post['edit_times'] + 1;
                $new_post_seolink = $inBlog->updatePost($post['id'], $mod, $model->config['update_seo_link']);
                $post['seolink'] = is_string($new_post_seolink) ? $new_post_seolink : $post['seolink'];
                cmsActions::updateLog('add_post', array('object' => $mod['title'], 'pubdate' => $model->config['update_date'] ? $mod['pubdate'] : $post['pubdate'], 'object_url' => $model->getPostURL('', $post['seolink'])), $post['id']);
                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_POST_UPDATE']);
                    $message = str_replace('%post%', '<a href="' . $model->getPostURL('', $post['seolink']) . '">' . $mod['title'] . '</a>', $message);
                    $message = str_replace('%blog%', '<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>', $message);
                    cmsUser::sendMessage(USER_UPDATER, $blog['user_id'], $message);
                    cmsCore::addSessionMessage($_LANG['POST_PREMODER_TEXT'], 'info');
                } else {
                    cmsCore::addSessionMessage($_LANG['POST_UPDATED'], 'success');
                }
                cmsCore::redirect($model->getPostURL('', $post['seolink']));
            }
        }
    }
    ////////// НОВАЯ РУБРИКА / РЕДАКТИРОВАНИЕ РУБРИКИ //////////////////////////////////////////////////////
    if ($do == 'newcat' || $do == 'editcat') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        // Для редактирования сначала получаем рубрику
        if ($do == 'editcat') {
            $cat = $inBlog->getBlogCategory($cat_id);
            if (!$cat) {
                cmsCore::halt();
            }
            $id = $cat['blog_id'];
        }
        // получаем блог
        $blog = $inBlog->getBlog($id);
        if (!$blog) {
            cmsCore::halt();
        }
        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        //Если нет запроса на сохранение
        if (!cmsCore::inRequest('goadd')) {
            $smarty = $inCore->initSmarty('components', 'com_blog_edit_cat.tpl');
            $smarty->assign('mod', $cat);
            $smarty->assign('form_action', $do == 'newcat' ? '/blog/' . $blog['id'] . '/newcat.html' : '/blog/editcat' . $cat['id'] . '.html');
            $smarty->display('com_blog_edit_cat.tpl');
            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }
        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            if (!cmsCore::validateForm()) {
                cmsCore::halt();
            }
            $new_cat['title'] = cmsCore::request('title', 'str', '');
            $new_cat['description'] = cmsCore::request('description', 'str', '');
            $new_cat['blog_id'] = $blog['id'];
            if (mb_strlen($new_cat['title']) < 3) {
                cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CAT_ERR_TITLE']));
            }
            //новая рубрика
            if ($do == 'newcat') {
                $cat['id'] = $inBlog->addBlogCategory($new_cat);
                cmsCore::addSessionMessage($_LANG['CAT_IS_ADDED'], 'success');
            }
            //редактирование рубрики
            if ($do == 'editcat') {
                $inBlog->updateBlogCategory($cat['id'], $new_cat);
                cmsCore::addSessionMessage($_LANG['CAT_IS_UPDATED'], 'success');
            }
            cmsUser::clearCsrfToken();
            cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL(1, $cat['id'])));
        }
    }
    ///////////////////////// УДАЛЕНИЕ РУБРИКИ /////////////////////////////////////////////////////////////////////////
    if ($do == 'delcat') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $cat = $inBlog->getBlogCategory($cat_id);
        if (!$cat) {
            cmsCore::halt();
        }
        $blog = $inBlog->getBlog($cat['blog_id']);
        if (!$blog) {
            cmsCore::halt();
        }
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        if (!cmsCore::validateForm()) {
            cmsCore::halt();
        }
        $inBlog->deleteBlogCategory($cat['id']);
        cmsCore::addSessionMessage($_LANG['CAT_IS_DELETED'], 'success');
        cmsUser::clearCsrfToken();
        cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL()));
    }
    ////////////////////////// ПРОСМОТР ПОСТА /////////////////////////////////////////////////////////////////////////
    if ($do == 'post') {
        $post = $inBlog->getPost($seolink);
        if (!$post) {
            cmsCore::error404();
        }
        $blog = $inBlog->getBlog($post['blog_id']);
        if (!$blog) {
            cmsCore::error404();
        }
        // право просмотра блога
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'] . '<br>' . $_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blog');
        }
        // право просмотра самого поста
        if (!cmsUser::checkUserContentAccess($post['allow_who'], $post['user_id'])) {
            cmsCore::addSessionMessage($_LANG['CLOSED_POST'] . '<br>' . $_LANG['CLOSED_POST_TEXT'], 'error');
            cmsCore::redirect($model->getBlogURL());
        }
        if ($inUser->id) {
            $inPage->addHeadJS('components/blog/js/blog.js');
        }
        $inPage->addPathway($blog['title'], $model->getBlogURL());
        $inPage->setTitle($post['title']);
        $inPage->addPathway($post['title']);
        $inPage->setDescription($post['title']);
        if ($post['cat_id']) {
            $cat = $inBlog->getBlogCategory($post['cat_id']);
        }
        $post['tags'] = cmsTagBar('blogpost', $post['id']);
        $is_author = $inUser->id && $inUser->id == $post['user_id'];
        $smarty = $inCore->initSmarty('components', 'com_blog_view_post.tpl');
        $smarty->assign('post', $post);
        $smarty->assign('blog', $blog);
        $smarty->assign('cat', $cat);
        $smarty->assign('is_author', $is_author);
        $smarty->assign('myblog', $inUser->id && $inUser->id == $blog['user_id']);
        $smarty->assign('is_admin', $inUser->is_admin);
        $smarty->assign('karma_form', cmsKarmaForm('blogpost', $post['id'], $post['rating'], $is_author));
        $smarty->assign('navigation', $inBlog->getPostNavigation($post['id'], $blog['id'], $model, $blog['seolink']));
        $smarty->display('com_blog_view_post.tpl');
        if ($inCore->isComponentInstalled('comments') && $post['comments']) {
            cmsCore::includeComments();
            comments('blog', $post['id']);
        }
    }
    ///////////////////////// УДАЛЕНИЕ ПОСТА /////////////////////////////////////////////////////////////////////////////
    if ($do == 'delpost') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $post = $inBlog->getPost($post_id);
        if (!$post) {
            cmsCore::halt();
        }
        $blog = $inBlog->getBlog($post['blog_id']);
        if (!$blog) {
            cmsCore::halt();
        }
        // удалять могут авторы, авторы блога, админы
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin && $inUser->id != $post['user_id']) {
            cmsCore::halt();
        }
        if (!cmsCore::validateForm()) {
            cmsCore::halt();
        }
        $inBlog->deletePost($post['id']);
        if ($inUser->id != $post['user_id']) {
            cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'] . ' <b>&laquo;' . $post['title'] . '&raquo;</b> ' . $_LANG['WAS_DELETED_FROM_BLOG'] . ' <b>&laquo;<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>&raquo;</b>');
        }
        cmsCore::addSessionMessage($_LANG['POST_IS_DELETED'], 'success');
        cmsUser::clearCsrfToken();
        cmsCore::jsonOutput(array('error' => false, 'redirect' => $model->getBlogURL()));
    }
    ///////////////////////// ПУБЛИКАЦИЯ ПОСТА /////////////////////////////////////////////////////////////////////////
    if ($do == 'publishpost') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $post = $inBlog->getPost($post_id);
        if (!$post) {
            cmsCore::halt();
        }
        $blog = $inBlog->getBlog($post['blog_id']);
        if (!$blog) {
            cmsCore::halt();
        }
        // публикуют авторы блога и админы
        if ($blog['user_id'] != $inUser->id && !$inUser->is_admin) {
            cmsCore::halt();
        }
        $inBlog->publishPost($post_id);
        if ($blog['allow_who'] == 'all' && $post['allow_who'] == 'all') {
            cmsCore::callEvent('ADD_POST_DONE', $post);
        }
        $post['seolink'] = $model->getPostURL('', $post['seolink']);
        if ($blog['allow_who'] != 'nobody' && $post['allow_who'] != 'nobody') {
            cmsActions::log('add_post', array('object' => $post['title'], 'user_id' => $post['user_id'], 'object_url' => $post['seolink'], 'object_id' => $post['id'], 'target' => $blog['title'], 'target_url' => $model->getBlogURL(), 'target_id' => $blog['id'], 'description' => '', 'is_friends_only' => (int) ($blog['allow_who'] == 'friends' || $post['allow_who'] == 'friends')));
        }
        cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'] . ' <b>&laquo;<a href="' . $post['seolink'] . '">' . $post['title'] . '</a>&raquo;</b> ' . $_LANG['PUBLISHED_IN_BLOG'] . ' <b>&laquo;<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>&raquo;</b>');
        cmsCore::halt('ok');
    }
    ////////// VIEW POPULAR POSTS ////////////////////////////////////////////////////////////////////////////////////////
    if ($do == 'best') {
        $inPage->setTitle($_LANG['POPULAR_IN_BLOGS']);
        $inPage->addPathway($_LANG['POPULAR_IN_BLOGS']);
        $inPage->setDescription($_LANG['POPULAR_IN_BLOGS']);
        // кроме админов в списке только с доступом для всех
        if (!$inUser->is_admin) {
            $inBlog->whereOnlyPublic();
        }
        // ограничиваем по рейтингу если надо
        if ($model->config['list_min_rating']) {
            $inBlog->ratingGreaterThan($model->config['list_min_rating']);
        }
        // всего постов
        $total = $inBlog->getPostsCount($inUser->is_admin);
        //устанавливаем сортировку
        $inDB->orderBy('p.rating', 'DESC');
        $inDB->limitPage($page, $model->config['perpage']);
        // сами посты
        $posts = $inBlog->getPosts($inUser->is_admin, $model);
        if (!$posts && $page > 1) {
            cmsCore::error404();
        }
        $smarty = $inCore->initSmarty('components', 'com_blog_view_posts.tpl');
        $smarty->assign('pagetitle', $_LANG['POPULAR_IN_BLOGS']);
        $smarty->assign('total', $total);
        $smarty->assign('ownertype', $ownertype);
        $smarty->assign('posts', $posts);
        $smarty->assign('pagination', cmsPage::getPagebar($total, $page, $model->config['perpage'], '/blogs/popular-%page%.html'));
        $smarty->assign('cfg', $model->config);
        $smarty->display('com_blog_view_posts.tpl');
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    $inCore->executePluginRoute($do);
}
    cmsCore::halt();
}
if (!$item_id) {
    cmsCore::jsonOutput(array('error' => true, 'html' => ' Не получен идентификатор записи!'));
    cmsCore::halt();
}
//библиотека тегов
cmsCore::includeFile('/core/lib_tags.php');
//шаблон формы редактирования
$template = 'p_front_editor_' . $component . '.tpl';
//получаем запись для редактирования
$item = $inDB->get_fields('cms_' . $component, "id = {$item_id}", '*');
// теги статьи
if ($item) {
    $target = $component == 'blog_posts' ? 'blogpost' : $component;
    $item['tags'] = cmsTagLine("{$target}", $item_id, false);
}
if (!$item) {
    cmsCore::jsonOutput(array('error' => true, 'html' => ' Не получена запись для редактирования!'));
    cmsCore::halt();
}
//изображение статьи для формы редактирования статей
if ($component == 'content') {
    $item['image'] = file_exists(PATH . '/images/photos/medium/article' . $item['id'] . '.jpg') ? 'article' . $item['id'] . '.jpg' : '';
}
//html-код формы
$html = '';
ob_start();
$smarty = cmsPage::initTemplate('plugins', $template);
$smarty->assign('item', $item);
$smarty->assign('csrf_token', cmsUser::getCsrfToken());
示例#11
0
文件: model.php 项目: deltas1/icms1
 /**
  * Получаем статьи по заданным параметрам
  * @return array
  */
 public function getArticlesList($only_published = true)
 {
     $today = date("Y-m-d H:i:s");
     if ($only_published) {
         $this->inDB->where("con.published = 1 AND con.pubdate <= '{$today}' AND (con.is_end=0 OR (con.is_end=1 AND con.enddate >= '{$today}'))");
     }
     $sql = "SELECT con.*,\r\n\t\t\t\t\t   cat.title as cat_title, cat.seolink as catseolink,\r\n\t\t\t\t\t   cat.showdesc,\r\n                       u.nickname as author,\r\n                       u.login as user_login\r\n                FROM cms_content con\r\n\t\t\t\tINNER JOIN cms_category cat ON cat.id = con.category_id\r\n\t\t\t\tLEFT JOIN cms_users u ON u.id = con.user_id\r\n                WHERE con.is_arhive = 0\r\n                      {$this->inDB->where}\r\n\r\n                {$this->inDB->group_by}\r\n\r\n                {$this->inDB->order_by}\n";
     if ($this->inDB->limit) {
         $sql .= "LIMIT {$this->inDB->limit}";
     }
     $result = $this->inDB->query($sql);
     $this->inDB->resetConditions();
     if (!$this->inDB->num_rows($result)) {
         return false;
     }
     while ($article = $this->inDB->fetch_assoc($result)) {
         $article['fpubdate'] = cmsCore::dateFormat($article['pubdate']);
         $article['ffpubdate'] = date('c', strtotime($article['pubdate']));
         $article['tagline'] = cmsTagLine('content', $article['id'], true);
         $article['comments'] = cmsCore::getCommentsCount('article', $article['id']);
         $article['url'] = $this->getArticleURL(null, $article['seolink']);
         $article['cat_url'] = $this->getCategoryURL(null, $article['catseolink']);
         $article['image'] = file_exists(PATH . '/images/photos/small/article' . $article['id'] . '.jpg') ? 'article' . $article['id'] . '.jpg' : '';
         $articles[] = $article;
     }
     $articles = cmsCore::callEvent('GET_ARTICLES', $articles);
     return translations::process(cmsConfig::getConfig('lang'), 'content_content', $articles);
 }
示例#12
0
        <?php 
    if ($do == 'add_photo') {
        ?>
        <tr>
        <td>Cохранить оригинал: </td>
        <td><input name="saveorig" type="radio" value="1" checked="checked" />Да<input name="saveorig" type="radio" value="0"  />Нет</label></td>
        </tr>
        <?php 
    }
    ?>
        <tr>
            <td valign="top">Теги фотографии: <br />
            <span class="hinttext">Ключевые слова, через запятую</span></td>
            <td valign="top"><input name="tags" type="text" id="tags" size="45" value="<?php 
    if (isset($mod['id'])) {
        echo cmsTagLine('photo', $mod['id'], false);
    }
    ?>
" /></td>
        </tr>
        </table>
        <table width="100%" border="0">
            <tr>
                <?php 
    if (!isset($mod['user']) || @$mod['user'] == 1) {
        echo '<td width="52%" valign="top">';
        echo 'Описание фотографии:<br/>';
        $inCore->insertEditor('description', $mod['description'], '260', '605');
        echo '</td>';
    }
    ?>
示例#13
0
文件: model.php 项目: Acsac/CMS-RuDi
    /**
     * Получаем статьи по заданным параметрам
     * @return array
     */
    public function getArticlesList($only_published=true) {
        $today = date("Y-m-d H:i:s");

        if ($only_published) {
            cmsCore::c('db')->where("con.published = 1 AND con.pubdate <= '". $today ."'");
        }

        $sql = "SELECT con.*,
                    con.pubdate as fpubdate,
                    cat.title as cat_title, cat.seolink as catseolink,
                    cat.showdesc,
                    u.nickname as author,
                    u.login as user_login
                FROM cms_content con
                INNER JOIN cms_category cat ON cat.id = con.category_id
                LEFT JOIN cms_users u ON u.id = con.user_id
                WHERE con.is_arhive = 0
                ". cmsCore::c('db')->where ."
                ". cmsCore::c('db')->group_by ."
                ". cmsCore::c('db')->order_by. "\n";

        if (cmsCore::c('db')->limit) {
            $sql .= "LIMIT ". cmsCore::c('db')->limit;
        }

        $result = cmsCore::c('db')->query($sql);

        cmsCore::c('db')->resetConditions();

        if (!cmsCore::c('db')->num_rows($result)) { return false; }

        while ($article = cmsCore::c('db')->fetch_assoc($result)) {
            $article['fpubdate'] = cmsCore::dateFormat($article['fpubdate']);
            $article['tagline']  = cmsTagLine('content', $article['id'], true);
            $article['comments'] = cmsCore::getCommentsCount('article', $article['id']);
            $article['url']      = $this->getArticleURL(null, $article['seolink']);
            $article['cat_url']  = $this->getCategoryURL(null, $article['catseolink']);
            
            if (file_exists(PATH .'/images/content/medium/'. ceil($article['id']/100) .'/article'. $article['id' ] .'.jpg')) {
                $article['image'] = '/images/content/medium/'. ceil($article['id']/100) .'/article'. $article['id' ] .'.jpg';
                $article['image_small'] = '/images/content/small/'. ceil($article['id']/100) .'/article'. $article['id' ] .'.jpg';
            }
            
            if (!empty($article['images'])) { $article['images'] = json_decode($article['images'], true); }
            
            $articles[] = $article;
        }

        $articles = cmsCore::callEvent('GET_ARTICLES', $articles);

        return $articles;
    }
示例#14
0
 /**
  * Получаем статьи по id категориям
  * @return array
  */
 public function getArticlesList2($only_published = true, $cat_id = '1')
 {
     $today = date("Y-m-d H:i:s");
     if ($only_published) {
         $this->inDB->where("con.published = 1 AND con.pubdate <= '{$today}' AND (con.is_end=0 OR (con.is_end=1 AND con.enddate >= '{$today}')) AND con.category_id = '{$cat_id}'");
     }
     $sql = "SELECT con.*,\n                       con.pubdate as fpubdate,\n\t\t\t\t\t   cat.title as cat_title, cat.seolink as catseolink,\n\t\t\t\t\t   cat.showdesc, cat.description as catdescription,\n                       u.nickname as author,\n                       u.login as user_login\n                FROM cms_content con\n\t\t\t\tINNER JOIN cms_category cat ON cat.id = con.category_id\n\t\t\t\tLEFT JOIN cms_users u ON u.id = con.user_id\n                WHERE con.is_arhive = 0\n                      {$this->inDB->where}\n\n                {$this->inDB->group_by}\n\n                ORDER BY con.ordering\n";
     if ($this->inDB->limit) {
         $sql .= "LIMIT {$this->inDB->limit}";
     }
     $result = $this->inDB->query($sql);
     $this->inDB->resetConditions();
     if (!$this->inDB->num_rows($result)) {
         return false;
     }
     while ($article = $this->inDB->fetch_assoc($result)) {
         $article['fpubdate'] = cmsCore::dateFormat($article['fpubdate']);
         $article['tagline'] = cmsTagLine('content', $article['id'], true);
         $article['comments'] = cmsCore::getCommentsCount('article', $article['id']);
         $article['url'] = $this->getArticleURL(null, $article['seolink']);
         $article['cat_url'] = $this->getCategoryURL(null, $article['catseolink']);
         if (isset($_SESSION['lang']) && $_SESSION['lang'] != 'ru') {
             $article['image'] = file_exists(PATH . '/images/photos/small/article' . $article['id'] . '_' . $_SESSION['lang'] . '.jpg') ? 'article' . $article['id'] . '_' . $_SESSION['lang'] . '.jpg' : '';
         } else {
             $article['image'] = file_exists(PATH . '/images/photos/small/article' . $article['id'] . '.jpg') ? 'article' . $article['id'] . '.jpg' : '';
         }
         $articles[] = $article;
     }
     $articles = cmsCore::callEvent('GET_ARTICLES', $articles);
     return $articles;
 }
示例#15
0
                <div style="margin-top:12px"><strong>Краткое описание</strong></div>
                <div><?php 
$inCore->insertEditor('shortdesc', $item['shortdesc'], '200', '100%');
?>
</div>

                <div style="margin-top:12px"><strong>Подробное описание</strong></div>
                <div><?php 
$inCore->insertEditor('description', $item['description'], '400', '100%');
?>
</div>

                <div style="margin-top:12px"><strong>Теги объекта</strong></div>
                <div><input name="tags" type="text" id="tags" style="width:99%" value="<?php 
if (isset($item['id'])) {
    echo cmsTagLine('map', $item['id'], false);
}
?>
" /></div>

                <?php 
if ($do == 'edit_item') {
    if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/images/photos/small/map' . $item['id'] . '.jpg')) {
        ?>
                                <div style="margin-top:3px;margin-bottom:3px;padding:10px;border:solid 1px gray;text-align:center">
                                    <img src="/images/photos/small/map<?php 
        echo $item['id'];
        ?>
.jpg" border="0" />
                                    <div>
                                        <label><input type="checkbox" name="img_delete[]" class="input" value="map<?php 
示例#16
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();
    }

}
示例#17
0
文件: content.php 项目: vityapro/cms
function applet_content()
{
    $inCore = cmsCore::getInstance();
    $inUser = cmsUser::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    //check access
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/content', $adminAccess)) {
        cpAccessDenied();
    }
    $cfg = $inCore->loadComponentConfig('content');
    cmsCore::loadModel('content');
    $model = new cms_model_content();
    $GLOBALS['cp_page_title'] = $_LANG['AD_ARTICLES'];
    cpAddPathway($_LANG['AD_ARTICLES'], 'index.php?view=tree');
    $do = cmsCore::request('do', 'str', 'add');
    $id = cmsCore::request('id', 'int', -1);
    if ($do == 'arhive_on') {
        $inDB->query("UPDATE cms_content SET is_arhive = 1 WHERE id = '{$id}'");
        cmsCore::addSessionMessage($_LANG['AD_ARTICLES_TO_ARHIVE'], 'success');
        cmsCore::redirectBack();
    }
    if ($do == 'move') {
        $item_id = cmsCore::request('id', 'int', 0);
        $cat_id = cmsCore::request('cat_id', 'int', 0);
        $dir = $_REQUEST['dir'];
        $step = 1;
        $model->moveItem($item_id, $cat_id, $dir, $step);
        echo '1';
        exit;
    }
    if ($do == 'move_to_cat') {
        $items = cmsCore::request('item', 'array_int');
        $to_cat_id = cmsCore::request('obj_id', 'int', 0);
        if ($items && $to_cat_id) {
            $last_ordering = (int) $inDB->get_field('cms_content', "category_id = '{$to_cat_id}' ORDER BY ordering DESC", 'ordering');
            foreach ($items as $item_id) {
                $article = $model->getArticle($item_id);
                if (!$article) {
                    continue;
                }
                $last_ordering++;
                $model->updateArticle($article['id'], array('category_id' => $to_cat_id, 'ordering' => $last_ordering, 'url' => $article['url'], 'title' => $inDB->escape_string($article['title']), 'id' => $article['id'], 'user_id' => $article['user_id']));
            }
            cmsCore::addSessionMessage($_LANG['AD_ARTICLES_TO'], 'success');
        }
        cmsCore::redirect('?view=tree&cat_id=' . $to_cat_id);
    }
    if ($do == 'show') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbShow('cms_content', $id);
            }
            echo '1';
            exit;
        } else {
            dbShowList('cms_content', cmsCore::request('item', 'array_int'));
            cmsCore::redirectBack();
        }
    }
    if ($do == 'hide') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbHide('cms_content', $id);
            }
            echo '1';
            exit;
        } else {
            dbHideList('cms_content', cmsCore::request('item', 'array_int'));
            cmsCore::redirectBack();
        }
    }
    if ($do == 'delete') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                $model->deleteArticle($id);
                cmsCore::addSessionMessage($_LANG['AD_ARTICLE_REMOVE'], 'success');
            }
        } else {
            $model->deleteArticles(cmsCore::request('item', 'array_int'));
            cmsCore::addSessionMessage($_LANG['AD_ARTICLES_REMOVE'], 'success');
        }
        cmsCore::redirectBack();
    }
    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        if (isset($_REQUEST['id'])) {
            $id = cmsCore::request('id', 'int', 0);
            $article['category_id'] = cmsCore::request('category_id', 'int', 1);
            $article['title'] = cmsCore::request('title', 'str');
            $article['url'] = cmsCore::request('url', 'str');
            $article['showtitle'] = cmsCore::request('showtitle', 'int', 0);
            $article['description'] = cmsCore::request('description', 'html', '');
            $article['description'] = $inDB->escape_string($article['description']);
            $article['content'] = cmsCore::request('content', 'html', '');
            $article['content'] = $inDB->escape_string($article['content']);
            $article['for_img'] = cmsCore::request('for_img', 'html', '');
            $article['for_img'] = $inDB->escape_string($article['for_img']);
            $article['published'] = cmsCore::request('published', 'int', 0);
            $article['showdate'] = cmsCore::request('showdate', 'int', 0);
            $article['showlatest'] = cmsCore::request('showlatest', 'int', 0);
            $article['show_in_new'] = cmsCore::request('show_in_new', 'int', 0);
            //new
            $article['show_in_footer'] = cmsCore::request('show_in_footer', 'int', 0);
            //new
            $article['showpath'] = cmsCore::request('showpath', 'int', 0);
            $article['comments'] = cmsCore::request('comments', 'int', 0);
            $article['canrate'] = cmsCore::request('canrate', 'int', 0);
            $article['add_text'] = cmsCore::request('add_text', 'str');
            $enddate = explode('.', cmsCore::request('enddate', 'str'));
            $article['enddate'] = $enddate[2] . '-' . $enddate[1] . '-' . $enddate[0];
            $article['is_end'] = cmsCore::request('is_end', 'int', 0);
            $article['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
            $article['tags'] = cmsCore::request('tags', 'str');
            $olddate = cmsCore::request('olddate', 'str', '');
            $pubdate = cmsCore::request('pubdate', 'str', '');
            $article['user_id'] = cmsCore::request('user_id', 'int', $inUser->id);
            $article['tpl'] = cmsCore::request('tpl', 'str', 'com_content_read.tpl');
            $date = explode('.', $pubdate);
            $article['pubdate'] = $date[2] . '-' . $date[1] . '-' . $date[0] . ' ' . date('H:i');
            $autokeys = cmsCore::request('autokeys', 'int');
            switch ($autokeys) {
                case 1:
                    $article['meta_keys'] = $inCore->getKeywords($article['content']);
                    $article['meta_desc'] = $article['title'];
                    break;
                case 2:
                    $article['meta_desc'] = strip_tags($article['description']);
                    $article['meta_keys'] = $article['tags'];
                    break;
                case 3:
                    $article['meta_desc'] = cmsCore::request('meta_desc', 'str');
                    $article['meta_keys'] = cmsCore::request('meta_keys', 'str');
                    break;
            }
            $model->updateArticle($id, $article);
            if (!cmsCore::request('is_public', 'int', 0)) {
                $showfor = $_REQUEST['showfor'];
                cmsCore::setAccess($id, $showfor, 'material');
            } else {
                cmsCore::clearAccess($id, 'material');
            }
            if (isset($_SESSION['lang']) && $_SESSION['lang'] != 'ru') {
                $file = 'article' . $id . '_' . $_SESSION['lang'] . '.jpg';
            } else {
                $file = 'article' . $id . '.jpg';
            }
            //$file = 'article'.$id.'.jpg';
            if (cmsCore::request('delete_image', 'int', 0)) {
                @unlink(PATH . "/images/photos/small/{$file}");
                @unlink(PATH . "/images/photos/medium/{$file}");
            } else {
                // Загружаем класс загрузки фото
                cmsCore::loadClass('upload_photo');
                $inUploadPhoto = cmsUploadPhoto::getInstance();
                // Выставляем конфигурационные параметры
                $inUploadPhoto->upload_dir = PATH . '/images/photos/';
                $inUploadPhoto->small_size_w = $model->config['img_small_w'];
                $inUploadPhoto->medium_size_w = $model->config['img_big_w'];
                $inUploadPhoto->thumbsqr = $model->config['img_sqr'];
                $inUploadPhoto->is_watermark = $model->config['watermark'];
                $inUploadPhoto->input_name = 'picture';
                $inUploadPhoto->filename = $file;
                // Процесс загрузки фото
                $inUploadPhoto->uploadPhoto();
            }
            cmsCore::addSessionMessage($_LANG['AD_ARTICLE_SAVE'], 'success');
            if (!isset($_SESSION['editlist']) || @sizeof($_SESSION['editlist']) == 0) {
                cmsCore::redirect('?view=tree&cat_id=' . $article['category_id']);
            } else {
                cmsCore::redirect('?view=content&do=edit');
            }
        }
    }
    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $article['category_id'] = cmsCore::request('category_id', 'int', 1);
        $article['title'] = cmsCore::request('title', 'str');
        $article['url'] = cmsCore::request('url', 'str');
        $article['showtitle'] = cmsCore::request('showtitle', 'int', 0);
        $article['description'] = cmsCore::request('description', 'html', '');
        $article['description'] = $inDB->escape_string($article['description']);
        $article['content'] = cmsCore::request('content', 'html', '');
        $article['content'] = $inDB->escape_string($article['content']);
        $article['for_img'] = cmsCore::request('for_img', 'html', '');
        $article['for_img'] = $inDB->escape_string($article['for_img']);
        $article['published'] = cmsCore::request('published', 'int', 0);
        $article['showdate'] = cmsCore::request('showdate', 'int', 0);
        $article['showlatest'] = cmsCore::request('showlatest', 'int', 0);
        $article['show_in_new'] = cmsCore::request('show_in_new', 'int', 0);
        //new
        $article['show_in_footer'] = cmsCore::request('show_in_footer', 'int', 0);
        //new
        $article['showpath'] = cmsCore::request('showpath', 'int', 0);
        $article['comments'] = cmsCore::request('comments', 'int', 0);
        $article['canrate'] = cmsCore::request('canrate', 'int', 0);
        $article['add_text'] = cmsCore::request('add_text', 'str');
        $enddate = explode('.', cmsCore::request('enddate', 'str'));
        $article['enddate'] = $enddate[2] . '-' . $enddate[1] . '-' . $enddate[0];
        $article['is_end'] = cmsCore::request('is_end', 'int', 0);
        $article['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
        $article['tags'] = cmsCore::request('tags', 'str');
        $article['pubdate'] = $_REQUEST['pubdate'];
        $date = explode('.', $article['pubdate']);
        $article['pubdate'] = $date[2] . '-' . $date[1] . '-' . $date[0] . ' ' . date('H:i');
        $article['user_id'] = cmsCore::request('user_id', 'int', $inUser->id);
        $article['tpl'] = cmsCore::request('tpl', 'str', 'com_content_read.tpl');
        $autokeys = cmsCore::request('autokeys', 'int');
        switch ($autokeys) {
            case 1:
                $article['meta_keys'] = $inCore->getKeywords($article['content']);
                $article['meta_desc'] = $article['title'];
                break;
            case 2:
                $article['meta_desc'] = strip_tags($article['description']);
                $article['meta_keys'] = $article['tags'];
                break;
            case 3:
                $article['meta_desc'] = cmsCore::request('meta_desc', 'str');
                $article['meta_keys'] = cmsCore::request('meta_keys', 'str');
                break;
        }
        $article['id'] = $model->addArticle($article);
        if (!cmsCore::request('is_public', 'int', 0)) {
            $showfor = $_REQUEST['showfor'];
            if (sizeof($showfor) > 0 && !cmsCore::request('is_public', 'int', 0)) {
                cmsCore::setAccess($article['id'], $showfor, 'material');
            }
        }
        $inmenu = cmsCore::request('createmenu', 'str', '');
        if ($inmenu) {
            createMenuItem($inmenu, $article['id'], $article['title']);
        }
        // Загружаем класс загрузки фото
        cmsCore::loadClass('upload_photo');
        $inUploadPhoto = cmsUploadPhoto::getInstance();
        // Выставляем конфигурационные параметры
        $inUploadPhoto->upload_dir = PATH . '/images/photos/';
        $inUploadPhoto->small_size_w = $model->config['img_small_w'];
        $inUploadPhoto->medium_size_w = $model->config['img_big_w'];
        $inUploadPhoto->thumbsqr = $model->config['img_sqr'];
        $inUploadPhoto->is_watermark = $model->config['watermark'];
        $inUploadPhoto->input_name = 'picture';
        $inUploadPhoto->filename = 'article' . $article['id'] . '.jpg';
        // Процесс загрузки фото
        $inUploadPhoto->uploadPhoto();
        cmsCore::addSessionMessage($_LANG['AD_ARTICLE_ADD'], 'success');
        cmsCore::redirect('?view=tree&cat_id=' . $article['category_id']);
    }
    if ($do == 'add' || $do == 'edit') {
        require '../includes/jwtabs.php';
        $GLOBALS['cp_page_head'][] = jwHeader();
        $toolmenu = array();
        $toolmenu[0]['icon'] = 'save.gif';
        $toolmenu[0]['title'] = $_LANG['SAVE'];
        $toolmenu[0]['link'] = 'javascript:document.addform.submit();';
        $toolmenu[1]['icon'] = 'cancel.gif';
        $toolmenu[1]['title'] = $_LANG['CANCEL'];
        $toolmenu[1]['link'] = 'javascript:history.go(-1);';
        cpToolMenu($toolmenu);
        $menu_list = cpGetList('menu');
        if ($do == 'add') {
            echo '<h3>' . $_LANG['AD_CREATE_ARTICLE'] . '</h3>';
            cpAddPathway($_LANG['AD_CREATE_ARTICLE'], 'index.php?view=content&do=add');
            $mod['category_id'] = (int) $_REQUEST['to'];
            $mod['showpath'] = 1;
            $mod['tpl'] = 'com_content_read.tpl';
        } else {
            if (isset($_REQUEST['item'])) {
                $_SESSION['editlist'] = $_REQUEST['item'];
            }
            $ostatok = '';
            if (isset($_SESSION['editlist'])) {
                $id = array_shift($_SESSION['editlist']);
                if (sizeof($_SESSION['editlist']) == 0) {
                    unset($_SESSION['editlist']);
                } else {
                    $ostatok = '(' . $_LANG['AD_NEXT_IN'] . sizeof($_SESSION['editlist']) . ')';
                }
            } else {
                $id = (int) $_REQUEST['id'];
            }
            $sql = "SELECT *, (TO_DAYS(enddate) - TO_DAYS(CURDATE())) as daysleft, DATE_FORMAT(pubdate, '%d.%m.%Y') as pubdate, DATE_FORMAT(enddate, '%d.%m.%Y') as enddate\n\t\t\t\t\t FROM cms_content\n\t\t\t\t\t WHERE id = {$id} LIMIT 1";
            $result = $inDB->query($sql);
            if ($inDB->num_rows($result)) {
                $mod = $inDB->fetch_assoc($result);
            }
            echo '<h3>' . $_LANG['AD_EDIT_ARTICLE'] . $ostatok . '</h3>';
            cpAddPathway($mod['title'], 'index.php?view=content&do=edit&id=' . $mod['id']);
        }
        ?>
    <form id="addform" name="addform" method="post" action="index.php" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?php 
        echo cmsUser::getCsrfToken();
        ?>
" />
        <input type="hidden" name="view" value="content" />

        <table class="proptable" width="100%" cellpadding="5" cellspacing="2">
            <tr>

                <!-- главная ячейка -->
                <td valign="top">

                    <table width="100%" cellpadding="0" cellspacing="4" border="0">
                        <tr>
                            <td valign="top">
                                <div><strong><?php 
        echo $_LANG['AD_ARTICLE_NAME'];
        ?>
</strong></div>
                                <div>
                                    <table width="100%" cellpadding="0" cellspacing="0" border="0">
                                        <tr>
                                            <td><input name="title" type="text" id="title" style="width:100%" value="<?php 
        echo htmlspecialchars($mod['title']);
        ?>
" /></td>
                                            <td style="width:15px;padding-left:10px;padding-right:10px;">
                                                <input type="checkbox" title="<?php 
        echo $_LANG['AD_VIEW_TITLE'];
        ?>
" name="showtitle" <?php 
        if ($mod['showtitle'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
 value="1">
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </td>
                            <td width="130" valign="top">
                                <div><strong><?php 
        echo $_LANG['AD_PUBLIC_DATE'];
        ?>
</strong></div>
                                <div>
                                    <input name="pubdate" type="text" id="pubdate" style="width:100px" <?php 
        if (@(!$mod['pubdate'])) {
            echo 'value="' . date('d.m.Y') . '"';
        } else {
            echo 'value="' . $mod['pubdate'] . '"';
        }
        ?>
/>

                                    <input type="hidden" name="olddate" value="<?php 
        echo @$mod['pubdate'];
        ?>
" />
                                </div>
                            </td>
                            <td width="16" valign="bottom" style="padding-bottom:10px">
                                <input type="checkbox" name="showdate" id="showdate" title="<?php 
        echo $_LANG['AD_VIEW_DATE_AND_AUTHOR'];
        ?>
" value="1" <?php 
        if ($mod['showdate'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/>
                            </td>
<!--                             <td width="160" valign="top">
                                <div><strong><?php 
        echo $_LANG['AD_ARTICLE_TEMPLATE'];
        ?>
</strong></div>
                                <div><input name="tpl" type="text" style="width:160px" value="<?php 
        echo @$mod['tpl'];
        ?>
"></div>
                            </td> -->
							  <td width="160" valign="top">
                                <div><strong>Шаблон статьи</strong></div>
								<?php 
        $inConf = cmsConfig::getInstance();
        //задаём имя директории
        $directory = PATH . "/templates/" . $inConf->template . "/components";
        $scan_dir = scandir($directory);
        if (is_dir($directory)) {
            //проверяем наличие директории
            //директория существует
            echo '<select name="tpl">';
            $scan_dir = scandir($directory);
            //сканируем (получаем массив файлов)
            array_shift($scan_dir);
            // удаляем из массива '.'
            array_shift($scan_dir);
            // удаляем из массива '..'
            for ($i = 0; $i < sizeof($scan_dir); $i++) {
                $tpl = explode("_", $scan_dir[$i]);
                if ($_GET['view'] == $tpl['1']) {
                    if ($_GET['view']) {
                        //выводим все файлы
                        if (@$mod["tpl"] == $scan_dir[$i]) {
                            echo '<option selected>' . $scan_dir[$i] . '</option>';
                        } else {
                            echo '<option>' . $scan_dir[$i] . '</option>';
                        }
                    }
                }
            }
            echo '</select>';
        } else {
            echo '<input name="tpl" type="text" style="width:160px" value="' . @$mod["tpl"] . '">';
        }
        ?>
                            </td>

                        </tr>
                    </table>

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_NOTICE'];
        ?>
</strong></div>
                    <div><?php 
        $inCore->insertEditor('description', $mod['description'], '200', '100%');
        ?>
</div>

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_TEXT'];
        ?>
</strong></div>
                    <?php 
        insertPanel();
        ?>
                    <div><?php 
        $inCore->insertEditor('content', $mod['content'], '400', '100%');
        ?>
</div><!--Editor text in articles-->

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_IMG'];
        ?>
</strong></div>
                    <div><?php 
        $inCore->insertEditor('for_img', $mod['for_img'], '200', '100%');
        ?>
</div>

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_ADD_TEXT'];
        ?>
</strong></div>
                    <div><input name="add_text" type="text" id="add_text" style="width:99%" value="<?php 
        echo htmlspecialchars($mod['add_text']);
        ?>
" /></div>


                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_TAGS'];
        ?>
</strong></div>
                    <div><input name="tags" type="text" id="tags" style="width:99%" value="<?php 
        if (isset($mod['id'])) {
            echo cmsTagLine('content', $mod['id'], false);
        }
        ?>
" /></div>

                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                        <tr>
                            <td width="20">
                                <input type="radio" name="autokeys" id="autokeys1" <?php 
        if ($do == 'add' && $cfg['autokeys']) {
            ?>
checked="checked"<?php 
        }
        ?>
 value="1"/>
                            </td>
                            <td>
                                <label for="autokeys1"><strong><?php 
        echo $_LANG['AD_AUTO_GEN_KEY'];
        ?>
</strong></label>
                            </td>
                        </tr>
                        <tr>
                            <td width="20">
                                <input type="radio" name="autokeys" id="autokeys2" value="2"/>
                            </td>
                            <td>
                                <label for="autokeys2"><strong><?php 
        echo $_LANG['AD_TAGS_AS_KEY'];
        ?>
</strong></label>
                            </td>
                        </tr>
                        <tr>
                            <td width="20">
                                <input type="radio" name="autokeys" id="autokeys3" value="3" <?php 
        if ($do == 'edit' || !$cfg['autokeys']) {
            ?>
checked="checked"<?php 
        }
        ?>
/>
                            </td>
                            <td>
                                <label for="autokeys3"><strong><?php 
        echo $_LANG['AD_MANUAL_KEY'];
        ?>
</strong></label>
                            </td>
                        </tr>

                        <?php 
        if ($cfg['af_on'] && $do == 'add') {
            ?>
                        <tr>
                            <td width="20"><input type="checkbox" name="noforum" id="noforum" value="1" /> </td>
                            <td><label for="noforum"><strong><?php 
            echo $_LANG['AD_NO_CREATE_THEME'];
            ?>
</strong></label></td>
                        </tr>
                        <?php 
        }
        ?>
                    </table>

                </td>

                <!-- боковая ячейка -->
                <td width="300" valign="top" style="background:#ECECEC;">

                    <?php 
        ob_start();
        ?>

                    {tab=<?php 
        echo $_LANG['AD_TAB_PUBLISH'];
        ?>
}

                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                        <tr>
                            <td width="20"><input type="checkbox" name="published" id="published" value="1" <?php 
        if ($mod['published'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="published"><strong><?php 
        echo $_LANG['AD_PUBLIC_ARTICLE'];
        ?>
</strong></label></td>
                        </tr>
                    </table>

                    <div style="margin-top:7px">
                        <select name="category_id" size="10" id="category_id" style="width:99%;height:200px">
                            <option value="1" <?php 
        if (@$mod['category_id'] == 1 || !isset($mod['category_id'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_ROOT_CATEGORY'];
        ?>
</option>
                            <?php 
        if (isset($mod['category_id'])) {
            echo $inCore->getListItemsNS('cms_category', $mod['category_id']);
        } else {
            echo $inCore->getListItemsNS('cms_category');
        }
        ?>
                        </select>
                    </div>

                    <div style="margin-bottom:10px">
                        <select name="showpath" id="showpath" style="width:99%">
                            <option value="0" <?php 
        if (@(!$mod['showpath'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_PATHWAY_NAME_ONLY'];
        ?>
</option>
                            <option value="1" <?php 
        if (@$mod['showpath']) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_PATHWAY_FULL'];
        ?>
</option>
                        </select>
                    </div>

                    <div style="margin-top:15px">
                        <strong><?php 
        echo $_LANG['AD_ARTICLE_URL'];
        ?>
</strong><br/>
                        <div style="color:gray"><?php 
        echo $_LANG['AD_IF_UNKNOWN'];
        ?>
</div>
                    </div>
                    <div>
                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                            <tr>
                                <td><input type="text" name="url" value="<?php 
        echo $mod['url'];
        ?>
" style="width:100%"/></td>
                                <td width="40" align="center">.html</td>
                            </tr>
                        </table>
                    </div>

                    <div style="margin-top:10px">
                        <strong><?php 
        echo $_LANG['AD_ARTICLE_AUTHOR'];
        ?>
</strong>
                    </div>
                    <div>
                        <select name="user_id" id="user_id" style="width:99%">
                          <?php 
        if (isset($mod['user_id'])) {
            echo $inCore->getListItems('cms_users', $mod['user_id'], 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
        } else {
            echo $inCore->getListItems('cms_users', $inUser->id, 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
        }
        ?>
                        </select>
                    </div>

                    <div style="margin-top:12px"><strong><?php 
        echo $_LANG['AD_PHOTO'];
        ?>
</strong></div>
                    <div style="margin-bottom:10px">
                        <?php 
        if ($do == 'edit') {
            if (isset($_SESSION['lang']) && $_SESSION['lang'] != 'ru') {
                $mod_id = $mod['id'] . '_' . $_SESSION['lang'];
                $id_art = $mod['id'] . '_' . $_SESSION['lang'];
            } else {
                $mod_id = $mod['id'];
                $id_art = $id;
            }
            //if (file_exists(PATH.'/images/photos/small/article'.$mod['id'].'.jpg')){
            if (file_exists(PATH . '/images/photos/small/article' . $mod_id . '.jpg')) {
                ?>
                        <div style="margin-top:3px;margin-bottom:3px;padding:10px;border:solid 1px gray;text-align:center">
                            <?/*php<img src="/images/photos/small/article<?php 
                echo $id;
                ?>
.jpg" border="0" />*/?>
                            <img src="/images/photos/small/article<?php 
                echo $id_art;
                ?>
.jpg" border="0" />
                        </div>
                        <table cellpadding="0" cellspacing="0" border="0">
                            <tr>
                                <td width="16"><input type="checkbox" id="delete_image" name="delete_image" value="1" /></td>
                                <td><label for="delete_image"><?php 
                echo $_LANG['AD_PHOTO_REMOVE'];
                ?>
</label></td>
                            </tr>
                        </table>
                        <?php 
            }
        }
        ?>
                        <input type="file" name="picture" style="width:100%" />
                    </div>

                    <div style="margin-top:25px"><strong><?php 
        echo $_LANG['AD_PUBLIC_PARAMETRS'];
        ?>
</strong></div>
                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                        <tr>
                            <td width="20"><input type="checkbox" name="show_in_new" id="show_in_new" value="1" <?php 
        if ($mod['show_in_new'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="show_in_new"><?php 
        echo $_LANG['AD_VIEW_NEW_CATS'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="show_in_footer" id="show_in_footer" value="1" <?php 
        if ($mod['show_in_footer'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="show_in_footer"><?php 
        echo $_LANG['AD_VIEW_FOOTER'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="showlatest" id="showlatest" value="1" <?php 
        if ($mod['showlatest'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="showlatest"><?php 
        echo $_LANG['AD_VIEW_NEW_ARTICLES'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="comments" id="comments" value="1" <?php 
        if ($mod['comments'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="comments"><?php 
        echo $_LANG['AD_ENABLE_COMMENTS'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="canrate" id="canrate" value="1" <?php 
        if ($mod['canrate']) {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="canrate"><?php 
        echo $_LANG['AD_ENABLE_RATING'];
        ?>
</label></td>
                        </tr>
                    </table>

                    <?php 
        if ($do == 'add') {
            ?>
                        <div style="margin-top:25px">
                            <strong><?php 
            echo $_LANG['AD_CREATE_LINK'];
            ?>
</strong>
                        </div>
                        <div>
                            <select name="createmenu" id="createmenu" style="width:99%">
                                <option value="0" selected="selected"><?php 
            echo $_LANG['AD_DONT_CREATE_LINK'];
            ?>
</option>
                            <?php 
            foreach ($menu_list as $menu) {
                ?>
                                <option value="<?php 
                echo $menu['id'];
                ?>
">
                                    <?php 
                echo $menu['title'];
                ?>
                                </option>
                            <?php 
            }
            ?>
                            </select>
                        </div>
                    <?php 
        }
        ?>

                    {tab=<?php 
        echo $_LANG['AD_DATE'];
        ?>
}

                    <div style="margin-top:5px">
                        <strong><?php 
        echo $_LANG['AD_ARTICLE_TIME'];
        ?>
</strong>
                    </div>
                    <div>
                        <select name="is_end" id="is_end" style="width:99%" onchange="if($(this).val() == 1){ $('#final_time').show(); }else {$('#final_time').hide();}">
                            <option value="0" <?php 
        if (@(!$mod['is_end'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_UNLIMITED'];
        ?>
</option>
                            <option value="1" <?php 
        if (@$mod['is_end']) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_TO_FINAL_TIME'];
        ?>
</option>
                        </select>
                    </div>

                    <div id="final_time" <?php 
        if (@(!$mod['is_end'])) {
            echo 'style="display: none"';
        }
        ?>
>
                    <div style="margin-top:20px">
                        <strong><?php 
        echo $_LANG['AD_FINAL_TIME'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_CALENDAR_FORMAT'];
        ?>
</span>
                    </div>
                    <div><input name="enddate" type="text" style="width:80%" <?php 
        if (@(!$mod['is_end'])) {
            echo 'value="' . date('d.m.Y') . '"';
        } else {
            echo 'value="' . $mod['enddate'] . '"';
        }
        ?>
id="enddate" /></div></div>


                    {tab=SEO}

                    <div style="margin-top:5px">
                        <strong><?php 
        echo $_LANG['AD_PAGE_TITLE'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_IF_UNKNOWN_PAGETITLE'];
        ?>
</span>
                    </div>
                    <div>
                        <input name="pagetitle" type="text" id="pagetitle" style="width:99%" value="<?php 
        if (isset($mod['pagetitle'])) {
            echo htmlspecialchars($mod['pagetitle']);
        }
        ?>
" />
                    </div>

                    <div style="margin-top:20px">
                        <strong><?php 
        echo $_LANG['KEYWORDS'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_FROM_COMMA'];
        ?>
</span>
                    </div>
                    <div>
                         <textarea name="meta_keys" style="width:97%" rows="4" id="meta_keys"><?php 
        echo htmlspecialchars($mod['meta_keys']);
        ?>
</textarea>
                    </div>

                    <div style="margin-top:20px">
                        <strong><?php 
        echo $_LANG['DESCRIPTION'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_LESS_THAN'];
        ?>
</span>
                    </div>
                    <div>
                         <textarea name="meta_desc" style="width:97%" rows="6" id="meta_desc"><?php 
        echo htmlspecialchars($mod['meta_desc']);
        ?>
</textarea>
                    </div>

                    {tab=<?php 
        echo $_LANG['AD_TAB_ACCESS'];
        ?>
}

                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist" style="margin-top:5px">
                        <tr>
                            <td width="20">
                                <?php 
        $sql = "SELECT * FROM cms_user_groups";
        $result = $inDB->query($sql);
        $style = 'disabled="disabled"';
        $public = 'checked="checked"';
        if ($do == 'edit') {
            $sql2 = "SELECT * FROM cms_content_access WHERE content_id = " . $mod['id'] . " AND content_type = 'material'";
            $result2 = $inDB->query($sql2);
            $ord = array();
            if ($inDB->num_rows($result2)) {
                $public = '';
                $style = '';
                while ($r = $inDB->fetch_assoc($result2)) {
                    $ord[] = $r['group_id'];
                }
            }
        }
        ?>
                                <input name="is_public" type="checkbox" id="is_public" onclick="checkGroupList()" value="1" <?php 
        echo $public;
        ?>
 />
                            </td>
                            <td><label for="is_public"><strong><?php 
        echo $_LANG['AD_SHARE'];
        ?>
</strong></label></td>
                        </tr>
                    </table>
                    <div style="padding:5px">
                        <span class="hinttext">
                            <?php 
        echo $_LANG['AD_IF_NOTED'];
        ?>
                        </span>
                    </div>

                    <div style="margin-top:10px;padding:5px;padding-right:0px;" id="grp">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_GROUPS_VIEW'];
        ?>
</strong><br />
                            <span class="hinttext">
                                <?php 
        echo $_LANG['AD_SELECT_MULTIPLE_CTRL'];
        ?>
                            </span>
                        </div>
                        <div>
                            <?php 
        echo '<select style="width: 99%" name="showfor[]" id="showin" size="6" multiple="multiple" ' . $style . '>';
        if ($inDB->num_rows($result)) {
            while ($item = $inDB->fetch_assoc($result)) {
                echo '<option value="' . $item['id'] . '"';
                if ($do == 'edit') {
                    if (inArray($ord, $item['id'])) {
                        echo 'selected="selected"';
                    }
                }
                echo '>';
                echo $item['title'] . '</option>';
            }
        }
        echo '</select>';
        ?>
                        </div>
                    </div>

                    {/tabs}

                    <?php 
        echo jwTabs(ob_get_clean());
        ?>

                </td>

            </tr>
        </table>

        <p>
            <input name="add_mod" type="submit" id="add_mod" <?php 
        if ($do == 'add') {
            echo 'value="' . $_LANG['AD_CREATE_CONTENT'] . '"';
        } else {
            echo 'value="' . $_LANG['AD_SAVE_CONTENT'] . '"';
        }
        ?>
 />
            <input name="back" type="button" id="back" value="<?php 
        echo $_LANG['CANCEL'];
        ?>
" onclick="window.history.back();"/>
            <input name="do" type="hidden" id="do" <?php 
        if ($do == 'add') {
            echo 'value="submit"';
        } else {
            echo 'value="update"';
        }
        ?>
 />
            <?php 
        if ($do == 'edit') {
            echo '<input name="id" type="hidden" value="' . $mod['id'] . '" />';
        }
        ?>
        </p>
    </form>
    <?php 
    }
}
示例#18
0
                    $fdata[$key] = stripslashes($fdata[$key]);
                }
                $inCore->insertEditor('fdata[' . $key . ']', stripslashes($fdata[$key]), '220', '100%');
                ?>
                            <?php 
            }
            ?>
                        </div>
                        <?php 
        }
        ?>

                        <div><strong>Теги записи</strong></div>
                        <div><input name="tags" type="text" id="tags" style="width:99%" value="<?php 
        if (isset($mod['id'])) {
            echo cmsTagLine('catalog', $mod['id'], false);
        }
        ?>
" /></div>

                        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                            <?php 
        if ($is_shop) {
            ?>
                            <tr>
                                <td width="20"><input type="checkbox" name="canmany" id="canmany" value="1" <?php 
            if (@$mod['canmany']) {
                echo 'checked="checked"';
            }
            ?>
/> </td>