function comments($target = '', $target_id = 0, $labels = array()) { $inCore = cmsCore::getInstance(); $inPage = cmsPage::getInstance(); $inDB = cmsDatabase::getInstance(); $inUser = cmsUser::getInstance(); cmsCore::loadModel('comments'); $model = new cms_model_comments($labels); // Проверяем включени ли компонент if (!$inCore->isComponentEnable('comments')) { return false; } // Инициализируем права доступа для группы текущего пользователя $model->initAccess(); global $_LANG; $do = $inCore->do; $page = cmsCore::request('page', 'int', 1); $id = cmsCore::request('id', 'int', 0); $login = cmsCore::strClear(urldecode(cmsCore::request('login', 'html', ''))); $inPage->addHeadJS('components/comments/js/comments.js'); $inPage->addHeadJsLang(array('EDIT_COMMENT', 'CONFIRM_DEL_COMMENT', 'COMMENT_IN_LINK')); //========================================================================================================================// //========================================================================================================================// if ($do == 'view' && !$target && !$target_id) { if (!$login) { $myprofile = false; $page_title = $inCore->getComponentTitle(); $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . $_LANG['COMMENTS'] . '" href="' . HOST . '/rss/comments/all/feed.rss">'); } else { // проверяем что пользователь есть $user = cmsUser::getShortUserData($login); if (!$user) { cmsCore::error404(); } // Мои комментарии $myprofile = $inUser->id == $user['id']; $page_title = $_LANG['COMMENTS'] . ' - ' . $user['nickname']; $inPage->addPathway($user['nickname'], cmsUser::getProfileURL($user['login'])); // Добавляем условие в выборку $model->whereUserIs($user['id']); } $inPage->setTitle($page_title); $inPage->addPathway($page_title); $inPage->setDescription($model->config['meta_desc'] ? $model->config['meta_desc'] : $page_title); $inPage->setKeywords($model->config['meta_keys'] ? $model->config['meta_keys'] : $page_title); // флаг модератора $is_moder = $inUser->is_admin || $model->is_can_moderate; // Не админам только открытые комментарии if (!($is_moder || $myprofile)) { $model->whereIsShow(); } // Общее количество комментариев $total = $model->getCommentsCount(!($is_moder || $myprofile)); // Сортировка и разбивка на страницы $inDB->orderBy('c.pubdate', 'DESC'); $inDB->limitPage($page, $model->config['perpage']); // Сами комментарии $comments = $total ? $model->getComments(!($is_moder || $myprofile)) : array(); $inDB->resetConditions(); if (!$comments && $page > 1) { cmsCore::error404(); } // пагинация if (!$login) { $pagebar = cmsPage::getPagebar($total, $page, $model->config['perpage'], '/comments/page-%page%'); } else { $pagebar = cmsPage::getPagebar($total, $page, $model->config['perpage'], 'javascript:centerLink(\'/comments/by_user_' . $user['login'] . '/page-%page%\')'); } // Отдаем в шаблон cmsPage::initTemplate('components', 'com_comments_list_all')->assign('comments_count', $total)->assign('comments', $comments)->assign('pagebar', $pagebar)->assign('is_user', $inUser->id)->assign('page_title', $page_title)->assign('cfg', $model->config)->assign('is_admin', $is_moder)->display('com_comments_list_all.tpl'); } //========================================================================================================================// //========================================================================================================================// if (!in_array($do, array('add', 'edit', 'delete')) && $target && $target_id) { if (!$model->config['cmm_ajax']) { $model->whereTargetIs($target, $target_id); $inDB->orderBy('c.pubdate', 'ASC'); $comments = cmsCore::callEvent('BEFORE_SHOW_COMMENTS', $model->getComments(!($inUser->is_admin || $model->is_can_moderate), true)); $total = count($comments); ob_start(); cmsPage::initTemplate('components', 'com_comments_list')->assign('comments_count', $total)->assign('comments', $comments)->assign('user_can_moderate', $model->is_can_moderate)->assign('user_can_delete', $model->is_can_delete)->assign('user_can_add', $model->is_can_add)->assign('is_admin', $inUser->is_admin)->assign('is_user', $inUser->id)->assign('cfg', $model->config)->assign('labels', $model->labels)->assign('target', $target)->assign('target_id', $target_id)->display('com_comments_list.tpl'); $html = ob_get_clean(); } else { $model->whereTargetIs($target, $target_id); $total = $model->getCommentsCount(!($inUser->is_admin || $model->is_can_moderate)); $inDB->resetConditions(); } cmsPage::initTemplate('components', 'com_comments_view')->assign('comments_count', $total)->assign('target', $target)->assign('target_id', $target_id)->assign('is_admin', $inUser->is_admin)->assign('labels', $model->labels)->assign('is_user', $inUser->id)->assign('cfg', $model->config)->assign('user_can_add', $model->is_can_add)->assign('html', isset($html) ? $html : '')->assign('add_comment_js', "addComment('" . $target . "', '" . $target_id . "', 0)")->assign('user_subscribed', cmsUser::isSubscribed($inUser->id, $target, $target_id))->display('com_comments_view.tpl'); } //========================================================================================================================// //========================================================================================================================// // Добавление комментария, форма добавления в addform.php if ($do == 'add') { // Только аякс if (!cmsCore::isAjax()) { cmsCore::error404(); } // Очищаем буфер ob_end_clean(); // Добавлять могут только админы и те, кому разрешено в настройках группы if (!$model->is_can_add && !$inUser->is_admin) { cmsCore::error404(); } // Входные данные $comment['guestname'] = cmsCore::request('guestname', 'str', ''); $comment['user_id'] = $inUser->id; if ($model->is_can_bbcode) { $content = cmsCore::request('content', 'html', ''); $comment['content_bbcode'] = $inDB->escape_string($content); $content = cmsCore::parseSmiles($content, true); $comment['content'] = $inDB->escape_string($content); } else { $comment['content'] = cmsCore::request('content', 'str', ''); $comment['content_bbcode'] = $comment['content']; $comment['content'] = str_replace(array('\\r', '\\n'), '<br>', $comment['content']); } $comment['parent_id'] = cmsCore::request('parent_id', 'int', 0); $comment['target'] = cmsCore::request('target', 'str', ''); $comment['target_id'] = cmsCore::request('target_id', 'int', 0); $comment['ip'] = cmsCore::strClear($_SERVER['REMOTE_ADDR']); // Проверяем правильность/наличие входных парамеров // цель комментария if (!$comment['target'] || !$comment['target_id']) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_UNKNOWN_TARGET'])); } // Имя гостя отсутствует if (!$comment['guestname'] && !$inUser->id) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_USER_NAME'])); } // Текст комментраия отсутствует if (!$comment['content']) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_COMMENT_TEXT'])); } // проверяем каптчу $need_captcha = $model->config['regcap'] ? true : ($inUser->id ? false : true); if ($need_captcha && !cmsPage::checkCaptchaCode()) { cmsCore::jsonOutput(array('error' => true, 'is_captcha' => true, 'text' => $_LANG['ERR_CAPTCHA'])); } // получаем массив со ссылкой и заголовком цели комментария // для этого: // 1. узнаем ответственный компонент из cms_comment_targets $target = $inDB->get_fields('cms_comment_targets', "target='{$comment['target']}'", '*'); if (!$target) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_UNKNOWN_TARGET'] . ' #1')); } // 2. подключим модель этого компонента if (cmsCore::loadModel($target['component'])) { $model_class = 'cms_model_' . $target['component']; if (class_exists($model_class)) { $target_model = new $model_class(); } } if (!isset($target_model)) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_UNKNOWN_TARGET'] . ' #2')); } // 3. запросим массив $target_data[link, title] у метода getCommentTarget модели $target_data = $target_model->getCommentTarget($comment['target'], $comment['target_id']); if (!$target_data) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_UNKNOWN_TARGET'] . ' #3')); } $comment['target_title'] = $target_data['title']; $comment['target_link'] = $target_data['link']; // 4. Узнаем видимость комментария в модели $target_model if (method_exists($target_model, 'getVisibility')) { $comment['is_hidden'] = $target_model->getVisibility($comment['target'], $comment['target_id']); } else { $comment['is_hidden'] = 0; } // публикация согласно настроек $comment['published'] = $inUser->is_admin || $model->is_can_moderate || $model->is_add_published ? 1 : 0; // Проверяем токен перед самым добавлением комментария if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } // 5. добавляем комментарий в базу $comment_id = $model->addComment($comment); // 6. Пересчитываем количество комментариев у цели если нужно if (method_exists($target_model, 'updateCommentsCount')) { $target_model->updateCommentsCount($comment['target'], $comment['target_id']); } if (!$comment['is_hidden'] && $comment['published']) { //регистрируем событие $content_short = strip_tags($comment['content']); cmsActions::log('add_comment', array('object' => $_LANG['COMMENT'], 'object_url' => $comment['target_link'] . '#c' . $comment_id, 'object_id' => $comment_id, 'target' => $comment['target_title'], 'target_url' => $comment['target_link'], 'target_id' => $comment['target_id'], 'description' => mb_strlen($content_short) > 140 ? mb_substr($content_short, 0, 140) : $content_short)); } //////////////////////////////////////////////////////////////// ///////////////// Операции по уведомлениям ///////////////////// $inConf = cmsConfig::getInstance(); $from_nick = $inUser->id ? $inUser->nickname : $comment['guestname']; $targetlink = HOST . $comment['target_link'] . '#c' . $comment_id; //получаем ID и e-mail автора $author = $inUser->id ? $model->getTargetAuthor($target['target_table'], $comment['target_id']) : ''; //подписываем пользователя на обновления, если нужно if ($inUser->id && cmsCore::inRequest('subscribe')) { cmsUser::subscribe($inUser->id, $comment['target'], $comment['target_id']); } if ($comment['published']) { //рассылаем уведомления о новом комменте cmsUser::sendUpdateNotify($comment['target'], $comment['target_id'], array('link' => $comment['target_link'] . '#c' . $comment_id, 'title' => stripslashes($comment['target_title']), 'letter_file' => 'newcomment', 'author' => $inUser->id ? $inUser->nickname : $comment['guestname'])); //проверяем и выдаем награду если нужно cmsUser::checkAwards($inUser->id); } //отправляем админу уведомление о комментарии на e-mail, если нужно if ($model->config['email']) { $mailmsg = str_replace(array('{sitename}', '{date}', '{from}', '{subjtitle}', '{targetlink}', '{content}'), array($inConf->sitename, date('d/m/Y (H:i)'), $from_nick, stripslashes($comment['target_title']), $targetlink, strip_tags($comment['content'])), cmsCore::getLanguageTextFile('newcomment_admin')); $inCore->mailText($model->config['email'], '', $mailmsg); } //отправляем автору уведомление на e-mail if ($author && $comment['published']) { if ($model->isAuthorNeedMail($author['id']) && $inUser->id != $author['id']) { $letter = cmsCore::getLanguageTextFile('newpostcomment'); $letter = str_replace('{sitename}', $inConf->sitename, $letter); $letter = str_replace('{subj}', $target['subj'], $letter); $letter = str_replace('{subjtitle}', stripslashes($comment['target_title']), $letter); $letter = str_replace('{targetlink}', $targetlink, $letter); $letter = str_replace('{date}', date('d/m/Y H:i:s'), $letter); $letter = str_replace('{from}', $from_nick, $letter); $inCore->mailText($author['email'], '', $letter); } } if (!$comment['published']) { $message = str_replace(array('%user%', '%targetlink%'), array($from_nick, $targetlink), $_LANG['COMM_PREMODER_ADMIN_TEXT']); cmsUser::sendMessage(USER_UPDATER, 1, $message); } cmsCore::jsonOutput(array('error' => false, 'target' => $comment['target'], 'target_id' => $comment['target_id'], 'is_premod' => $comment['published'] ? 0 : $_LANG['COMM_PREMODER_TEXT'], 'comment_id' => $comment_id)); } //========================================================================================================================// //========================================================================================================================// if ($do == 'edit') { if (!cmsCore::isAjax()) { cmsCore::error404(); } $comment = $model->getComment(cmsCore::request('comment_id', 'int', 0)); if (!$comment) { die; } // редактировать могут авторы (если время редактирования есть) // модераторы и администраторы if (!$model->is_can_moderate && !$inUser->is_admin && !($inUser->id == $comment['user_id'] && $comment['is_editable'])) { cmsCore::error404(); } if ($model->is_can_bbcode) { $content = cmsCore::request('content', 'html', ''); $com_new['content_bbcode'] = $inDB->escape_string($content); $com_new['content'] = $inDB->escape_string(cmsCore::parseSmiles($content, true)); } else { $com_new['content'] = cmsCore::request('content', 'str', ''); $com_new['content_bbcode'] = $com_new['content']; $com_new['content'] = str_replace(array('\\r', '\\n'), '<br>', $com_new['content']); } // Текст комментраия отсутствует if (!$com_new['content']) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_COMMENT_TEXT'])); } if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } //Если ошибок не было, //обновляем комментарий в базе $model->updateComment($comment['id'], $com_new); // Обновляем в ленте активности $content_short = mb_substr(strip_tags($com_new['content']), 0, 140); cmsActions::updateLog('add_comment', array('description' => $content_short), $comment['id']); $com_new['content'] = stripslashes(str_replace(array('\\r', '\\n'), ' ', $com_new['content'])); $com_new = cmsCore::callEvent('GET_COMMENT', $com_new); cmsCore::jsonOutput(array('error' => false, 'text' => $com_new['content'], 'comment_id' => $comment['id'])); } //========================================================================================================================// //========================================================================================================================// if ($do == 'delete') { if (!cmsCore::isAjax()) { cmsCore::error404(); } $comment = $model->getComment($id); if (!$comment) { cmsCore::error404(); } if (!$inUser->id && !($model->is_can_delete && $inUser->id == $comment['user_id']) && !$model->is_can_moderate && !$inUser->is_admin) { cmsCore::error404(); } //узнаем ответственный компонент из cms_comment_targets $target = $inDB->get_fields('cms_comment_targets', "target='{$comment['target']}'", '*'); if (!$target) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_UNKNOWN_TARGET'] . ' #1')); } if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } $model->deleteComment($id); //подключим модель этого компонента if (cmsCore::loadModel($target['component'])) { $model_class = 'cms_model_' . $target['component']; if (class_exists($model_class)) { $target_model = new $model_class(); // Пересчитываем количество комментариев у цели если нужно if (method_exists($target_model, 'updateCommentsCount')) { $target_model->updateCommentsCount($comment['target'], $comment['target_id']); } } } cmsCore::jsonOutput(array('error' => false, 'target' => $comment['target'], 'target_id' => $comment['target_id'])); } }
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'); } }
/** * Добавляет пост в блоге * @param array $item * @return array $post_id, $seolink */ public function addPost($item) { $item = cmsCore::callEvent('ADD_POST', $item); //парсим bb-код перед записью в базу // Парсим по отдельности части текста, если есть тег [cut if (mb_strstr($item['content'], '[cut')) { $msg_to = $this->getPostShort($item['content']); $msg_to = cmsCore::parseSmiles($msg_to, true); $msg_after = $this->getPostShort($item['content'], false, true); $msg_after = cmsCore::parseSmiles($msg_after, true); $cut = $this->getPostCut($item['content']); $item['content_html'] = $msg_to . $cut . $msg_after; } else { $item['content_html'] = cmsCore::parseSmiles($item['content'], true); } // Экранируем специальные символы $item['content'] = $this->inDB->escape_string($item['content']); $item['content_html'] = $this->inDB->escape_string($item['content_html']); $post_id = $this->inDB->insert('cms_blog_posts', $item); if (!$post_id) { return false; } cmsInsertTags($item['tags'], $this->getTarget('tags'), $post_id); $item['id'] = $post_id; $item['seolink'] = $this->generatePostSeoLink($item); $this->inDB->query("UPDATE cms_blog_posts SET seolink='{$item['seolink']}' WHERE id = '{$post_id}'"); if ($item['published']) { cmsUser::checkAwards($item['user_id']); } cmsCore::setIdUploadImage('blog_post', $post_id); return array('id' => $post_id, 'seolink' => $item['seolink']); }
/** * Добавляет фото * @param array $photo * @return int */ public function addPhoto($photo){ $photo_id = cmsCore::c('db')->insert('cms_photo_files', cmsCore::callEvent('ADD_PHOTO', $photo)); if ($photo['tags']){ cmsInsertTags($photo['tags'], $this->getTarget('tags'), $photo_id); } cmsUser::checkAwards($inUser->id); return $photo_id; }
$is_users_only = $album['allow_who'] == 'registered' ? 1 : 0; cmsActions::log('add_user_photo_multi', array( 'object' => $total_foto, 'object_url' => '', 'object_id' => '', 'target' => $album['title'], 'target_id' => $album_id, 'target_url' => '/users/'.$usr['login'].'/photos/private'.$album_id.'.html', 'description' => $photo_descr, 'is_friends_only' => $is_friends_only, 'is_users_only' => $is_users_only )); } if (!$is_edit) { cmsUser::checkAwards($inUser->id); cmsCore::redirect("/users/{$usr['login']}/photos/private{$album_id}.html"); } else { cmsCore::redirect("/users/{$usr['id']}/photo{$photo_id}.html"); } } } /////////////////////////////// PHOTO DELETE ///////////////////////////////////////////////////////////////////////////////////////// if ($pdo=='delphoto'){ cmsCore::loadLib('tags'); cmsCore::loadLanguage('components/photos'); $photo_id = cmsCore::request('photoid', 'int', '');
function forum() { $inCore = cmsCore::getInstance(); $inPage = cmsPage::getInstance(); $inDB = cmsDatabase::getInstance(); $inUser = cmsUser::getInstance(); $model = new cms_model_forum(); define('IS_BILLING', $inCore->isComponentInstalled('billing')); if (IS_BILLING) { cmsCore::loadClass('billing'); } global $_LANG; $pagetitle = $inCore->getComponentTitle(); $inPage->addPathway($pagetitle, '/forum'); $inPage->setTitle($pagetitle); $inPage->setDescription($model->config['meta_desc'] ? $model->config['meta_desc'] : $pagetitle); $inPage->setKeywords($model->config['meta_keys'] ? $model->config['meta_keys'] : $pagetitle); $id = cmsCore::request('id', 'int', 0); $do = $inCore->do; $page = cmsCore::request('page', 'int', 1); $inPage->addHeadJS('components/forum/js/common.js'); $inPage->addHeadJsLang(array('CONFIRM_DELETE_POLL', 'CONFIRM_DEL_POST', 'CONFIRM_DEL_THREAD', 'MOVE_THREAD', 'MOVE_POST', 'RENAME_THREAD', 'CONFIRM_DELETE_FILE', 'SELECT_NEW_FILE_UPLOAD', 'SELECT_TEXT_QUOTE', 'CONFIRM_DELETE_ALL_USER_POSTS')); //============================================================================// //=============================== Список Форумов ============================// //============================================================================// if ($do == 'view') { $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . $_LANG['FORUMS'] . '" href="' . HOST . '/rss/forum/all/feed.rss">'); $forums = $model->getForums(); cmsPage::initTemplate('components', 'com_forum_list')->assign('pagetitle', $pagetitle)->assign('forums', $forums)->assign('forum', array())->assign('user_id', $inUser->id)->assign('cfg', $model->config)->display('com_forum_list.tpl'); } //============================================================================// //================ Список тем форума + список подфорумов ====================// //============================================================================// if ($do == 'forum') { $forum = $model->getForum($id); if (!$forum) { cmsCore::error404(); } $forum = translations::process(cmsConfig::getConfig('lang'), 'forum_forums', $forum); $moderators = $model->getForumModerators($forum['moder_list']); // опции просмотра $order_by = cmsCore::getSearchVar('order_by', 'pubdate'); $order_to = cmsCore::getSearchVar('order_to', 'desc'); if (!in_array($order_by, array('pubdate', 'title', 'post_count', 'hits'))) { $order_by = 'pubdate'; } if (!in_array($order_to, array('asc', 'desc'))) { $order_to = 'desc'; } $daysprune = (int) cmsCore::getSearchVar('daysprune'); if (!cmsCore::checkContentAccess($forum['access_list'])) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . htmlspecialchars($forum['title']) . '" href="' . HOST . '/rss/forum/' . $forum['id'] . '/feed.rss">'); $inPage->setTitle($forum['pagetitle'] ? $forum['pagetitle'] : $forum['title']); $inPage->setDescription($forum['meta_desc'] ? $forum['meta_desc'] : crop($forum['description'] ? $forum['description'] : $forum['title'])); $inPage->setKeywords($forum['meta_keys'] ? $forum['meta_keys'] : $forum['title']); // Получаем дерево форумов $path_list = $inDB->getNsCategoryPath('cms_forums', $forum['NSLeft'], $forum['NSRight'], 'id, title, access_list, moder_list'); // Строим глубиномер if ($path_list) { $path_list = translations::process(cmsConfig::getConfig('lang'), 'forum_forums', $path_list); foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']); } } // Получим подфорумы $model->whereNestedForum($forum['NSLeft'], $forum['NSRight']); $sub_forums = $model->getForums(); cmsPage::initTemplate('components', 'com_forum_list')->assign('pagetitle', $forum['title'])->assign('forums', $sub_forums)->assign('forum', $forum)->assign('cfg', $model->config)->assign('user_id', $inUser->id)->display('com_forum_list.tpl'); // Получим темы if ($daysprune) { $model->whereDayIntervalIs($daysprune); } $model->whereForumIs($forum['id']); $inDB->orderBy('t.pinned', 'DESC, t.' . $order_by . ' ' . $order_to); $inDB->limitPage($page, $model->config['pp_forum']); $threads = $model->getThreads(); if (!$threads && $page > 1) { cmsCore::error404(); } cmsPage::initTemplate('components', 'com_forum_view')->assign('threads', $threads)->assign('show_panel', true)->assign('order_by', $order_by)->assign('order_to', $order_to)->assign('daysprune', $daysprune)->assign('moderators', $moderators)->assign('pagination', cmsPage::getPagebar($forum['thread_count'], $page, $model->config['pp_forum'], '/forum/' . $forum['id'] . '-%page%'))->display('com_forum_view.tpl'); } //============================================================================// //======================== Просмотр темы форума =============================// //============================================================================// if ($do == 'thread') { $thread = $model->getThread($id); if (!$thread) { cmsCore::error404(); } // Строим глубиномер $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { $path_list = translations::process(cmsConfig::getConfig('lang'), 'forum_forums', $path_list); foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']); } // Для последнего форума проверяем // не модератор ли текущий пользователь $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } $inPage->addPathway($thread['title'], '/forum/thread' . $thread['id'] . '.html'); if (!$thread['is_mythread']) { $inDB->setFlag('cms_forum_threads', $thread['id'], 'hits', $thread['hits'] + 1); } // получаем посты $model->whereThreadIs($thread['id']); $inDB->orderBy('p.pinned', 'DESC, p.pubdate ASC'); $inDB->limitPage($page, $model->config['pp_thread']); $posts = $model->getPosts(); if (!$posts) { cmsCore::error404(); } // SEO $inPage->setTitle($thread['title']); // meta description if (!$thread['description']) { $first_post = current($posts); $first_post_content = strip_tags($first_post['content_html']); if (mb_strlen($first_post_content) >= 100) { $inPage->setDescription(crop($first_post_content)); } else { $inPage->setDescription($thread['title']); } } else { $inPage->setDescription(crop($thread['description'])); } // meta keywords $all_post_content = ''; foreach ($posts as $p) { $all_post_content .= ' ' . strip_tags($p['content_html']); } $meta_keys = cmsCore::getKeywords($all_post_content); $inPage->setKeywords($meta_keys ? $meta_keys : $thread['title']); cmsCore::initAutoGrowText('#message'); cmsPage::initTemplate('components', 'com_forum_view_thread')->assign('forum', $pcat)->assign('forums', $model->getForums())->assign('is_subscribed', cmsUser::isSubscribed($inUser->id, 'forum', $thread['id']))->assign('thread', $thread)->assign('prev_thread', $inDB->get_fields('cms_forum_threads', "id < '{$thread['id']}' AND forum_id = '{$thread['forum_id']}'", 'id, title', 'id DESC'))->assign('next_thread', $inDB->get_fields('cms_forum_threads', "id > '{$thread['id']}' AND forum_id = '{$thread['forum_id']}'", 'id, title', 'id ASC'))->assign('posts', $posts)->assign('thread_poll', $model->getThreadPoll($thread['id']))->assign('page', $page)->assign('num', ($page - 1) * $model->config['pp_thread'] + 1)->assign('lastpage', ceil($thread['post_count'] / $model->config['pp_thread']))->assign('pagebar', cmsPage::getPagebar($thread['post_count'], $page, $model->config['pp_thread'], '/forum/thread' . $thread['id'] . '-%page%.html'))->assign('user_id', $inUser->id)->assign('do', $do)->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->assign('is_can_add_post', cmsUser::isUserCan('forum/add_post'))->assign('cfg', $model->config)->assign('bb_toolbar', $inUser->id && $model->config['fast_on'] && $model->config['fast_bb'] ? cmsPage::getBBCodeToolbar('message', $model->config['img_on']) : '')->assign('smilies', $inUser->id && $model->config['fast_on'] && $model->config['fast_bb'] ? cmsPage::getSmilesPanel('message') : '')->display('com_forum_view_thread.tpl'); } //============================================================================// //================ Новая тема, написать/редактировать пост ===================// //============================================================================// if (in_array($do, array('newthread', 'newpost', 'editpost'))) { if (!$inUser->id) { cmsUser::goToLogin(); } // id первого поста в теме $first_post_id = false; // опросов по умолчанию нет $thread_poll = array(); // применяется при редактировании поста $is_allow_attach = true; // ограничение по карме if (in_array($do, array('newthread', 'newpost'))) { if ($inUser->karma < $model->config['min_karma_add'] && !$inUser->is_admin) { cmsCore::addSessionMessage(sprintf($_LANG['ADD_KARMA_LIMIT'], cmsCore::spellCount($model->config['min_karma_add'], $_LANG['KPOINT1'], $_LANG['KPOINT2'], $_LANG['KPOINT10']), $inUser->karma), 'error'); cmsCore::redirectBack(); } } // новая тема if ($do == 'newthread') { // права доступа if (!cmsUser::isUserCan('forum/add_thread') && !$inUser->is_admin) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $forum = $model->getForum($id); if (!$forum) { cmsCore::error404(); } if (!cmsCore::checkContentAccess($forum['access_list'])) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $path_list = $inDB->getNsCategoryPath('cms_forums', $forum['NSLeft'], $forum['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']); } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } if (IS_BILLING && $forum['topic_cost']) { cmsBilling::checkBalance('forum', 'add_thread', false, $forum['topic_cost']); } $pagetitle = $_LANG['NEW_THREAD']; $thread = cmsUser::sessionGet('thread'); if ($thread) { cmsUser::sessionDel('thread'); } $last_post['content'] = cmsUser::sessionGet('post_content'); if ($last_post['content']) { cmsUser::sessionDel('post_content'); } } // новый пост if ($do == 'newpost') { // права доступа if (!cmsUser::isUserCan('forum/add_post') && !$inUser->is_admin) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $thread = $model->getThread($id); if (!$thread || $thread['closed']) { cmsCore::error404(); } $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']); } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } $inPage->addPathway($thread['title'], '/forum/thread' . $thread['id'] . '.html'); $pagetitle = $_LANG['NEW_POST']; $last_post = $model->getPost(cmsCore::request('replyid', 'int', 0)); if ($last_post) { $last_post['content'] = preg_replace('/\\[hide(.*?)\\](.*?)\\[\\/hide\\]/sui', '', $last_post['content']); $last_post['content'] = preg_replace('/\\[hide(.*?)\\](.*?)$/sui', '', $last_post['content']); $quote_nickname = $inDB->get_field('cms_users', "id = '{$last_post['user_id']}'", 'nickname'); $last_post['content'] = '[quote=' . $quote_nickname . ']' . "\r\n" . $last_post['content'] . "\r\n" . '[/quote]' . "\r\n\r\n"; $pagetitle = $_LANG['REPLY_FULL_QUOTE']; } } // редактирование поста if ($do == 'editpost') { $last_post = $model->getPost($id); if (!$last_post) { cmsCore::error404(); } $is_allow_attach = $last_post['attach_count'] < $model->config['fa_max']; // уменьшаем значение настроек согласно загруженных файлов $model->config['fa_max'] = $model->config['fa_max'] - $last_post['attach_count']; $thread = $model->getThread($last_post['thread_id']); if (!$thread || $thread['closed']) { cmsCore::error404(); } $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsPage::includeTemplateFile('special/accessdenied.php'); return; } $inPage->addPathway($pcat['title'], '/forum/' . $pcat['id']); } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } $inPage->addPathway($thread['title'], '/forum/thread' . $thread['id'] . '.html'); $end_min = $model->checkEditTime($last_post['pubdate']); $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $last_post['user_id'] == $inUser->id; // редактировать могут только администраторы, модераторы или авторы, если время есть if (!$inUser->is_admin && !$is_forum_moder && !$is_author_can_edit) { cmsCore::error404(); } if (!$inUser->is_admin && !$is_forum_moder && $model->config['edit_minutes']) { $msg_minute = str_replace('{min}', cmsCore::spellCount($end_min, $_LANG['MINUTE1'], $_LANG['MINUTE2'], $_LANG['MINUTE10']), $_LANG['EDIT_INFO']); cmsCore::addSessionMessage($msg_minute, 'info'); } $first_post_id = $inDB->get_field('cms_forum_posts', "thread_id = '{$thread['id']}' ORDER BY pubdate ASC", 'id'); $thread_poll = $model->getThreadPoll($thread['id']); $pagetitle = $_LANG['EDIT_POST']; } ///////////////////////// /// Показываем форму /// ///////////////////////// if (!cmsCore::inRequest('gosend')) { $inPage->setTitle($pagetitle); $inPage->addPathway($pagetitle); $inPage->addHeadJsLang(array('FILE_SELECTED', 'FILE_DENIED', 'FILE_DUPLICATE')); cmsCore::initAutoGrowText('#message'); cmsPage::initTemplate('components', 'com_forum_add')->assign('pagetitle', $pagetitle)->assign('is_first_post', isset($last_post['id']) ? $first_post_id == $last_post['id'] : true)->assign('thread_poll', $thread_poll)->assign('cfg', $model->config)->assign('do', $do)->assign('forum', isset($forum) ? $forum : $pcat)->assign('is_subscribed', cmsUser::isSubscribed($inUser->id, 'forum', @$thread['id']))->assign('thread', $thread)->assign('post_content', htmlspecialchars($last_post['content']))->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->assign('is_allow_attach', cmsCore::checkContentAccess($model->config['group_access']) && $is_allow_attach)->assign('bb_toolbar', cmsPage::getBBCodeToolbar('message', $model->config['img_on'], 'forum', 'post', @$last_post['id']))->assign('smilies', cmsPage::getSmilesPanel('message'))->display('com_forum_add.tpl'); } else { ///////////////////////// // Выполняем действия /// ///////////////////////// if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } $message_bb = $inDB->escape_string(cmsCore::request('message', 'html', '')); $message_html = $inDB->escape_string(cmsCore::parseSmiles(cmsCore::request('message', 'html', ''), true)); if (!$message_html) { cmsCore::addSessionMessage($_LANG['NEED_TEXT_POST'], 'error'); cmsCore::redirectBack(); } $message_post = strip_tags($message_html); $message_post = mb_strlen($message_post) > 200 ? mb_substr($message_post, 0, 200) : $message_post; $post_pinned = 0; if (in_array($do, array('newthread', 'newpost'))) { if ($do == 'newthread') { $thread['title'] = cmsCore::request('title', 'str', ''); $thread['description'] = cmsCore::request('description', 'str', ''); $post_pinned = 1; if (!$thread['title']) { cmsCore::addSessionMessage($_LANG['NEED_TITLE_THREAD_YOUR_POST'], 'error'); cmsUser::sessionPut('thread', $thread); cmsUser::sessionPut('post_content', stripcslashes($message_bb)); cmsCore::redirectBack(); } $thread['is_hidden'] = cmsCore::yamlToArray($forum['access_list']) ? 1 : 0; $thread['forum_id'] = $forum['id']; $thread['user_id'] = $inUser->id; $thread['pubdate'] = date("Y-m-d H:i:s"); $thread['hits'] = 0; $thread['id'] = $model->addThread($thread); $thread['NSLeft'] = $forum['NSLeft']; $thread['NSRight'] = $forum['NSRight']; $thread['post_count'] = 0; if (IS_BILLING && $forum['topic_cost']) { cmsBilling::process('forum', 'add_thread', $forum['topic_cost']); } } $post_id = $model->addPost(array('thread_id' => $thread['id'], 'user_id' => $inUser->id, 'pinned' => $post_pinned, 'content' => $message_bb, 'content_html' => $message_html, 'pubdate' => date("Y-m-d H:i:s"), 'editdate' => date("Y-m-d H:i:s"))); // Обновляем количество постов в теме $thread_post_count = $model->updateThreadPostCount($thread['id']); // Закрываем тему если нужно $is_fixed = cmsCore::request('fixed', 'int', 0); if ($is_fixed && ($is_forum_moder || $inUser->is_admin || $thread['is_mythread'])) { $model->closeThread($thread['id']); } // Загружаем аттачи if ($model->config['fa_on'] && cmsCore::checkContentAccess($model->config['group_access'])) { $file_error = $model->addUpdatePostAttachments($post_id); if ($file_error === false) { cmsCore::addSessionMessage($_LANG['CHECK_SIZE_TYPE_FILE'] . $model->config['fa_max'], 'error'); } } // Обновляем кеши $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true); $total_pages = ceil($thread_post_count / $model->config['pp_thread']); // Проверяем награды cmsUser::checkAwards($inUser->id); // Рассылаем уведомления тем, кто подписан if ($do == 'newpost') { cmsUser::sendUpdateNotify('forum', $thread['id'], array('link' => '/forum/thread' . $thread['id'] . '-' . $total_pages . '.html#' . $post_id, 'title' => stripslashes($thread['title']), 'letter_file' => 'newforumpost', 'author' => $inUser->nickname)); } // Подписываемся сами если нужно if (cmsCore::inRequest('subscribe')) { cmsUser::subscribe($inUser->id, 'forum', $thread['id']); } // Если пост не в скрытый форум и не в объедненный с предыдущим, добавляем в ленту if (!$thread['is_hidden'] && $thread_post_count > $thread['post_count']) { if ($do == 'newthread') { cmsActions::log('add_thread', array('object' => $thread['title'], 'object_url' => '/forum/thread' . $thread['id'] . '-1.html', 'object_id' => $thread['id'], 'target' => $forum['title'], 'target_url' => '/forum/' . $forum['id'], 'target_id' => $forum['id'], 'description' => $message_post)); } else { cmsActions::log('add_fpost', array('object' => $_LANG['MESSAGE'], 'object_url' => '/forum/thread' . $thread['id'] . '-' . $total_pages . '.html#' . $post_id, 'object_id' => $post_id, 'target' => $thread['title'], 'target_url' => '/forum/thread' . $thread['id'] . '.html', 'target_id' => $thread['id'], 'description' => $message_post)); } } // Для новой темы прикрепляем опрос если нужно if ($do == 'newthread') { $model->addPoll(cmsCore::request('poll', 'array', array()), $thread['id']); $last_poll_error = $model->getLastAddPollError(); if ($last_poll_error) { cmsCore::addSessionMessage($last_poll_error, 'error'); cmsCore::redirect('/forum/editpost' . $post_id . '-1.html'); } } cmsCore::redirect('/forum/thread' . $thread['id'] . '-' . $total_pages . '.html#' . $post_id); } elseif ($do == 'editpost') { $model->updatePost(array('content' => $message_bb, 'content_html' => $message_html, 'edittimes' => $last_post['edittimes'] + 1, 'editdate' => date("Y-m-d H:i:s")), $last_post['id']); if ($model->config['fa_on'] && cmsCore::checkContentAccess($model->config['group_access'])) { $file_error = $model->addUpdatePostAttachments($last_post['id']); if ($file_error === false) { cmsCore::addSessionMessage($_LANG['CHECK_SIZE_TYPE_FILE'] . $model->config['fa_max'], 'error'); } } if ($first_post_id == $last_post['id']) { cmsActions::updateLog('add_thread', array('description' => $message_post), $thread['id']); if ($thread_poll) { $model->updatePoll(cmsCore::request('poll', 'array', array()), $thread_poll); } else { $model->addPoll(cmsCore::request('poll', 'array', array()), $thread['id']); } $last_poll_error = $model->getLastAddPollError(); if ($last_poll_error) { cmsUser::sessionPut('thread', $thread); cmsUser::sessionPut('post_content', stripcslashes($message_bb)); cmsCore::addSessionMessage($last_poll_error, 'error'); cmsCore::redirectBack(); } } else { cmsActions::updateLog('add_fpost', array('description' => $message_post), $last_post['id']); } $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true); cmsCore::redirect('/forum/thread' . $thread['id'] . '-' . $page . '.html#' . $last_post['id']); } } } ///////////////////////////// DELETE POST ///////////////////////////////////////////////////////////////////////////////////////////////// if ($do == 'deletepost') { if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } if (!$inUser->id) { cmsCore::error404(); } $post = $model->getPost($id); if (!$post) { cmsCore::error404(); } $thread = $model->getThread($post['thread_id']); if (!$thread) { cmsCore::error404(); } $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list, NSLeft, NSRight'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsCore::error404(); } } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } $end_min = $model->checkEditTime($post['pubdate']); $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $post['user_id'] == $inUser->id; if (!$inUser->is_admin && !($is_forum_moder && !cmsUser::userIsAdmin($post['user_id'])) && !$is_author_can_edit) { cmsCore::error404(); } $model->deletePost($post['id']); $model->updateThreadPostCount($post['thread_id']); $model->cacheThreadLastPost($post['thread_id']); if ($path_list) { $path_list = array_reverse($path_list); foreach ($path_list as $pcat) { $model->updateForumCache($pcat['NSLeft'], $pcat['NSRight']); } } cmsCore::addSessionMessage($_LANG['MSG_IS_DELETED'], 'info'); $total_pages = ceil(($thread['post_count'] - 1) / $model->config['pp_thread']); if ($page > $total_pages) { $page = $total_pages; } cmsCore::jsonOutput(array('error' => false, 'redirect' => '/forum/thread' . $thread['id'] . '-' . $page . '.html')); } //============================================================================// //========================== Операции с темами ===============================// //============================================================================// if (in_array($do, array('movethread', 'renamethread', 'deletethread', 'close', 'pin', 'pin_post', 'move_post'))) { if (!$inUser->id) { cmsCore::error404(); } $thread = $model->getThread($id); if (!$thread) { cmsCore::halt(); } $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list, NSLeft, NSRight'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsCore::halt(); } } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } //======================= Перемещение темы ===============================// if ($do == 'movethread') { if (!$inUser->is_admin && !$is_forum_moder) { cmsCore::halt(); } if (!cmsCore::inRequest('gomove')) { cmsPage::initTemplate('components', 'com_forum_move_thread')->assign('thread', $thread)->assign('forums', $model->getForums())->display('com_forum_move_thread.tpl'); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } else { $new_forum = $model->getForum(cmsCore::request('forum_id', 'int', 0)); if (!$new_forum) { cmsCore::error404(); } $is_hidden = 0; $path_list = $inDB->getNsCategoryPath('cms_forums', $new_forum['NSLeft'], $new_forum['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsCore::halt(); } if (cmsCore::yamlToArray($pcat['access_list'])) { $is_hidden = 1; } } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } if (!$is_forum_moder && !$inUser->is_admin) { cmsCore::addSessionMessage($_LANG['YOU_NO_THIS_FORUM_MODER'], 'error'); cmsCore::redirect('/forum/thread' . $thread['id'] . '.html'); } $inDB->query("UPDATE cms_forum_threads SET forum_id = '{$new_forum['id']}', is_hidden = '{$is_hidden}' WHERE id = '{$thread['id']}'"); cmsActions::updateLog('add_thread', array('target' => $new_forum['title'], 'target_url' => '/forum/' . $new_forum['id'], 'target_id' => $new_forum['id']), $thread['id']); // Обновляем кешированные значения // для старого форума $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true); // для нового форума $model->updateForumCache($new_forum['NSLeft'], $new_forum['NSRight'], true); cmsCore::addSessionMessage($_LANG['THREAD_IS_MOVE'] . '"' . $new_forum['title'] . '"', 'success'); cmsCore::redirect('/forum/thread' . $thread['id'] . '.html'); } } //===================== Переименование темы ==============================// if ($do == 'renamethread') { if (!$inUser->is_admin && !$is_forum_moder && !$thread['is_mythread']) { cmsCore::halt(); } if (!cmsCore::inRequest('gorename')) { cmsPage::initTemplate('components', 'com_forum_rename_thread')->assign('thread', $thread)->display('com_forum_rename_thread.tpl'); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } else { $new_thread['title'] = cmsCore::request('title', 'str', $thread['title']); $new_thread['description'] = cmsCore::request('description', 'str', ''); $model->updateThread($new_thread, $thread['id']); cmsActions::updateLog('add_fpost', array('target' => $new_thread['title']), 0, $thread['id']); cmsActions::updateLog('add_thread', array('object' => $new_thread['title']), $thread['id']); $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true); cmsCore::jsonOutput(array('error' => false, 'title' => stripslashes($new_thread['title']), 'description' => stripslashes($new_thread['description']))); } } //======================= Удаление темы ==================================// if ($do == 'deletethread') { if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } if (!$inUser->is_admin && !($is_forum_moder && !cmsUser::userIsAdmin($thread['user_id'])) && !$thread['is_mythread']) { cmsCore::halt(); } $model->deleteThread($thread['id']); // Обновляем кешированные значения $model->updateForumCache($thread['NSLeft'], $thread['NSRight'], true); cmsCore::jsonOutput(array('error' => false, 'redirect' => '/forum/' . $thread['forum_id'])); } //=============== Прикрепление/открепление темы ==========================// if ($do == 'pin') { if (!$inUser->is_admin && !$is_forum_moder) { cmsCore::halt(); } $pinned = cmsCore::request('pinned', 'int', 0); $inDB->query("UPDATE cms_forum_threads SET pinned = '{$pinned}' WHERE id = '{$thread['id']}'"); cmsCore::halt($pinned); } //========== Прикрепление/открепление сообщения темы =====================// if ($do == 'pin_post') { if (!$inUser->is_admin && !$is_forum_moder) { cmsCore::halt(); } $pinned = cmsCore::request('pinned', 'int', 0); $post_id = cmsCore::request('post_id', 'int', 0); // Проверяем, принадлежит ли сообщение теме if (!$model->isBelongsToPostTopic($post_id, $thread['id'])) { cmsCore::halt(); } $inDB->query("UPDATE cms_forum_posts SET pinned = '{$pinned}' WHERE id = '{$post_id}' AND thread_id = '{$thread['id']}'"); // Ниже строки для тех, кто обновлялся с 1.9, если чистая установка, их можно удалить // Ставим принудительно для первого поста темы флаг pinned if ($pinned) { $first_post_id = $inDB->get_field('cms_forum_posts', "thread_id = '{$thread['id']}' ORDER BY pubdate ASC", 'id'); $inDB->query("UPDATE cms_forum_posts SET pinned = 1 WHERE id = '{$first_post_id}' AND thread_id = '{$thread['id']}'"); } cmsCore::redirect('/forum/thread' . $thread['id'] . '-1.html#' . $post_id); } //=========================== Перенос сообщения темы =====================// if ($do == 'move_post') { if (!$inUser->is_admin && !$is_forum_moder) { cmsCore::halt(); } $post_id = cmsCore::request('post_id', 'int', 0); // Проверяем, принадлежит ли сообщение теме if (!$model->isBelongsToPostTopic($post_id, $thread['id'])) { cmsCore::halt(); } cmsCore::callEvent('MOVE_FORUM_POST', array('thread' => $thread, 'post_id' => $post_id)); if (!cmsCore::inRequest('gomove')) { cmsPage::initTemplate('components', 'com_forum_move_post')->assign('thread', $thread)->assign('post_id', $post_id)->assign('threads', cmsCore::getListItems('cms_forum_threads', $thread['id'], 'title', 'ASC', "forum_id = '{$thread['forum_id']}'"))->display('com_forum_move_post.tpl'); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } else { $new_thread = $model->getThread(cmsCore::request('new_thread_id', 'int', 0)); if (!$new_thread) { cmsCore::error404(); } $n_path_list = $inDB->getNsCategoryPath('cms_forums', $new_thread['NSLeft'], $new_thread['NSRight'], 'id, title, access_list, moder_list, NSLeft, NSRight'); if ($n_path_list) { foreach ($n_path_list as $n_pcat) { if (!cmsCore::checkContentAccess($n_pcat['access_list'])) { cmsCore::halt(); } } $is_forum_moder = $model->isForumModerator($n_pcat['moder_list']); } if (!$is_forum_moder && !$inUser->is_admin) { cmsCore::error404(); } $model->updatePost(array('thread_id' => $new_thread['id'], 'pubdate' => date("Y-m-d H:i:s")), $post_id); $model->updateThreadPostCount($thread['id']); $thread_post_count = $model->updateThreadPostCount($new_thread['id']); $total_pages = ceil($thread_post_count / $model->config['pp_thread']); cmsActions::updateLog('add_fpost', array('target' => $new_thread['title'], 'target_url' => '/forum/thread' . $new_thread['id'] . '.html', 'target_id' => $new_thread['id'], 'object_url' => '/forum/thread' . $new_thread['id'] . '-' . $total_pages . '.html#' . $post_id, 'pubdate' => date("Y-m-d H:i:s")), $post_id); $model->cacheThreadLastPost($thread['id']); if ($path_list) { $path_list = array_reverse($path_list); foreach ($path_list as $pcat) { $model->cacheLastPost($pcat['NSLeft'], $pcat['NSRight']); } } if ($n_path_list) { $n_path_list = array_reverse($n_path_list); foreach ($n_path_list as $pcat) { $model->cacheLastPost($pcat['NSLeft'], $pcat['NSRight']); } } cmsCore::addSessionMessage($_LANG['POST_IS_MOVE'] . '"' . $new_thread['title'] . '"', 'success'); cmsCore::redirect('/forum/thread' . $new_thread['id'] . '-' . $total_pages . '.html#' . $post_id); } } //==================== Открытие/закрытие темы ============================// if ($do == 'close') { if (!$inUser->is_admin && !$is_forum_moder && !$thread['is_mythread']) { cmsCore::halt(); } $closed = cmsCore::request('closed', 'int', 0); if ($closed) { $model->closeThread($thread['id']); } else { $model->openThread($thread['id']); } cmsCore::halt($closed); } cmsCore::halt(); } //============================================================================// //========================== Операции с файлами ==============================// //============================================================================// if (in_array($do, array('download', 'delfile', 'reloadfile'))) { if (!$model->config['fa_on']) { cmsCore::error404(); } $file = $model->getPostAttachment($id); if (!$file) { cmsCore::error404(); } $post = $model->getPost($file['post_id']); if (!$post) { cmsCore::error404(); } $thread = $model->getThread($post['thread_id']); if (!$thread) { cmsCore::error404(); } $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsCore::error404(); } } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } //================= Скачивание прикрепленного файла ======================// if ($do == 'download') { $location = PATH . '/upload/forum/post' . $file['post_id'] . '/' . $file['filename']; if (!file_exists($location)) { cmsCore::error404(); } $inDB->query("UPDATE cms_forum_files SET hits = hits + 1 WHERE id = '{$file['id']}'"); ob_clean(); header('Content-Disposition: attachment; filename=' . htmlspecialchars($file['filename'])); header('Content-Type: application/x-force-download; name="' . htmlspecialchars($file['filename']) . '"'); header('Content-Length: ' . $file['filesize']); header('Accept-Ranges: bytes'); cmsCore::halt(file_get_contents($location)); } //=================== Удаление прикрепленного файла ======================// if ($do == 'delfile') { if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } $end_min = $model->checkEditTime($post['pubdate']); $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $post['user_id'] == $inUser->id && cmsCore::checkContentAccess($model->config['group_access']); if (!$inUser->is_admin && !$is_forum_moder && !$is_author_can_edit) { cmsCore::halt(); } $model->deletePostAttachment($file); cmsCore::halt(1); } //================== Перезакачка прикрепленного файла ====================// if ($do == 'reloadfile') { $end_min = $model->checkEditTime($post['pubdate']); $is_author_can_edit = (is_bool($end_min) ? $end_min : $end_min > 0) && $post['user_id'] == $inUser->id && cmsCore::checkContentAccess($model->config['group_access']); if (!$inUser->is_admin && !$is_forum_moder && !$is_author_can_edit) { cmsCore::error404(); } if (!cmsCore::inRequest('goreload')) { cmsPage::initTemplate('components', 'com_forum_file_reload')->assign('file', $file)->assign('cfg', $model->config)->display('com_forum_file_reload.tpl'); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } else { $success = $model->addUpdatePostAttachments($post['id'], $file); if ($success) { $post['attached_files'] = $model->getPostAttachments($post['id']); $post['is_author_can_edit'] = $is_author_can_edit; cmsPage::initTemplate('components', 'com_forum_attached_files')->assign('post', $post)->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->assign('cfg', $model->config)->display('com_forum_attached_files.tpl'); cmsCore::jsonOutput(array('error' => false, 'post_id' => $post['id'], 'html' => ob_get_clean())); } else { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CHECK_SIZE_TYPE_FILE'] . $model->config['fa_max'])); } } } cmsCore::halt(); } //============================================================================// //========================= Операции с опросами ==============================// //============================================================================// if ($do == 'view_poll') { $thread = $model->getThread($id); if (!$thread) { cmsCore::halt(); } $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsCore::halt(); } } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } $thread_poll = $model->getThreadPoll($thread['id']); if (!$thread_poll) { cmsCore::halt(); } if ($inUser->id && $thread_poll['is_user_vote'] && $thread_poll['options']['change'] && cmsCore::request('revote', 'int')) { $model->deleteVote($thread_poll); $thread_poll['is_user_vote'] = 0; $thread_poll['vote_count'] -= 1; } if (!$thread_poll['is_user_vote'] && !$thread_poll['options']['result']) { $thread_poll['show_result'] = cmsCore::request('show_result', 'int'); } cmsPage::initTemplate('components', 'com_forum_thread_poll')->assign('thread', $thread)->assign('thread_poll', $thread_poll)->assign('user_id', $inUser->id)->assign('do', $thread_poll['show_result'] ? $do : 'thread')->assign('is_moder', $is_forum_moder)->assign('is_admin', $inUser->is_admin)->display('com_forum_thread_poll.tpl'); cmsCore::halt(ob_get_clean()); } if ($do == 'delete_poll') { if (!$inUser->id) { cmsCore::halt(); } if (!cmsUser::checkCsrfToken()) { cmsCore::halt(); } $thread = $model->getThread($id); if (!$thread) { cmsCore::halt(); } $path_list = $inDB->getNsCategoryPath('cms_forums', $thread['NSLeft'], $thread['NSRight'], 'id, title, access_list, moder_list'); if ($path_list) { foreach ($path_list as $pcat) { if (!cmsCore::checkContentAccess($pcat['access_list'])) { cmsCore::halt(); } } $is_forum_moder = $model->isForumModerator($pcat['moder_list']); } $thread_poll = $model->getThreadPoll($thread['id']); if (!$thread_poll) { cmsCore::halt(); } if (!$is_forum_moder && !$inUser->is_admin) { cmsCore::halt(); } $model->deletePoll($thread_poll['id']); cmsCore::halt(1); } if ($do == 'vote_poll') { if (!$inUser->id) { cmsCore::halt(); } if (!cmsUser::checkCsrfToken()) { cmsCore::halt(); } $answer = cmsCore::request('answer', 'str', ''); $poll = $model->getPollById(cmsCore::request('poll_id', 'int')); if (!$answer || !$poll) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['SELECT_THE_OPTION'])); } if ($model->isUserVoted($poll['id'])) { cmsCore::jsonOutput(array('error' => true, 'text' => '')); } $model->votePoll($poll, $answer); cmsCore::jsonOutput(array('error' => false, 'text' => '')); } //============================================================================// //========================= Последние сообщения ==============================// //============================================================================// if ($do == 'latest_posts') { $inActions = cmsActions::getInstance(); $inPage->setTitle($_LANG['LATEST_POSTS_ON_FORUM']); $inPage->addPathway($_LANG['FORUMS'], '/forum'); $inPage->addPathway($_LANG['LATEST_POSTS_ON_FORUM']); $inActions->showTargets(true); $action = $inActions->getAction('add_fpost'); $inActions->onlySelectedTypes(array($action['id'])); $total = $inActions->getCountActions(); $inDB->limitPage($page, 15); $actions = $inActions->getActionsLog(); if (!$actions && $page > 1) { cmsCore::error404(); } cmsPage::initTemplate('components', 'com_forum_actions')->assign('actions', $actions)->assign('total', $total)->assign('do', $do)->assign('user_id', $inUser->id)->assign('pagetitle', $_LANG['LATEST_POSTS_ON_FORUM'])->assign('pagebar', cmsPage::getPagebar($total, $page, 15, '/forum/latest_posts/page-%page%'))->display('com_forum_actions.tpl'); } //============================================================================// //============================= Последние темы ===============================// //============================================================================// if ($do == 'latest_thread') { $inActions = cmsActions::getInstance(); $inPage->setTitle($_LANG['NEW_THREADS_ON_FORUM']); $inPage->addPathway($_LANG['FORUMS'], '/forum'); $inPage->addPathway($_LANG['NEW_THREADS_ON_FORUM']); $inActions->showTargets(true); $action = $inActions->getAction('add_thread'); $inActions->onlySelectedTypes(array($action['id'])); $total = $inActions->getCountActions(); $inDB->limitPage($page, 15); $actions = $inActions->getActionsLog(); if (!$actions && $page > 1) { cmsCore::error404(); } cmsPage::initTemplate('components', 'com_forum_actions')->assign('actions', $actions)->assign('total', $total)->assign('do', $do)->assign('user_id', $inUser->id)->assign('pagetitle', $_LANG['NEW_THREADS_ON_FORUM'])->assign('pagebar', cmsPage::getPagebar($total, $page, 15, '/forum/latest_thread/page-%page%'))->display('com_forum_actions.tpl'); } //============================================================================// //========================== Просмотр категории ==============================// //============================================================================// if ($do == 'view_cat') { $cat = $model->getForumCat(cmsCore::request('seolink', 'str', '')); if (!$cat) { cmsCore::error404(); } $cat = translations::process(cmsConfig::getConfig('lang'), 'forum_forum_cats', $cat); $inPage->setTitle($cat['pagetitle'] ? $cat['pagetitle'] : $cat['title']); $inPage->setDescription($cat['meta_desc'] ? $cat['meta_desc'] : $cat['title']); $inPage->setKeywords($cat['meta_keys'] ? $cat['meta_keys'] : $cat['title']); $inPage->addPathway($cat['title']); $model->whereForumCatIs($cat['id']); $sub_forums = $model->getForums(); cmsPage::initTemplate('components', 'com_forum_list')->assign('pagetitle', $cat['title'])->assign('forums', $sub_forums)->assign('forum', array())->assign('cfg', $model->config)->assign('user_id', false)->display('com_forum_list.tpl'); $inDB->addJoin('INNER JOIN cms_forums f ON f.id = t.forum_id'); $inDB->where("t.is_hidden = 0"); $model->whereForumCatIs($cat['id']); $inDB->orderBy('t.pubdate', 'DESC, t.hits DESC'); $inDB->limit(15); $threads = $model->getThreads(); cmsPage::initTemplate('components', 'com_forum_view')->assign('threads', $threads)->display('com_forum_view.tpl'); } //============================================================================// //===================== Активность пользователя ==============================// //============================================================================// if ($do == 'user_activity') { $login = cmsCore::request('login', 'str', $inUser->login); $sub_do = cmsCore::request('sub_do', 'str', 'threads'); $user = cmsUser::getShortUserData($login); if (!$user) { cmsCore::error404(); } $my_profile = $inUser->login == $login; $pagetitle = $my_profile ? $_LANG['MY_ACTIVITY'] : $user['nickname'] . ' - ' . $_LANG['ACTIVITY_ON_FORUM']; $inPage->setTitle($pagetitle); $inPage->addPathway($pagetitle); $threads = array(); $posts = array(); if (!$my_profile && !$inUser->is_admin) { $model->wherePublicThreads(); } $model->whereThreadUserIs($user['id']); $thread_count = $model->getThreadsCount(); if ($sub_do == 'threads' && $thread_count) { $inDB->orderBy('t.pubdate', 'DESC, t.hits DESC'); $inDB->limitPage($page, 15); $threads = $model->getThreads(); $pagination = cmsPage::getPagebar($thread_count, $page, 15, "javascript:forum.getUserActivity('threads','/forum/{$user['login']}_activity.html','%page%');"); } $inDB->resetConditions(); // Если тем у пользователя нет, показываем вкладку сообщений if (!$thread_count) { $sub_do = 'posts'; } $inDB->addSelect('t.title as thread_title'); $inDB->addJoin('INNER JOIN cms_forum_threads t ON t.id = p.thread_id'); $model->wherePostUserIs($user['id']); if (!$my_profile && !$inUser->is_admin) { $model->wherePublicThreads(); } $post_count = $model->getPostsCount(); // Если сообщений нет, 404 if (!$post_count && !$my_profile) { cmsCore::error404(); } if ($sub_do == 'posts' && $post_count) { $inDB->orderBy('p.thread_id', 'DESC, p.pubdate DESC'); $inDB->limitPage($page, 10); $posts = $model->getPosts(); $pagination = cmsPage::getPagebar($post_count, $page, 10, "javascript:forum.getUserActivity('posts','/forum/{$user['login']}_activity.html','%page%');"); } $inDB->resetConditions(); cmsPage::initTemplate('components', 'com_forum_user_activity')->assign('threads', $threads)->assign('posts', $posts)->assign('post_count', $post_count)->assign('thread_count', $thread_count)->assign('pagetitle', $pagetitle)->assign('sub_do', $sub_do)->assign('page', $page)->assign('user_id', $user['id'])->assign('my_profile', $my_profile)->assign('is_admin', $inUser->is_admin)->assign('is_moderator', cmsUser::isUserCan('forum/moderate'))->assign('pagination', $pagination)->assign('link', '/forum/' . $user['login'] . '_activity.html')->display('com_forum_user_activity.tpl'); } //////////////////////////////////////////////////////////////////////////////// if ($do == 'delete_all_user_posts') { if (!$inUser->id) { cmsCore::error404(); } if (!$inUser->is_admin && !cmsUser::isUserCan('forum/moderate')) { cmsCore::error404(); } if (!cmsUser::checkCsrfToken()) { cmsCore::halt(); } $user = cmsUser::getShortUserData(cmsCore::request('user_id', 'int', 0)); if (!$user || $user['id'] == $inUser->id) { cmsCore::error404(); } $model->deleteAllUserPosts($user['id']); cmsCore::addSessionMessage($_LANG['ALL_USERPOSTS_ISDELETED'], 'success'); cmsCore::halt(); } }
private function createForum($article) { $forum_id = (int) $this->config['AF_ADDTREADFORUM_ID']; if (!$forum_id) { return false; } if (!$this->checkCatForAdd($article['category_id'])) { return false; } // если для статьи есть уже тема, выходим $forum_thread_id = $this->inDB->get_field('cms_forum_threads', "rel_to='content' AND rel_id='{$article['id']}'", 'id'); if ($forum_thread_id) { return false; } cmsCore::loadModel('forum'); $model_forum = new cms_model_forum(); $post_html = $this->getHtmlPost($article); $post = $this->getBbtexPost($article); $threadlastid = $model_forum->addThread(array('forum_id' => $forum_id, 'user_id' => $article['user_id'], 'title' => $this->inDB->escape_string($article['title']), 'description' => '', 'is_hidden' => '0', 'rel_to' => 'content', 'hits' => 0, 'pubdate' => date("Y-m-d H:i:s"), 'rel_id' => $article['id'])); $model_forum->addPost(array('thread_id' => $threadlastid, 'user_id' => $article['user_id'], 'content' => $post, 'content_html' => $post_html, 'pubdate' => date("Y-m-d H:i:s"), 'editdate' => date("Y-m-d H:i:s"))); $forum = $this->inDB->get_fields('cms_forums', "id='{$forum_id}'", '*'); $model_forum->updateThreadPostCount($threadlastid); cmsUser::checkAwards($article['user_id']); $model_forum->updateForumCache($forum['NSLeft'], $forum['NSRight'], true); cmsActions::log('add_thread', array('object' => $article['title'], 'user_id' => $article['user_id'], 'object_url' => '/forum/thread' . $threadlastid . '.html', 'object_id' => $threadlastid, 'target' => $this->inDB->escape_string($forum['title']), 'target_url' => '/forum/' . $forum_id, 'target_id' => $forum_id, 'description' => strip_tags($post_html))); return true; }
public function addPhoto_new($photo) { if (isset($_SESSION['lang']) && $_SESSION['lang'] != 'ru') { $photo_id = $this->inDB->insert($_SESSION['lang'] . '_photo_files', cmsCore::callEvent('ADD_PHOTO', $photo)); } else { $photo_id = $this->inDB->insert('cms_photo_files', cmsCore::callEvent('ADD_PHOTO', $photo)); } if ($photo['tags']) { cmsInsertTags($photo['tags'], $this->getTarget('tags'), $photo_id); } cmsUser::checkAwards($inUser->id); return $photo_id; }