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'].' — '.cmsCore::m('blogs')->config['min_karma_private'].', '.$_LANG['BLOG_HEAVING'].' — '.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'].' — '.cmsCore::m('blogs')->config['min_karma_public'].', '.$_LANG['BLOG_HEAVING'].' — '.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'].' — '.cmsCore::m('blogs')->config['min_karma_private'].', '.$_LANG['BLOG_HEAVING'].' — '.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'].' — '.cmsCore::m('blogs')->config['min_karma_public'].', '.$_LANG['BLOG_HEAVING'].' — '.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>«'.$post['title'].'»</b> '.$_LANG['WAS_DELETED_FROM_BLOG'].' <b>«<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>»</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>«<a href="'.$post['seolink'].'">'.$post['title'].'</a>»</b> '.$_LANG['PUBLISHED_IN_BLOG'].' <b>«<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>»</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(); } }
function users() { header('X-Frame-Options: DENY'); $inCore = cmsCore::getInstance(); $inPage = cmsPage::getInstance(); $inDB = cmsDatabase::getInstance(); $inUser = cmsUser::getInstance(); global $_LANG; $model = new cms_model_users(); // id пользователя $id = cmsCore::request('id', 'int', 0); // логин пользователя $login = cmsCore::strClear(urldecode(cmsCore::request('login', 'html', ''))); $do = $inCore->do; $page = cmsCore::request('page', 'int', 1); $pagetitle = $inCore->getComponentTitle(); if ($model->config['sw_search'] != 2) { $inPage->addPathway($pagetitle, '/users'); } $inPage->setTitle($pagetitle); $inPage->setDescription($pagetitle); // js только авторизованным if ($inUser->id) { $inPage->addHeadJS('components/users/js/profile.js'); $inPage->addHeadJsLang(array('CONFIRM_CLEAN_CAT', 'CHOOSE_RECIPIENT', 'SEND_TO_USER', 'FRIENDSHIP_OFFER', 'STOP_FRIENDLY', 'REALY_STOP_FRIENDLY', 'ENTER_STATUS', 'HAVE_JUST')); } //============================================================================// //========================= Список пользователей ============================// //============================================================================// if ($do == 'view') { // если запрещен просмотр всех пользователей, 404 if ($model->config['sw_search'] == 2) { cmsCore::error404(); } //очищаем поисковые запросы если пришли со другой страницы if (!strstr(cmsCore::getBackURL(), '/users')) { cmsUser::sessionClearAll(); } $stext = array(); // Возможные входные переменные $name = cmsCore::getSearchVar('name'); $city = cmsCore::getSearchVar('city'); $hobby = cmsCore::getSearchVar('hobby'); $gender = cmsCore::getSearchVar('gender'); $orderby = cmsCore::request('orderby', array('karma', 'rating', 'regdate'), 'regdate'); $orderto = cmsCore::request('orderto', array('asc', 'desc'), 'desc'); $age_to = (int) cmsCore::getSearchVar('ageto', 'all'); $age_fr = (int) cmsCore::getSearchVar('agefrom', 'all'); $group_id = cmsCore::request('group_id', 'int', 0); // Флаг о показе только онлайн пользователей if (cmsCore::inRequest('online')) { cmsUser::sessionPut('usr_online', (bool) cmsCore::request('online', 'int')); $page = 1; } $only_online = cmsUser::sessionGet('usr_online'); if ($only_online) { $stext[] = $_LANG['SHOWING_ONLY_ONLINE']; } /////////////////////////////////////// //////////Условия выборки////////////// /////////////////////////////////////// // группа if ($group_id) { $model->whereUserGroupIs($group_id); $link['group'] = '/users/group/' . $group_id; $_LANG['GROUP_SEARCH_NAME'] = cmsUser::getGroupTitle($group_id); } // Добавляем в выборку имя, если оно есть if ($name) { $model->whereNameIs($name); $stext[] = $_LANG['NAME'] . " — " . htmlspecialchars(stripslashes($name)); } // Добавляем в выборку город, если он есть if ($city) { $model->whereCityIs($city); $stext[] = $_LANG['CITY'] . " — " . htmlspecialchars(stripslashes($city)); } // Добавляем в выборку хобби, если есть if ($hobby) { $model->whereHobbyIs($hobby); $stext[] = $_LANG['HOBBY'] . " — " . htmlspecialchars(stripslashes($hobby)); } // Добавляем в выборку пол, если есть if ($gender) { $model->whereGenderIs($gender); if ($gender == 'm') { $stext[] = $_LANG['MALE']; } else { $stext[] = $_LANG['FEMALE']; } } // Добавляем в выборку возраст, более if ($age_fr) { $model->whereAgeFrom($age_fr); $stext[] = $_LANG['NOT_YOUNG'] . " {$age_fr} " . $_LANG['YEARS']; } // Добавляем в выборку возраст, менее if ($age_to) { $model->whereAgeTo($age_to); $stext[] = $_LANG['NOT_OLD'] . " {$age_fr} " . $_LANG['YEARS']; } // Считаем общее количество согласно выборки $total = $model->getUsersCount($only_online); if ($total) { //устанавливаем сортировку $inDB->orderBy($orderby, $orderto); //устанавливаем номер текущей страницы и кол-во пользователей на странице $inDB->limitPage($page, $model->config['users_perpage']); // Загружаем пользователей согласно выборки $users = $model->getUsers($only_online); } else { $inDB->resetConditions(); } $link['latest'] = '/users'; $link['positive'] = '/users/positive.html'; $link['rating'] = '/users/rating.html'; if ($orderby == 'regdate') { $link['selected'] = 'latest'; } if ($orderby == 'karma') { $link['selected'] = 'positive'; } if ($orderby == 'rating') { $link['selected'] = 'rating'; } $pagebar_link = '/users/' . $link['selected'] . '%page%.html'; if ($group_id) { $link['selected'] = 'group'; $pagebar_link = '/users/' . $link['selected'] . '/' . $group_id . '-%page%'; } cmsPage::initTemplate('components', 'com_users_view')->assign('stext', $stext)->assign('orderby', $orderby)->assign('orderto', $orderto)->assign('users', $users)->assign('total', $total)->assign('only_online', $only_online)->assign('gender', $gender)->assign('name', stripslashes($name))->assign('city', stripslashes($city))->assign('hobby', stripslashes($hobby))->assign('age_to', $age_to)->assign('age_fr', $age_fr)->assign('cfg', $model->config)->assign('link', $link)->assign('pagebar', cmsPage::getPagebar($total, $page, $model->config['users_perpage'], $pagebar_link))->display('com_users_view.tpl'); } //============================================================================// //======================= Редактирование профиля ============================// //============================================================================// if ($do == 'editprofile') { // неавторизованным, не владельцам и не админам тут делать нечего if (!$inUser->id || $inUser->id != $id && !$inUser->is_admin) { cmsCore::error404(); } $usr = $model->getUser($id); if (!$usr) { cmsCore::error404(); } $opt = cmsCore::request('opt', 'str', 'edit'); // главного админа может редактировать только он сам if ($id == 1 && $inUser->id != $id) { cmsCore::error404(); } // показываем форму if ($opt == 'edit') { $inPage->setTitle($_LANG['CONFIG_PROFILE'] . ' - ' . $usr['nickname']); $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login'])); $inPage->addPathway($_LANG['CONFIG_PROFILE']); $private_forms = array(); if (isset($model->config['privforms'])) { if (is_array($model->config['privforms'])) { foreach ($model->config['privforms'] as $form_id) { $private_forms = array_merge($private_forms, cmsForm::getFieldsHtml($form_id, $usr['formsdata'])); } } } cmsPage::initTemplate('components', 'com_users_edit_profile')->assign('opt', $opt)->assign('usr', $usr)->assign('private_forms', $private_forms)->assign('cfg_forum', $inCore->loadComponentConfig('forum'))->assign('cfg', $model->config)->display('com_users_edit_profile.tpl'); return; } // Если сохраняем профиль if ($opt == 'save') { if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } $errors = false; $users['nickname'] = cmsCore::request('nickname', 'str'); if (mb_strlen($users['nickname']) < 2) { cmsCore::addSessionMessage($_LANG['SHORT_NICKNAME'], 'error'); $errors = true; } cmsCore::loadModel('registration'); $modreg = new cms_model_registration(); if (!$inUser->is_admin) { if ($modreg->getBadNickname($users['nickname'])) { cmsCore::addSessionMessage($_LANG['ERR_NICK_EXISTS'], 'error'); $errors = true; } } $profiles['gender'] = cmsCore::request('gender', 'str'); $profiles['city'] = cmsCore::request('city', 'str'); if (mb_strlen($profiles['city']) > 50) { cmsCore::addSessionMessage($_LANG['LONG_CITY_NAME'], 'error'); $errors = true; } $users['email'] = cmsCore::request('email', 'email'); if (!$users['email']) { cmsCore::addSessionMessage($_LANG['REALY_ADRESS_EMAIL'], 'error'); $errors = true; } if ($usr['email'] != $users['email']) { $is_set_email = $inDB->get_field('cms_users', "email='{$users['email']}'", 'id'); if ($is_set_email) { cmsCore::addSessionMessage($_LANG['ADRESS_EMAIL_IS_BUSY'], 'error'); $errors = true; } else { // формируем токен $token = md5($usr['email'] . uniqid() . microtime()); $inDB->insert('cms_users_activate', array('user_id' => $inUser->id, 'pubdate' => date("Y-m-d H:i:s"), 'code' => $token)); $codelink = HOST . '/users/change_email/' . $token . '/' . $users['email']; // по старому адресу высылаем письмо с подтверждением $letter = cmsCore::getLanguageTextFile('change_email'); $letter = str_replace(array('{nickname}', '{codelink}'), array($inUser->nickname, $codelink), $letter); cmsCore::mailText($usr['email'], '', $letter); cmsCore::addSessionMessage(sprintf($_LANG['YOU_CHANGE_EMAIL'], $usr['email']), 'info'); // email не меняем $users['email'] = $usr['email']; } } $profiles['showphone'] = cmsCore::request('showphone', 'int', 0); $profiles['showmail'] = cmsCore::request('showmail', 'int'); $profiles['email_newmsg'] = cmsCore::request('email_newmsg', 'int'); $profiles['showbirth'] = cmsCore::request('showbirth', 'int'); $profiles['description'] = cmsCore::request('description', 'str', ''); $users['birthdate'] = (int) $_REQUEST['birthdate']['year'] . '-' . (int) $_REQUEST['birthdate']['month'] . '-' . (int) $_REQUEST['birthdate']['day']; $profiles['signature'] = $inDB->escape_string(cmsCore::badTagClear(cmsCore::request('signature', 'html', ''))); $profiles['signature_html'] = $inDB->escape_string(cmsCore::parseSmiles(cmsCore::request('signature', 'html', ''), true)); $profiles['allow_who'] = cmsCore::request('allow_who', 'str'); if (!preg_match('/^([a-zA-Z]+)$/ui', $profiles['allow_who'])) { $errors = true; } $users['icq'] = cmsCore::request('icq', 'str', ''); $profiles['showicq'] = cmsCore::request('showicq', 'int'); $profiles['cm_subscribe'] = cmsCore::request('cm_subscribe', 'str'); if (!preg_match('/^([a-zA-Z]+)$/ui', $profiles['cm_subscribe'])) { $errors = true; } $users['phone'] = cmsCore::request('phone', 'int', 0); // получаем данные форм $profiles['formsdata'] = ''; if (isset($model->config['privforms'])) { if (is_array($model->config['privforms'])) { foreach ($model->config['privforms'] as $form_id) { $form_input = cmsForm::getFieldsInputValues($form_id); $profiles['formsdata'] .= $inDB->escape_string(cmsCore::arrayToYaml($form_input['values'])); // Проверяем значения формы foreach ($form_input['errors'] as $field_error) { if ($field_error) { cmsCore::addSessionMessage($field_error, 'error'); $errors = true; } } } } } if ($errors) { cmsCore::redirectBack(); } $inDB->update('cms_user_profiles', cmsCore::callEvent('UPDATE_USER_PROFILES', array_merge(array('id' => $usr['pid'], 'user_id' => $usr['id']), $profiles)), $usr['pid']); $inDB->update('cms_users', cmsCore::callEvent('UPDATE_USER_USERS', array_merge(array('id' => $usr['id']), $users)), $usr['id']); cmsCore::addSessionMessage($_LANG['PROFILE_SAVED'], 'info'); cmsCore::redirect(cmsUser::getProfileURL($usr['login'])); } if ($opt == 'changepass') { $errors = false; $oldpass = cmsCore::request('oldpass', 'str'); $newpass = cmsCore::request('newpass', 'str'); $newpass2 = cmsCore::request('newpass2', 'str'); if ($inUser->password != md5($oldpass)) { cmsCore::addSessionMessage($_LANG['OLD_PASS_WRONG'], 'error'); $errors = true; } if ($newpass != $newpass2) { cmsCore::addSessionMessage($_LANG['WRONG_PASS'], 'error'); $errors = true; } if ($oldpass && $newpass && $newpass2 && mb_strlen($newpass) < 6) { cmsCore::addSessionMessage($_LANG['PASS_SHORT'], 'error'); $errors = true; } if ($errors) { cmsCore::redirectBack(); } cmsCore::callEvent('UPDATE_USER_PASSWORD', array('user_id' => $usr['id'], 'oldpass' => $oldpass, 'newpass' => $newpass)); $sql = "UPDATE cms_users SET password='******' WHERE id = '{$id}' AND password='******'"; $inDB->query($sql); cmsCore::addSessionMessage($_LANG['PASS_CHANGED'], 'info'); cmsCore::redirect(cmsUser::getProfileURL($inUser->login)); } } //============================================================================// //============================= Просмотр профиля ============================// //============================================================================// if ($do == 'profile') { $inPage->addHeadJsLang(array('NEW_POST_ON_WALL', 'CONFIRM_DEL_POST_ON_WALL')); // если просмотр профиля гостям запрещен if (!$inUser->id && !$model->config['sw_guest']) { cmsUser::goToLogin(); } if (is_numeric($login)) { cmsCore::error404(); } $usr = $model->getUser($login); if (!$usr) { cmsCore::error404(); } $myprofile = $inUser->id == $usr['id']; $inPage->setTitle($usr['nickname']); $inPage->addPathway($usr['nickname']); // просмотр профиля запрещен if (!cmsUser::checkUserContentAccess($usr['allow_who'], $usr['id'])) { cmsPage::initTemplate('components', 'com_users_not_allow')->assign('is_auth', $inUser->id)->assign('usr', $usr)->display('com_users_not_allow.tpl'); return; } // Профиль удален if ($usr['is_deleted']) { cmsPage::initTemplate('components', 'com_users_deleted.tpl')->assign('usr', $usr)->assign('is_admin', $inUser->is_admin)->assign('others_active', $inDB->rows_count('cms_users', "login='******'login']}' AND is_deleted=0", 1))->display('com_users_deleted.tpl'); return; } // Данные о друзьях $usr['friends_total'] = cmsUser::getFriendsCount($usr['id']); $usr['friends'] = cmsUser::getFriends($usr['id']); // очищать сессию друзей если в своем профиле и количество друзей из базы не совпадает с количеством друзей в сессии if ($myprofile && sizeof($usr['friends']) != $usr['friends_total']) { cmsUser::clearSessionFriends(); } // обрезаем список $usr['friends'] = array_slice($usr['friends'], 0, 6); // выясняем друзья ли мы с текущим пользователем $usr['isfriend'] = !$myprofile ? cmsUser::isFriend($usr['id']) : false; // награды пользователя $usr['awards'] = $model->config['sw_awards'] ? $model->getUserAwards($usr['id']) : false; // стена if ($model->config['sw_wall']) { $inDB->limitPage(1, $model->config['wall_perpage']); $usr['wall_html'] = cmsUser::getUserWall($usr['id'], 'users', $myprofile, $inUser->is_admin); } // можно ли пользователю изменять карму $usr['can_change_karma'] = $model->isUserCanChangeKarma($usr['id']) && $inUser->id; // Фотоальбомы пользователя if ($model->config['sw_photo']) { $usr['albums'] = $model->getPhotoAlbums($usr['id'], $usr['isfriend'], !$inCore->isComponentEnable('photos')); $usr['albums_total'] = sizeof($usr['albums']); $usr['albums_show'] = 6; if ($usr['albums_total'] > $usr['albums_show']) { array_splice($usr['albums'], $usr['albums_show']); } } $usr['board_count'] = $model->config['sw_board'] ? $inDB->rows_count('cms_board_items', "user_id='{$usr['id']}' AND published=1") : 0; $usr['comments_count'] = $model->config['sw_comm'] ? $inDB->rows_count('cms_comments', "user_id='{$usr['id']}' AND published=1") : 0; $usr['forum_count'] = $model->config['sw_forum'] ? $inDB->rows_count('cms_forum_posts', "user_id = '{$usr['id']}'") : 0; $usr['files_count'] = $model->config['sw_files'] ? $inDB->rows_count('cms_user_files', "user_id = '{$usr['id']}'") : 0; $cfg_reg = $inCore->loadComponentConfig('registration'); $usr['invites_count'] = $inUser->id && $myprofile && $cfg_reg['reg_type'] == 'invite' ? $model->getUserInvitesCount($inUser->id) : 0; $usr['blog'] = $model->config['sw_blogs'] ? $inDB->get_fields('cms_blogs', "user_id = '{$usr['id']}' AND owner = 'user'", 'title, seolink') : false; $usr['form_fields'] = array(); if (is_array($model->config['privforms'])) { foreach ($model->config['privforms'] as $form_id) { $usr['form_fields'] = array_merge($usr['form_fields'], cmsForm::getFieldsValues($form_id, $usr['formsdata'])); } } if ($usr['city']) { cmsCore::loadModel('geo'); $geo = new cms_model_geo(); $city_parents = $geo->getCityParents($usr['city']); if ($city_parents) { $usr['country'] = $city_parents['country_name']; } } $plugins = $model->getPluginsOutput($usr); cmsPage::initTemplate('components', 'com_users_profile.tpl')->assign('usr', $usr)->assign('plugins', $plugins)->assign('cfg', $model->config)->assign('myprofile', $myprofile)->assign('cfg_forum', $inCore->loadComponentConfig('forum'))->assign('is_admin', $inUser->is_admin)->assign('is_auth', $inUser->id)->display('com_users_profile.tpl'); } //============================================================================// //============================= Список сообщений ============================// //============================================================================// if ($do == 'messages') { if (!$model->config['sw_msg']) { cmsCore::error404(); } if (!$inUser->id || $inUser->id != $id && !$inUser->is_admin) { cmsUser::goToLogin(); } $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::error404(); } $inPage->setTitle($_LANG['MY_MESS']); $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login'])); $inPage->addPathway($_LANG['MY_MESS'], '/users/' . $id . '/messages.html'); include 'components/users/messages.php'; } //============================================================================// //=========================== Отправка сообщения ============================// //============================================================================// if ($do == 'sendmessage') { if (!$model->config['sw_msg']) { cmsCore::halt(); } if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') { cmsCore::halt(); } if (!$inUser->id || $inUser->id == $id && !cmsCore::inRequest('massmail') && !cmsCore::request('send_to_group', 'int', 0)) { cmsCore::halt(); } if (!cmsCore::inRequest('gosend')) { $replyid = cmsCore::request('replyid', 'int', 0); if ($replyid) { $msg = $model->getReplyMessage($replyid, $inUser->id); if (!$msg) { cmsCore::halt(); } } $inPage->setRequestIsAjax(); cmsPage::initTemplate('components', 'com_users_messages_add')->assign('msg', isset($msg) ? $msg : array())->assign('is_reply_user', $replyid)->assign('id', $id)->assign('bbcodetoolbar', cmsPage::getBBCodeToolbar('message'))->assign('smilestoolbar', cmsPage::getSmilesPanel('message'))->assign('groups', $inUser->is_admin ? cmsUser::getGroups(true) : array())->assign('friends', cmsUser::getFriends($inUser->id))->assign('id_admin', $inUser->is_admin)->display('com_users_messages_add.tpl'); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } if (cmsCore::inRequest('gosend')) { // Кому отправляем $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::halt(); } $message = cmsCore::parseSmiles(cmsCore::request('message', 'html', ''), true); if (mb_strlen($message) < 2) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_SEND_MESS'])); } if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } $output = cmsCore::callEvent('USER_SEND_MESSEDGE', array('text' => $message, 'to_id' => $id)); $message = $output['text']; $id = $output['to_id']; $send_to_group = cmsCore::request('send_to_group', 'int', 0); $group_id = cmsCore::request('group_id', 'int', 0); // // Обычная отправка (1 получатель) // if (!cmsCore::inRequest('massmail') && !$send_to_group) { //отправляем сообщение $msg_id = cmsUser::sendMessage($inUser->id, $id, $message); // отправляем уведомление на email если нужно $model->sendNotificationByEmail($id, $inUser->id, $msg_id); cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['SEND_MESS_OK'])); } // // далее идут массовые рассылки, доступные только админам // if (!$inUser->is_admin) { cmsCore::halt(); } // отправить всем: получаем список всех пользователей if (cmsCore::inRequest('massmail')) { $userlist = cmsUser::getAllUsers(); // проверяем что есть кому отправлять if (!$userlist) { cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['ERR_SEND_MESS'])); } $count = array(); // отправляем всем по списку foreach ($userlist as $usr) { $count[] = cmsUser::sendMessage(USER_MASSMAIL, $usr['id'], $message); } cmsCore::jsonOutput(array('error' => false, 'text' => sprintf($_LANG['SEND_MESS_ALL_OK'], sizeof($count)))); } // отправить группе: получаем список членов группы if ($send_to_group) { $count = cmsUser::sendMessageToGroup(USER_MASSMAIL, $group_id, $message); $success_msg = sprintf($_LANG['SEND_MESS_GROUP_OK'], $count, cmsUser::getGroupTitle($group_id)); cmsCore::jsonOutput(array('error' => false, 'text' => $success_msg)); } } } //============================================================================// //============================= Удаление сообщения ==========================// //============================================================================// if ($do == 'delmessage') { if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') { cmsCore::halt(); } if (!$model->config['sw_msg']) { cmsCore::halt(); } if (!$inUser->id) { cmsCore::halt(); } $msg = $inDB->get_fields('cms_user_msg', "id='{$id}'", '*'); if (!$msg) { cmsCore::halt(); } $can_delete = $inUser->id == $msg['to_id'] || $inUser->id == $msg['from_id'] ? true : false; if (!$can_delete && !$inUser->is_admin) { cmsCore::halt(); } // Сообщения с from_id < 0 if ($msg['from_id'] < 0) { $inDB->query("DELETE FROM cms_user_msg WHERE id = '{$id}' LIMIT 1"); $info_text = $_LANG['MESS_NOTICE_DEL_OK']; } // мне сообщение от пользователя if ($msg['to_id'] == $inUser->id && $msg['from_id'] > 0) { $inDB->query("UPDATE cms_user_msg SET to_del=1 WHERE id='{$id}'"); $info_text = $_LANG['MESS_DEL_OK']; } // от меня сообщение if ($msg['from_id'] == $inUser->id && !$msg['is_new']) { $inDB->query("UPDATE cms_user_msg SET from_del=1 WHERE id='{$id}'"); $info_text = $_LANG['MESS_DEL_OK']; } // отзываем сообщение if ($msg['from_id'] == $inUser->id && $msg['is_new']) { $inDB->query("DELETE FROM cms_user_msg WHERE id = '{$id}' LIMIT 1"); $info_text = $_LANG['MESS_BACK_OK']; } // удаляем сообщения, которые удалены с двух сторон $inDB->query("DELETE FROM cms_user_msg WHERE to_del=1 AND from_del=1"); cmsCore::jsonOutput(array('error' => false, 'text' => $info_text)); } //============================================================================// //=========================== Удаление сообщений ============================// //============================================================================// if ($do == 'delmessages') { if (!$model->config['sw_msg']) { cmsCore::error404(); } if ($inUser->id != $id && !$inUser->is_admin) { cmsCore::error404(); } $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::error404(); } $opt = cmsCore::request('opt', 'str', 'in'); if ($opt == 'notices') { $inDB->query("DELETE FROM cms_user_msg WHERE to_id = '{$id}' AND from_id < 0"); } else { $del_flag = $opt == 'in' ? 'to_del' : 'from_del'; $id_flag = $opt == 'in' ? 'to_id' : 'from_id'; $inDB->query("UPDATE cms_user_msg SET {$del_flag}=1 WHERE {$id_flag}='{$id}'"); $inDB->query("DELETE FROM cms_user_msg WHERE to_del=1 AND from_del=1"); } cmsCore::addSessionMessage($_LANG['MESS_ALL_DEL_OK'], 'info'); cmsCore::redirectBack(); } //============================================================================// //============================= Загрузка аватара ============================// //============================================================================// if ($do == 'avatar') { if (!$inUser->id || $inUser->id && $inUser->id != $id) { cmsCore::error404(); } $inPage->setTitle($_LANG['LOAD_AVATAR']); $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login)); $inPage->addPathway($_LANG['LOAD_AVATAR']); if (cmsCore::inRequest('upload')) { cmsCore::loadClass('upload_photo'); $inUploadPhoto = cmsUploadPhoto::getInstance(); // Выставляем конфигурационные параметры $inUploadPhoto->upload_dir = PATH . '/images/'; $inUploadPhoto->dir_medium = 'users/avatars/'; $inUploadPhoto->dir_small = 'users/avatars/small/'; $inUploadPhoto->small_size_w = $model->config['smallw']; $inUploadPhoto->medium_size_w = $model->config['medw']; $inUploadPhoto->medium_size_h = $model->config['medh']; $inUploadPhoto->is_watermark = false; $inUploadPhoto->input_name = 'picture'; $file = $inUploadPhoto->uploadPhoto($inUser->orig_imageurl); if (!$file) { cmsCore::addSessionMessage('<strong>' . $_LANG['ERROR'] . ':</strong> ' . cmsCore::uploadError() . '!', 'error'); cmsCore::redirect('/users/' . $id . '/avatar.html'); } $sql = "UPDATE cms_user_profiles SET imageurl = '{$file['filename']}' WHERE user_id = '{$id}' LIMIT 1"; $inDB->query($sql); // очищаем предыдущую запись о смене аватара cmsActions::removeObjectLog('add_avatar', $id); // выводим сообщение в ленту cmsActions::log('add_avatar', array('object' => '', 'object_url' => '', 'object_id' => $id, 'target' => '', 'target_url' => '', 'description' => '<a href="' . cmsUser::getProfileURL($inUser->login) . '" class="act_usr_ava"> <img border="0" src="/images/users/avatars/small/' . $file['filename'] . '"> </a>')); cmsCore::redirect(cmsUser::getProfileURL($inUser->login)); } else { cmsPage::initTemplate('components', 'com_users_avatar_upload')->assign('id', $id)->display('com_users_avatar_upload.tpl'); } } //============================================================================// //============================= Библиотека аватаров =========================// //============================================================================// if ($do == 'select_avatar') { if (!$inUser->id || $inUser->id && $inUser->id != $id) { cmsCore::error404(); } $avatars_dir = PATH . "/images/users/avatars/library"; $avatars_dir_rel = "/images/users/avatars/library"; $avatars_dir_handle = opendir($avatars_dir); $avatars = array(); while ($nextfile = readdir($avatars_dir_handle)) { if ($nextfile != '.' && $nextfile != '..' && (mb_strstr($nextfile, '.gif') || mb_strstr($nextfile, '.jpg') || mb_strstr($nextfile, '.jpeg') || mb_strstr($nextfile, '.png'))) { $avatars[] = $nextfile; } } closedir($avatars_dir_handle); if (!cmsCore::inRequest('set_avatar')) { $inPage->setTitle($_LANG['SELECT_AVATAR']); $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login)); $inPage->addPathway($_LANG['SELECT_AVATAR']); $perpage = 20; $total = sizeof($avatars); $avatars = array_slice($avatars, ($page - 1) * $perpage, $perpage); cmsPage::initTemplate('components', 'com_users_avatars')->assign('userid', $id)->assign('avatars', $avatars)->assign('avatars_dir', $avatars_dir_rel)->assign('page', $page)->assign('perpage', $perpage)->assign('pagebar', cmsPage::getPagebar($total, $page, $perpage, '/users/%user_id%/select-avatar-%page%.html', array('user_id' => $id)))->display('com_users_avatars.tpl'); } else { $avatar_id = cmsCore::request('avatar_id', 'int', 0); $file = $avatars[$avatar_id]; if (file_exists($avatars_dir . '/' . $file)) { $uploaddir = PATH . '/images/users/avatars/'; $realfile = $file; $filename = md5($realfile . '-' . $id . '-' . time()) . '.jpg'; $uploadfile = $avatars_dir . '/' . $realfile; $uploadavatar = $uploaddir . $filename; $uploadthumb = $uploaddir . 'small/' . $filename; if ($inUser->orig_imageurl && $inUser->orig_imageurl != 'nopic.jpg') { @unlink(PATH . '/images/users/avatars/' . $inUser->orig_imageurl); @unlink(PATH . '/images/users/avatars/small/' . $inUser->orig_imageurl); } cmsCore::includeGraphics(); copy($uploadfile, $uploadavatar); @img_resize($uploadfile, $uploadthumb, $model->config['smallw'], $model->config['smallw']); $sql = "UPDATE cms_user_profiles SET imageurl = '{$filename}' WHERE user_id = '{$id}' LIMIT 1"; $inDB->query($sql); // очищаем предыдущую запись о смене аватара cmsActions::removeObjectLog('add_avatar', $id); // выводим сообщение в ленту cmsActions::log('add_avatar', array('object' => '', 'object_url' => '', 'object_id' => $id, 'target' => '', 'target_url' => '', 'description' => '<a href="' . cmsUser::getProfileURL($inUser->login) . '" class="act_usr_ava"> <img border="0" src="/images/users/avatars/small/' . $filename . '"> </a>')); } cmsCore::redirect(cmsUser::getProfileURL($inUser->login)); } } //============================================================================// //======================== Работа с фотографиями ============================// //============================================================================// if ($do == 'photos') { if (!$model->config['sw_photo']) { cmsCore::error404(); } $pdo = cmsCore::request('pdo', 'str', ''); include 'components/users/photos.php'; } //============================================================================// //============================= Друзья пользователя =========================// //============================================================================// if ($do == 'friendlist') { if (!$inUser->id) { cmsUser::goToLogin(); } $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::error404(); } $perpage = 10; $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login'])); $inPage->addPathway($_LANG['FRIENDS']); $inPage->setTitle($_LANG['FRIENDS']); // все друзья $friends = cmsUser::getFriends($usr['id']); // их общее количество $total = count($friends); // получаем только нужных на странице $friends = array_slice($friends, ($page - 1) * $perpage, $perpage); cmsPage::initTemplate('components', 'com_users_friends')->assign('friends', $friends)->assign('usr', $usr)->assign('myprofile', $id == $inUser->id)->assign('total', $total)->assign('pagebar', cmsPage::getPagebar($total, $page, $perpage, 'javascript:centerLink(\'/users/' . $id . '/friendlist%page%.html\')'))->display('com_users_friends.tpl'); } //============================================================================// //============================= Запрос на дружбу ============================// //============================================================================// if ($do == 'addfriend') { if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') { cmsCore::halt(); } if (!$inUser->id || $inUser->id == $id) { cmsCore::halt(); } $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::halt(); } cmsUser::clearSessionFriends(); if (cmsUser::isFriend($id)) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['YOU_ARE_BE_FRIENDS'])); } // проверяем был ли ранее запрос на дружбу // если был, то делаем accept запросу $is_need_accept_id = cmsUser::getFriendFieldId($id, 0, 'to_me'); if ($is_need_accept_id) { $inDB->query("UPDATE cms_user_friends SET is_accepted = 1 WHERE id = '{$is_need_accept_id}'"); //регистрируем событие cmsActions::log('add_friend', array('object' => $inUser->nickname, 'user_id' => $usr['id'], 'object_url' => cmsUser::getProfileURL($inUser->login), 'object_id' => $is_need_accept_id, 'target' => '', 'target_url' => '', 'target_id' => 0, 'description' => '')); cmsCore::callEvent('USER_ACCEPT_FRIEND', $id); cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['ADD_FRIEND_OK'] . $usr['nickname'])); } // Если пользователь пытается добавиться в друзья к // пользователю, к которому уже отправил запрос if (cmsUser::getFriendFieldId($id, 0, 'from_me')) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ADD_TO_FRIEND_SEND_ERR'])); } // Мы вообще не друзья с пользователем, создаем запрос cmsUser::addFriend($id); cmsUser::sendMessage(USER_UPDATER, $id, sprintf($_LANG['RECEIVED_F_O'], cmsUser::getProfileLink($inUser->login, $inUser->nickname), '<a class="ajaxlink" href="javascript:void(0)" onclick="users.acceptFriend(' . $inUser->id . ', this);return false;">' . $_LANG['ACCEPT'] . '</a>', '<a class="ajaxlink" href="javascript:void(0)" onclick="users.rejectFriend(' . $inUser->id . ', this);return false;">' . $_LANG['REJECT'] . '</a>')); cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['ADD_TO_FRIEND_SEND'])); } //============================================================================// //============================= Прекращение дружбы ==========================// //============================================================================// if ($do == 'delfriend') { if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') { cmsCore::halt(); } if (!$inUser->id || $inUser->id == $id) { cmsCore::halt(); } $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::error404(); } if (cmsUser::getFriendFieldId($id)) { $is_accepted_friend = cmsUser::isFriend($id); if (cmsUser::deleteFriend($id)) { // Если подтвержденный друг if ($is_accepted_friend) { cmsCore::jsonOutput(array('error' => false, 'text' => $usr['nickname'] . $_LANG['DEL_FRIEND'])); } else { cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['REJECT_FRIEND'] . $usr['nickname'])); } } else { cmsCore::halt(); } } else { cmsCore::halt(); } } //============================================================================// //============================= История кармы ===============================// //============================================================================// if ($do == 'karma') { $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::error404(); } $inPage->setTitle($_LANG['KARMA_HISTORY']); $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login'])); $inPage->addPathway($_LANG['KARMA_HISTORY']); cmsPage::initTemplate('components', 'com_users_karma')->assign('karma', $model->getUserKarma($usr['id']))->assign('usr', $usr)->display('com_users_karma.tpl'); } //============================================================================// //============================= Изменение кармы =============================// //============================================================================// if ($do == 'votekarma') { if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') { cmsCore::halt(); } if (!$inUser->id) { cmsCore::halt(); } $points = cmsCore::request('sign', 'str', 'plus') == 'plus' ? 1 : -1; $to = cmsCore::request('to', 'int', 0); $user = cmsUser::getShortUserData($to); if (!$user) { cmsCore::halt(); } if (!$model->isUserCanChangeKarma($to)) { cmsCore::halt(); } cmsCore::halt(cmsUser::changeKarmaUser($to, $points)); } //============================================================================// //======================= Наградить пользователя ============================// //============================================================================// if ($do == 'giveaward') { if (!$inUser->is_admin) { cmsCore::error404(); } $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::error404(); } $inPage->setTitle($_LANG['AWARD_USER']); $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login'])); $inPage->addPathway($_LANG['AWARD']); if (!cmsCore::inRequest('gosend')) { cmsPage::initTemplate('components', 'com_users_awards_give')->assign('usr', $usr)->assign('awardslist', cmsUser::getAwardsImages())->display('com_users_awards_give.tpl'); } else { $award['title'] = cmsCore::request('title', 'str', $_LANG['AWRD']); $award['description'] = cmsCore::request('description', 'str', ''); $award['imageurl'] = cmsCore::request('imageurl', 'str', ''); $award['from_id'] = $inUser->id; $award['id'] = 0; cmsUser::giveAward($award, $id); cmsCore::redirect(cmsUser::getProfileURL($usr['login'])); } } //============================================================================// //============================= Удаление награды ============================// //============================================================================// if ($do == 'delaward') { $aw = $inDB->get_fields('cms_user_awards', "id = '{$id}'", '*'); if (!$aw) { cmsCore::error404(); } if (!$inUser->id || $inUser->id != $aw['user_id'] && !$inUser->is_admin) { cmsCore::error404(); } $inDB->delete('cms_user_awards', "id = '{$id}'", 1); cmsActions::removeObjectLog('add_award', $id); cmsCore::redirectBack(); } //============================================================================// //============================= Награды на сайте ============================// //============================================================================// if ($do == 'awardslist') { $inPage->setTitle($_LANG['SITE_AWARDS']); $inPage->addPathway($_LANG['SITE_AWARDS']); $awards = cmsUser::getAutoAwards(); if (!$awards) { cmsCore::error404(); } foreach ($awards as $aw) { //Перебираем все награды и ищем пользователей с текущей наградой $sql = "SELECT u.id as id, u.nickname as nickname, u.login as login, IFNULL(p.gender, 'm') as gender\r\n FROM cms_user_awards aw\r\n LEFT JOIN cms_users u ON u.id = aw.user_id\r\n LEFT JOIN cms_user_profiles p ON p.user_id = u.id\r\n WHERE aw.award_id = '{$aw['id']}'"; $rs = $inDB->query($sql); $aw['uhtml'] = ''; if ($inDB->num_rows($rs)) { while ($user = $inDB->fetch_assoc($rs)) { $aw['uhtml'] .= cmsUser::getGenderLink($user['id'], $user['nickname'], $user['gender'], $user['login']) . ', '; } $aw['uhtml'] = rtrim($aw['uhtml'], ', '); } else { $aw['uhtml'] = $_LANG['NOT_USERS_WITH_THIS_AWARD']; } $aws[] = $aw; } cmsPage::initTemplate('components', 'com_users_awards_site')->assign('aws', $aws)->display('com_users_awards_site.tpl'); } //============================================================================// //============================= Удаление профиля ============================// //============================================================================// if ($do == 'delprofile') { // неавторизованным тут делать нечего if (!$inUser->id) { cmsCore::error404(); } // есть ли удаляемый профиль $data = cmsUser::getShortUserData($id); if (!$data) { cmsCore::error404(); } // владелец профиля или админ if ($inUser->is_admin) { // могут ли администраторы удалять профиль if (!cmsUser::isAdminCan('admin/users', cmsUser::getAdminAccess())) { cmsCore::error404(); } // администратор сам себя не удалит if ($inUser->id == $data['id']) { cmsCore::error404(); } } else { // удаляем только свой профиль if ($inUser->id != $data['id']) { cmsCore::error404(); } } if (isset($_POST['csrf_token'])) { if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } $model->deleteUser($id); if (!$inUser->is_admin) { session_destroy(); cmsCore::redirect('/logout'); } else { cmsCore::addSessionMessage($_LANG['DELETING_PROFILE_OK'], 'info'); cmsCore::redirect('/users'); } } else { $inPage->setTitle($_LANG['DELETING_PROFILE']); $inPage->addPathway($data['nickname'], $inUser->getProfileURL($data['login'])); $inPage->addPathway($_LANG['DELETING_PROFILE']); $confirm['title'] = $_LANG['DELETING_PROFILE']; $confirm['text'] = '<p>' . $_LANG['REALLY_DEL_PROFILE'] . '</p>'; $confirm['action'] = '/users/' . $id . '/delprofile.html'; $confirm['yes_button'] = array(); $confirm['yes_button']['type'] = 'submit'; cmsPage::initTemplate('components', 'action_confirm.tpl')->assign('confirm', $confirm)->display('action_confirm.tpl'); } } //============================================================================// //============================ Восстановить профиль =========================// //============================================================================// if ($do == 'restoreprofile') { if (!$inUser->is_admin) { cmsCore::error404(); } $usr = cmsUser::getShortUserData($id); if (!$usr) { cmsCore::error404(); } $inDB->query("UPDATE cms_users SET is_deleted = 0 WHERE id = '{$id}'"); cmsCore::redirectBack(); } //============================================================================// //============================= Файлы пользователей =========================// //============================================================================// if ($do == 'files') { if (!$model->config['sw_files']) { cmsCore::error404(); } $fdo = cmsCore::request('fdo', 'str', ''); include 'components/users/files.php'; } //============================================================================// //================================ Инвайты =================================// //============================================================================// if ($do == 'invites') { $reg_cfg = $inCore->loadComponentConfig('registration'); if ($reg_cfg['reg_type'] != 'invite') { cmsCore::error404(); } $invites_count = $model->getUserInvitesCount($inUser->id); if (!$invites_count) { cmsCore::error404(); } if (!cmsCore::inRequest('send_invite')) { $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login)); $inPage->addPathway($_LANG['MY_INVITES']); cmsPage::initTemplate('components', 'com_users_invites')->assign('invites_count', $invites_count)->display('com_users_invites.tpl'); return; } if (cmsCore::inRequest('send_invite')) { if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); } $invite_email = cmsCore::request('invite_email', 'email', ''); if (!$invite_email) { cmsCore::redirectBack(); } if ($model->sendInvite($inUser->id, $invite_email)) { cmsCore::addSessionMessage(sprintf($_LANG['INVITE_SENDED'], $invite_email), 'success'); } else { cmsCore::addSessionMessage($_LANG['INVITE_ERROR'], 'error'); } cmsCore::redirect(cmsUser::getProfileURL($inUser->login)); } } if ($do == 'change_email') { if (!$inUser->id) { cmsUser::goToLogin(); } $email = cmsCore::request('email', 'email', ''); $token = cmsCore::request('token', 'str', ''); // не занят ли email $is_email = $inDB->get_field('cms_users', "email='{$email}'", 'id'); if ($is_email || !$email || !$token) { cmsCore::error404(); } // проверяем токен $valid_id = $inDB->get_field('cms_users_activate', "code='{$token}' AND user_id = '{$inUser->id}'", 'id'); if (!$valid_id) { cmsCore::error404(); } $inDB->delete('cms_users_activate', "id = '{$valid_id}'"); // Сохраняем новый email $inDB->update('cms_users', array('email' => $email), $inUser->id); cmsCore::addSessionMessage($_LANG['NEW_EMAIL_SAVED'], 'success'); cmsCore::redirect(cmsUser::getProfileURL($inUser->login)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }
function calendar() { $inCore = cmsCore::getInstance(); $inPage = cmsPage::getInstance(); $inUser = cmsUser::getInstance(); $inCore->loadModel('calendar'); $model = new cms_model_calendar(); $do = $inCore->request('do', 'str', 'view'); $cfg = $inCore->loadComponentConfig('calendar'); if ($do == 'view') { $inPage->setTitle("Календарь событий"); $smarty = $inCore->initSmarty('components', 'com_calendar_view.tpl'); $guest = TRUE; if ($inUser->id == 0 and $cfg['calendar_access'] == "all") { $guest = FALSE; } if ($inUser->id != 0 and $cfg['calendar_access'] == "users") { $guest = FALSE; } if ($inUser->is_admin) { $guest = FALSE; } $catigories = $model->getAllCategories(); $smarty->assign('guest', $guest); $smarty->assign('cfg', $cfg); $smarty->assign('catigories', $catigories); $smarty->assign('category', "all"); $smarty->display('com_calendar_view.tpl'); return; } if ($do == "category_view") { $category_id = $inCore->request('category_id', 'int', 0); $smarty = $inCore->initSmarty('components', 'com_calendar_view.tpl'); $guest = TRUE; if ($inUser->id == 0 and $cfg['calendar_access'] == "all") { $guest = FALSE; } if ($inUser->id != 0 and $cfg['calendar_access'] == "users") { $guest = FALSE; } if ($inUser->is_admin) { $guest = FALSE; } $category = $model->getCategory($category_id); $catigories = $model->getAllCategories(); if (!$category) { //$inCore->redirect("/calendar"); print mysql_error(); } $inPage->setTitle("Календарь событий:" . $category['title']); $smarty->assign('guest', $guest); $smarty->assign('cfg', $cfg); $smarty->assign('catigories', $catigories); $smarty->assign('category', $category_id); $smarty->display('com_calendar_view.tpl'); return; } if ($do == 'add') { $guest = TRUE; if ($inUser->id == 0 and $cfg['calendar_access'] == "all") { $guest = FALSE; } if ($inUser->id != 0 and $cfg['calendar_access'] == "users") { $guest = FALSE; } if ($inUser->is_admin) { $guest = FALSE; } if ($guest) { $inCore->redirect('/'); exit; } $is_send = $inCore->inRequest('title'); if ($is_send) { $title = $inCore->request('title', 'str'); $type_raw = $inCore->request('type', 'str'); $date_start = $inCore->request('date_start', 'str'); $date_end = $inCore->request('date_end', 'str'); $hour_start = $inCore->request('hour_start', 'str'); $hour_end = $inCore->request('hour_end', 'str'); $min_start = $inCore->request('min_start', 'str'); $min_end = $inCore->request('min_end', 'str'); $content = $inCore->request('content', 'str'); if (!$title || !$type_raw || !$date_start || !$hour_start || !$hour_end || !$min_start || !$min_end) { cmsCore::addSessionMessage('Ой, что то не было заполнено...', 'error'); $inCore->redirectBack(); exit; } else { $start_time = strtotime($date_start . ' ' . $hour_start . ':' . $min_start); $end_time = strtotime($date_end . ' ' . $hour_end . ':' . $min_end); if ($data_end == "" or $date_end < $date_start) { $data_end = $data_start; } $type_data = explode("_", $type_raw); $type = $type_data[0]; $apx = $type_data[1]; $event_id = $model->addEvent($inUser->id, $type, $apx, $start_time, $end_time, $title, $content); if ($event_id) { if ($type != "private") { cmsActions::log('add_event', array('object' => 'событие', 'object_url' => '/calendar/event' . $event_id . '.html', 'object_id' => $event_id, 'target' => $title, 'target_url' => '/calendar/event' . $event_id . '.html', 'target_id' => '0', 'description' => $title)); } cmsCore::addSessionMessage('Ваше мероприятие добавлено!', 'success'); } else { cmsCore::addSessionMessage('Ошибка добавления!', 'error'); } $inCore->redirect('/calendar'); exit; } } if ($event['start_time'] == "") { $event['start_time'] = time(); } if ($event['end_time'] == "") { $event['end_time'] = time(); } $bb_toolbar = cmsPage::getBBCodeToolbar('message', $cfg['img_on'], 'forum'); $smilies = cmsPage::getSmilesPanel('message'); $inPage->setTitle("Добавить событие"); $smarty = $inCore->initSmarty('components', 'com_calendar_add.tpl'); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->assign('title', $event['title']); $smarty->assign('content', $event['content']); $smarty->assign('type', $event['type']); $smarty->assign('start_date', date("d.m.Y", $event['start_time'])); $smarty->assign('start_hour', date("H", $event['start_time'])); $smarty->assign('start_min', date("i", $event['start_time'])); $smarty->assign('end_date', date("d.m.Y", $event['end_time'])); $smarty->assign('end_hour', date("H", $event['end_time'])); $smarty->assign('end_min', date("i", $event['end_time'])); $smarty->display('com_calendar_add.tpl'); return; } if ($do == "view_event") { $event_id = $inCore->request('event_id', 'int', 0); /*FOTOLIB*/ include 'fotolib.class.php'; $foto = new FotoLib(); //Проверяем можем ли добавлять фото $allow_add_foto = $foto->addAcces("calendar"); if ($_FILES) { $foto->uploadFoto($_FILES, "calendar", $event_id); } $images = $foto->loadImages("calendar", $event_id); /*FOTOLIB*/ $event = $model->getEvent($event_id); if (!$event) { cmsCore::addSessionMessage('Ошибка запроса' . mysql_error(), 'error'); $inCore->redirect('/calendar'); exit; } else { if ($event['type'] == 'private' and $event['author_id'] != $inUser->id) { cmsCore::addSessionMessage('Ошибка запроса', 'error'); $inCore->redirect('/calendar'); exit; } $msg = $inCore->parseSmiles($event['content'], true); if (count($event['parent']) != 0) { $delta = $event['end_time'] - $event['start_time']; $day = date("d", $event['start_time']); $month = date("n", $event['start_time']) - 1; //Яваскриптики считают с 0 $year = date("Y", $event['start_time']); if ($delta < 24 * 60 * 60) { $calendar_view = "agendaDay"; if (date("d", $event['start_time']) != date("d", $event['end_time'])) { //Если меньше 24 часов но всё же в разные дни включаем недельный вид $calendar_view = "agendaWeek"; } } elseif ($delta < 7 * 24 * 60 * 60) { $calendar_view = "agendaWeek"; } else { $calendar_view = "month"; } $events_string = ""; foreach ($event['parent'] as $parent) { $events_string .= "{\n\t id : '" . $parent['id'] . "',\n\t title : '" . str_replace("'", '"', $parent['title']) . "',\n\t start : '" . date("Y-m-d H:i:s", $parent['start_time']) . "',\n\t end : '" . date("Y-m-d H:i:s", $parent['end_time']) . "',\n\t url : '/calendar/event" . $parent['id'] . ".html',"; if ($parent['end_time'] - $parent['start_time'] > 60 * 60 * 8) { $events_string .= "allDay: true,"; } else { $events_string .= "allDay: false,"; } switch ($parent['type']) { case "public": if ($parent['author_id'] == $inUser->id) { $events_string .= "color: '#B9C3BC',\n"; } else { $events_string .= "color: '#C3BCB9',\n"; } $events_string .= "textColor: '#000000',\n"; break; case "private": $events_string .= "color: '#3366CC'\n"; } $events_string .= "},"; } } $issignup = $model->isSignup($event_id); $singups_user = $model->getSingupsUsers($event_id); $inPage->setTitle('Просмотр события "' . $event['title'] . '"'); $smarty = $inCore->initSmarty('components', 'com_calendar_event_view.tpl'); $smarty->assign('event', $event); $smarty->assign('content', $msg); $smarty->assign('parent', $event['parent']); $smarty->assign('calendar_view', $calendar_view); $smarty->assign('events_string', $events_string); $smarty->assign('year', $year); $smarty->assign('month', $month); $smarty->assign('day', $day); $smarty->assign('start_time', date("d.m.Y H:i", $event['start_time'])); $smarty->assign('end_time', date("d.m.Y H:i", $event['end_time'])); $smarty->assign('issngnup', $issignup); $smarty->assign('singups_user', $singups_user); $smarty->assign('images', $images); //fotolib $smarty->assign('allow_add_foto', $allow_add_foto); //fotolib if ($event['start_time'] - time() < 0) { $status = "Прошедшее событие"; } else { if ($event['start_time'] - time() > 86400) { $status = 'Осталось ' . declension(round(($event['start_time'] - time()) / 86400), array("день", "дня", "дней")); } else { $status = 'Осталось ' . declension(round(($event['start_time'] - time()) / 3600), array("час", "часа", "часов")); } } $smarty->assign('status', $status); if ($inUser->id == $event['author_id'] or $inUser->is_admin) { $smarty->assign('admin', TRUE); } $smarty->display('com_calendar_event_view.tpl'); $inCore->includeComments(); comments('calendar', $event_id); return; } } if ($do == "delete_event") { if ($inUser->id == 0) { $inCore->redirect('/'); exit; } $event_id = $inCore->request('event_id', 'int', 0); $deleted = $model->deleteEvent($event_id); if ($deleted) { cmsCore::addSessionMessage('Ваше мероприятие удалено!', 'success'); $inCore->redirect('/calendar'); exit; } else { cmsCore::addSessionMessage('Ошибка', 'error'); $inCore->redirect('/calendar'); exit; } } if ($do == "edit_event") { if ($inUser->id == 0) { $inCore->redirect('/'); exit; } $event_id = $inCore->request('event_id', 'int', 0); $event = $model->getEvent($event_id); if ($event["author_id"] != $inUser->id and !$inUser->is_admin) { cmsCore::addSessionMessage('Ошибка доступа', 'error'); $inCore->redirectBack(); exit; } $is_send = $inCore->inRequest('title'); if ($is_send) { $title = $inCore->request('title', 'str'); $type = $inCore->request('type', 'str'); $date_start = $inCore->request('date_start', 'str'); $date_end = $inCore->request('date_end', 'str'); $hour_start = $inCore->request('hour_start', 'str'); $hour_end = $inCore->request('hour_end', 'str'); $min_start = $inCore->request('min_start', 'str'); $min_end = $inCore->request('min_end', 'str'); $content = $inCore->request('content', 'str'); if (!$title || !$type || !$date_start || !$hour_start || !$hour_end || !$min_start || !$min_end) { cmsCore::addSessionMessage('Ой, что то не было заполнено...', 'error'); $inCore->redirectBack(); exit; } else { $start_time = strtotime($date_start . ' ' . $hour_start . ':' . $min_start); if ($data_end == "" or $data_end < $data_start) { $data_end = $data_start; } $end_time = strtotime($date_end . ' ' . $hour_end . ':' . $min_end); if (!is_numeric($type)) { $category_id = "0"; } else { $category_id = $type; $type = "public"; } $update = $model->updateEvent($event_id, $type, $category_id, $start_time, $end_time, $title, $content); if ($update) { cmsCore::addSessionMessage('Ваше мероприятие изменено!', 'success'); $inCore->redirect('/calendar/event' . $event_id . '.html'); exit; } else { cmsCore::addSessionMessage('Ошибка добавления!', 'error'); $inCore->redirect('/calendar/edit' . $event_id . '.html'); exit; } } } else { $event = $model->getEvent($event_id); if (!$event) { cmsCore::addSessionMessage('Ошибка запроса', 'error'); $inCore->redirect('/calendar'); exit; } if ($event['category_id']) { $event['type'] = $event['category_id']; } $bb_toolbar = cmsPage::getBBCodeToolbar('calendar', 1, 'forum'); $smilies = cmsPage::getSmilesPanel('calendar'); //Проверяем присоедиялся ли пользователь ко встрече $catigories = $model->getAllCategories(); $inPage->setTitle("Редактировать событие"); $smarty = $inCore->initSmarty('components', 'com_calendar_add.tpl'); $smarty->assign('event', $event); $smarty->assign('edit', 1); $smarty->assign('catigories', $catigories); $smarty->assign('title', $event['title']); $smarty->assign('content', $event['content']); $smarty->assign('type', $event['type']); $smarty->assign('start_date', date("d.m.Y", $event['start_time'])); $smarty->assign('start_hour', date("H", $event['start_time'])); $smarty->assign('start_min', date("i", $event['start_time'])); $smarty->assign('end_date', date("d.m.Y", $event['end_time'])); $smarty->assign('end_hour', date("H", $event['end_time'])); $smarty->assign('end_min', date("i", $event['end_time'])); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->display('com_calendar_add.tpl'); return; } } if ($do == "add_parent") { if ($inUser->id == 0) { $inCore->redirectBack(); return; } $event_id = $inCore->request('event_id', 'int', 0); $event = $model->getEvent($event_id); if (!$event) { $inCore->redirectBack(); return; } $is_send = $inCore->inRequest('title'); if ($is_send) { $title = $inCore->request('title', 'str'); $date_start = $inCore->request('date_start', 'str'); $date_end = $inCore->request('date_end', 'str'); $hour_start = $inCore->request('hour_start', 'str'); $hour_end = $inCore->request('hour_end', 'str'); $min_start = $inCore->request('min_start', 'str'); $min_end = $inCore->request('min_end', 'str'); $content = $inCore->request('content', 'str'); if (!$title || !$date_start || !$hour_start || !$hour_end || !$min_start || !$min_end) { cmsCore::addSessionMessage('Ой, что то не было заполнено...', 'error'); $inCore->redirectBack(); exit; } else { $start_time = strtotime($date_start . ' ' . $hour_start . ':' . $min_start); $end_time = strtotime($date_end . ' ' . $hour_end . ':' . $min_end); if ($data_end == "" or $date_end < $date_start) { $data_end = $data_start; } $type = $event['type']; $model->addEvent($inUser->id, $type, $apx, $start_time, $end_time, $title, $content, $event['id']); $inCore->redirect('/calendar/event' . $event['id'] . ".html"); exit; } } $bb_toolbar = cmsPage::getBBCodeToolbar('message', $cfg['img_on'], 'forum'); $smilies = cmsPage::getSmilesPanel('message'); $inPage->setTitle("Добавить вложеное событие"); $smarty = $inCore->initSmarty('components', 'com_calendar_add.tpl'); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->assign('parent', "1"); $smarty->assign('parent_title', $event['title']); $smarty->assign('title', ""); $smarty->assign('content', ""); $smarty->assign('type', $event['type']); $smarty->assign('start_date', date("d.m.Y", $event['start_time'])); $smarty->assign('start_hour', date("H", $event['start_time'])); $smarty->assign('start_min', date("i", $event['start_time'])); $smarty->assign('end_date', date("d.m.Y", $event['end_time'])); $smarty->assign('end_hour', date("H", $event['end_time'])); $smarty->assign('end_min', date("i", $event['end_time'])); $smarty->display('com_calendar_add.tpl'); return; } if ($do == "event_signup") { //Если не залогинились то возвращаем обратно if ($inUser->id == 0) { $inCore->redirectBack(); return; } $event_id = $inCore->request('event_id', 'int', 0); $event = $model->getEvent($event_id); //Если приватное событие то отправляем обратно if ($event["type"] == "private") { $inCore->redirectBack(); return; } //Если мероприятие уже прошло говорим ай-яй-яй if ($event['start_time'] - time() < 0) { cmsCore::addSessionMessage('Присоединиться к мероприятию уже невозможно', 'error'); $inCore->redirectBack(); exit; } //Проверяем статус присоединения ко встрече if ($model->isSignup($event_id)) { //Если уже присоединялись то удаляем и выводим статус $model->deleteSignup($event_id); cmsCore::addSessionMessage('Вы отказались от участия в мероприятии ' . $event["title"], 'success'); // Добавляем событие в ленту cmsActions::log('del_signup', array('object' => $event["title"], 'object_url' => '/calendar/event' . $event_id . '.html', 'object_id' => $event_id, 'target' => '', 'target_url' => '/calendar/event' . $event_id . '.html', 'target_id' => '0', 'description' => '')); $inCore->redirect('/calendar/event' . $event_id . '.html'); } else { //Если не присоединялись то добавляем в базу и выводим статус //Если уже присоединялись то удаляем и выводим статус $model->addSignup($event["id"]); cmsCore::addSessionMessage('Вы присоединились к событию ' . $event["title"], 'success'); // Добавляем событие в ленту cmsActions::log('add_signup', array('object' => $event["title"], 'object_url' => '/calendar/event' . $event_id . '.html', 'object_id' => $event["id"], 'target' => '', 'target_url' => '/calendar/event' . $event_id . '.html', 'target_id' => '0', 'description' => '')); $inCore->redirect('/calendar/event' . $event_id . '.html'); } return; } //AJAX if ($do == "ajax_add") { $guest = TRUE; if ($inUser->id == 0 and $cfg['calendar_access'] == "all") { $guest = FALSE; } if ($inUser->id != 0 and $cfg['calendar_access'] == "users") { $guest = FALSE; } if ($inUser->is_admin) { $guest = FALSE; } if (!$guest) { $title = iconv("utf8", "cp1251", $inCore->request('title', 'str')); $type = $inCore->request('type', 'str'); $date_start = $inCore->request('date_start', 'str'); $date_end = $inCore->request('date_end', 'str'); $hour_start = $inCore->request('hour_start', 'str'); $hour_end = $inCore->request('hour_end', 'str'); $min_start = $inCore->request('min_start', 'str'); $min_end = $inCore->request('min_end', 'str'); $content = iconv("utf8", "cp1251", $inCore->request('content', 'str')); $start_time = strtotime($date_start . ' ' . $hour_start . ':' . $min_start); $end_time = strtotime($date_end . ' ' . $hour_end . ':' . $min_end); if ($type == "prvate") { $category_id = 0; $type = "private"; } else { if (is_numeric($type)) { $category_id = $type; } else { $category_id = 0; } $type = "public"; } $event_id = $model->addEvent($inUser->id, $type, $category_id, $start_time, $end_time, $title, $content); $output = array(); if (!$event_id) { $output['error'] = TRUE; $output['errortext'] = iconv("CP1251", "UTF-8", "Ошибка БД"); } else { $output['error'] = FALSE; $event = $model->getEvent($event_id); $output['event_id'] = $event_id; $output['start'] = $event['start_time']; $output['end_time'] = $event['end_time']; if ($event['end_time'] - $event['start_time'] > 60 * 60 * 8) { $output['allDay'] = TRUE; } else { $output['allDay'] = FALSE; } $output['bg'] = $event['bg']; $output['tx'] = $event['tx']; if ($type != "private") { cmsActions::log('add_event', array('object' => 'событие', 'object_url' => '/calendar/event' . $event_id . '.html', 'object_id' => $event_id, 'target' => $title, 'target_url' => '/calendar/event' . $event_id . '.html', 'target_id' => '0', 'description' => $title)); } } } else { $output['error'] = TRUE; $output['errortext'] = iconv("CP1251", "UTF-8", "Ошибка доступа"); } print json_encode($output); exit; } if ($do == "ajax_edit") { $type_act = $inCore->request('type', 'str'); $id = $inCore->request('id', 'int'); $dayDelta = $inCore->request('dayDelta', 'str'); $minuteDelta = $inCore->request('minuteDelta', 'str'); $event = $model->getEvent($id); if ($event['author_id'] == $inUser->id) { $type = $event['type']; $apx = ""; $start_time = $event['start_time']; $end_time = $event['end_time']; $title = $event['title']; $content = $event['content']; $delta = $dayDelta * 24 * 60 * 60 + $minuteDelta * 60; if ($type_act == "drop") { $start_time = $start_time + $delta; $end_time = $end_time + $delta; } if ($type_act == "resize") { $end_time = $end_time + $delta; } $model->updateEvent($id, $type, $apx, $start_time, $end_time, $title, $content); } else { print "Ошибка доступа"; } exit; } if ($do == "ajax_get_event") { $starttime = $inCore->request('start', 'int'); $endtime = $inCore->request('end', 'int'); $parent_id = $inCore->request('parent_id', 'parent_id'); $category = $inCore->request('category', 'str'); if ($category == "all" or !is_numeric($category)) { $category = FALSE; } if (!$parent_id) { $parent_id = 0; } $events = $model->getCalendar($starttime, $endtime, $category, $parent_id); $output = array(); foreach ($events as $data) { $data['title'] = iconv("cp1251", "utf8", $data["title"]); $data['start'] = date("Y-m-d H:i:s", $data["start_time"]); $data['end'] = date("Y-m-d H:i:s", $data["end_time"]); $data['url'] = "/calendar/event" . $data['id'] . ".html"; if ($data["author_id"] == $inUser->id) { $data['editable'] = true; } else { $data['editable'] = false; } if ($data["end_time"] - $data["start_time"] > 60 * 60 * 8) { $data['allDay'] = "true"; } if (!$data['category_id']) { switch ($data["type"]) { case "public": $data['color'] = $cfg['public_bg_color']; $data['textColor'] = $cfg['public_tx_color']; break; case "private": $data['color'] = $cfg['private_bg_color']; $data['textColor'] = $cfg['private_tx_color']; break; } } else { $data['color'] = $data['bg']; $data['textColor'] = $data['tx']; } if ($data["type"] == "private" and $data['author_id'] != $inUser->id) { } else { $output[] = $data; } } print json_encode($output); exit; } if ($do == "isc_calendar") { header('Content-type: text/calendar; charset=utf-8'); header('Content-Disposition: inline; filename=calendar.ics'); echo "BEGIN:VCALENDAR\n"; echo "VERSION:2.0\n"; echo "PRODID:-//hacksw/handcal//NONSGML v1.0//EN'\n"; $events = $model->getCalendar(time() - 60 * 60 * 24 * 30, time() + 60 * 60 * 24 * 30, 0); foreach ($events as $event) { if ($event['type'] == "public") { $title = iconv("cp1251", "utf8", $event["title"]); //$content = iconv("cp1251","utf8",str_replace("\n",'',$event["content"])); $dtstart = date("Ymd", $event["start_time"]) . "T" . date("His", $event["start_time"]) . "Z"; $dtend = date("Ymd", $event["end_time"]) . "T" . date("His", $event["end_time"]) . "Z"; echo "BEGIN:VEVENT\n"; echo "DTSTART:{$dtstart}\n"; echo "DTEND:{$dtend}\n"; echo "SUMMARY:{$title}\n"; //echo "DESCRIPTION:$content\n"; echo "END:VEVENT\n"; } } echo "END:VCALENDAR\n"; exit; } if ($do == "ajax_add_form") { $start = strtotime($inCore->request('start', 'str')); $end = strtotime($inCore->request('end', 'str')); if (!$inUser->id) { print "Ошибка доступа."; exit; } $catigories = $model->getAllCategories(); $bb_toolbar = cmsPage::getBBCodeToolbar('message', $cfg['img_on'], 'forum'); $smilies = cmsPage::getSmilesPanel('message'); $smarty = $inCore->initSmarty('components', 'com_calendar_add.tpl'); $smarty->assign('catigories', $catigories); $smarty->assign('start_date', date("d.m.Y", $start)); $smarty->assign('start_hour', date("H", $start)); $smarty->assign('start_min', date("i", $start)); $smarty->assign('end_date', date("d.m.Y", $end)); $smarty->assign('end_hour', date("H", $end)); $smarty->assign('end_min', date("i", $end)); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->display('com_calendar_add.tpl'); exit; } // FOTOLIB if ($do == "imagerotate") { $side = $md5 = $inCore->request('side', 'str'); $image_id = $inCore->request('image_id', 'int'); include 'fotolib.class.php'; $foto = new FotoLib(); $foto->Rotate($side, $image_id); $inCore->redirectBack(); exit; } if ($do == "imagedelete") { include 'fotolib.class.php'; $image_id = $inCore->request('image_id', 'int'); $foto = new FotoLib(); $foto->Delete($image_id); $inCore->redirectBack(); exit; } }
function battleways() { $inCore = cmsCore::getInstance(); $inPage = cmsPage::getInstance(); $inDB = cmsDatabase::getInstance(); $inUser = cmsUser::getInstance(); global $_LANG; $inCore->loadModel('battleways'); $model = new cms_model_battleways(); $usr = cmsCore::request('id', 'int', 0); $cfg = $inCore->loadComponentConfig('battleways'); // Проверяем включени ли компонент if (!$cfg['component_enabled']) { cmsCore::error404(); } $id = $inCore->request('id', 'int', 0); $do = $inCore->request('do', 'str', 'view'); $tag = $inCore->request('tag', 'str', ''); $color = $inCore->request('color', 'str', ''); $page = $inCore->request('page', 'int', 1); $select_tag = 0; $t = urldecode($tag); if (!empty($t)) { $sql = "SELECT * \nFROM `cms_battleways` \nWHERE `type` LIKE '%" . $t . "%'"; if ($inDB->query($sql)) { $select_tag = 1; } } if (!isset($cfg['perpage'])) { $cfg['perpage'] = 10; } if (!isset($cfg['images'])) { $cfg['images'] = 0; } if ($_SESSION['user']['id'] == 0) { echo "Гостям запрещено просматривать данный раздел"; } else { if ($do == 'view_battleway') { //if($model->authorBattleway($id)) //{ $battleway = $model->getBattleway($id); $smarty = $inCore->initSmarty('components', 'com_battleways_view.tpl'); $smarty->assign('is_posts_view', (bool) sizeof($battleway)); $smarty->assign('pagetitle', $battleway['title']); $smarty->assign('content', $battleway['content']); $smarty->display('com_battleways_view.tpl'); // } // else // { // cmsCore::error404(); // } } if ($do == 'del') { $del = $model->delBattleway($id); $inCore->redirect('/battleways/'); } if ($do == 'view') { if ($select_tag == 0) { $total_battleways = $model->totalPosts(); $pagination = cmsPage::getPagebar($total_battleways, $page, $cfg['perpage'], '/battleways/page%page%.html'); } $user_id = $inUser->id; //GET ENTRIES $posts_list = $model->getAllPosts($page, $cfg['perpage'], $select_tag, $t, $color, $user_id); if ($posts_list) { foreach ($posts_list as $post) { $post['datetime'] = $inCore->dateFormat($post['datetime'], 1, 0, 1); /* if(!empty($post['type'])) { $sql="select * from `cms_battleways_color` where `id`='".$post['color']."';"; $result = $inDB->query($sql); if ($inDB->num_rows($result)){ $color = $inDB->fetch_assoc($result); $post['status'] = "<a href='/battleways/".$post['type']."/".$post['color']."/' style='background: ".$color['color'].";border-radius: 3px;color: ".$color['font_color'].";display: inline-block;height: 19px;margin: 5px 3px 2px 2px;outline: #FFFFFF 0px;padding: 1px 4px;text-decoration: none;text-indent: 0px;vertical-align: middle;white-space: nowrap;'>".$post['type']."</a>"; } else { $post['status'] = "<a href='/battleways/".$post['type']."/' style='background: #E6E6E6;border:1px solid #e1e1e1;padding:5px;border-radius: 8px;border-radius: 3px;color:#333333;text-shadow: #FFFFFF 1px 1px 0px;display: inline-block;height: 19px;margin: 5px 3px 2px 2px;outline: #FFFFFF 0px;padding: 1px 4px;text-decoration: none;text-indent: 0px;vertical-align: middle;white-space: nowrap;cursor:pointer;'>".$post['type']."</a>"; } } */ $posts[] = $post; } } $smarty = $inCore->initSmarty('components', 'com_battleways_view.tpl'); $smarty->assign('is_posts', (bool) sizeof($posts_list)); if ($select_tag == 0) { $smarty->assign('pagination', $pagination); } $smarty->assign('mark', $model->getMarks()); $smarty->assign('pagetitle', "Ваши минизаписки"); if ($posts) { $smarty->assign('posts', $posts); } $smarty->display('com_battleways_view.tpl'); } if ($do == 'add_battleway') { $user_id = $inUser->id; $title = $inCore->request('title', 'str', ''); $type = $inCore->request('type', 'str', ''); $color = $inCore->request('color', 'int', ''); if (!empty($title)) { $describe_full = $inCore->request('full', 'html', ''); //парсим bb-код перед записью в базу $describe_full_html = $inCore->parseSmiles($describe_full, true); // Экранируем специальные символы $describe_full_html = $inDB->escape_string($describe_full_html); $sql = "INSERT INTO `cms_battleways` (\n`id` ,\n`datetime` ,\n`title` ,\n`content` ,\n`user` ,\n`type` ,\n`color` \n)\nVALUES (\nNULL , NOW(), '" . $title . "', '" . $describe_full_html . "', '" . $user_id . "', '" . $type . "', '" . $color . "'\n);"; $result = $inDB->query($sql); $inCore->redirect('/battleways/'); } $inPage->addHeadJS('components/battleways/js/battleways.js'); $bb_toolbar = cmsPage::getBBCodeToolbar('message', $cfg['images'], 'battleways'); $smilies = cmsPage::getSmilesPanel('message'); $smarty = $inCore->initSmarty('components', 'com_battleways_add.tpl'); $smarty->assign('mark_insert', $model->getAutoMark()); $smarty->assign('select_color', $model->getColors()); $smarty->assign('title', "Добавление записки"); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->display('com_battleways_add.tpl'); } if ($do == 'edit_battleway') { $battleway = $model->getBattleway($id); $smarty = $inCore->initSmarty('components', 'com_battleways_edit.tpl'); $smarty->assign('is_posts_view', (bool) sizeof($battleway)); $smarty->assign('pagetitle', $battleway['title']); $smarty->assign('content', $battleway['content']); $user_id = $inUser->id; $title = $inCore->request('title', 'str', ''); $type = $inCore->request('type', 'str', ''); $color = $inCore->request('color', 'int', ''); if (!empty($title)) { $describe_full = $inCore->request('full', 'html', ''); //парсим bb-код перед записью в базу $describe_full_html = $inCore->parseSmiles($describe_full, true); // Экранируем специальные символы $describe_full_html = $inDB->escape_string($describe_full_html); $sql = "INSERT INTO `cms_battleways` (\n\t\t\t\t\t`id` ,\n\t\t\t\t\t`datetime` ,\n\t\t\t\t\t`title` ,\n\t\t\t\t\t`content` ,\n\t\t\t\t\t`user` ,\n\t\t\t\t\t`type` ,\n\t\t\t\t\t`color` \n\t\t\t\t\t)\n\t\t\t\t\tVALUES (\n\t\t\t\t\tNULL , NOW(), '" . $title . "', '" . $describe_full_html . "', '" . $user_id . "', '" . $type . "', '" . $color . "'\n\t\t\t\t\t);"; $result = $inDB->query($sql); $inCore->redirect('/battleways/'); } $inPage->addHeadJS('components/battleways/js/battleways.js'); $bb_toolbar = cmsPage::getBBCodeToolbar('message', $cfg['images'], 'battleways'); $smilies = cmsPage::getSmilesPanel('message'); $smarty = $inCore->initSmarty('components', 'com_battleways_edit.tpl'); $smarty->assign('mark_insert', $model->getAutoMark()); $smarty->assign('select_color', $model->getColors()); $smarty->assign('title', "Добавление записки"); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->display('com_battleways_edit.tpl'); } } ///////////////////////////////////////////////// }
function clubs() { $inCore = cmsCore::getInstance(); $inPage = cmsPage::getInstance(); $inDB = cmsDatabase::getInstance(); $inUser = cmsUser::getInstance(); global $_LANG; $model = new cms_model_clubs(); $inPhoto = $model->initPhoto(); define('IS_BILLING', $inCore->isComponentInstalled('billing')); if (IS_BILLING) { cmsCore::loadClass('billing'); } // js только авторизованным if($inUser->id){ $inPage->addHeadJS('components/clubs/js/clubs.js'); } $pagetitle = $inCore->getComponentTitle(); $id = cmsCore::request('id', 'int', 0); $do = $inCore->do; $page = cmsCore::request('page', 'int', 1); $inPage->setTitle($pagetitle); $inPage->setDescription($model->config['meta_desc'] ? $model->config['meta_desc'] : $pagetitle); $inPage->setKeywords($model->config['meta_keys'] ? $model->config['meta_keys'] : $pagetitle); $inPage->addPathway($pagetitle, '/clubs'); $inPage->addHeadJsLang(array('NO_PUBLISH','EDIT_PHOTO','YOU_REALLY_DELETE_PHOTO','YOU_REALLY_DELETE_ALBUM','RENAME_ALBUM','ALBUM_TITLE','ADD_PHOTOALBUM','REALY_EXIT_FROM_CLUB','JOINING_CLUB','SEND_MESSAGE','CREATE','CREATE_CLUB','SEND_INVITE_CLUB','YOU_NO_SELECT_USER')); //////////////////////// КЛУБЫ ПОЛЬЗОВАТЕЛЯ///////////////////////////////////// if ($do == 'user_clubs') { if (!cmsCore::isAjax()) { return false; } $inPage->displayLangJS(array('CREATE','CREATE_CLUB')); $user_id = cmsCore::request('user_id', 'int', $inUser->id); $user = cmsUser::getShortUserData($user_id); if (!$user) { return false; } // получаем клубы, в которых пользователь админ $model->whereAdminIs($user['id']); $inDB->orderBy('c.pubdate', 'DESC'); $clubs = $model->getClubs(); // получаем клубы, в которых состоит пользователь $inDB->addSelect('uc.role'); $inDB->addJoin("INNER JOIN cms_user_clubs uc ON uc.club_id = c.id AND uc.user_id = '{$user['id']}'"); $inDB->orderBy('uc.role', 'DESC, uc.pubdate DESC'); $inclubs = $model->getClubs(); cmsPage::initTemplate('components', 'com_clubs_user')-> assign('can_create', (($inUser->id == $user['id']) && ($model->config['cancreate'] || $inUser->is_admin)))-> assign('clubs', array_merge($clubs, $inclubs))-> assign('user', $user)-> assign('my_profile', $user['id'] == $inUser->id)-> display(); } //////////////////////// ВСЕ КЛУБЫ ///////////////////////////////////////////// if ($do=='view'){ $inDB->orderBy('is_vip', 'DESC, rating DESC'); $inDB->limitPage($page, $model->config['perpage']); $total = $model->getClubsCount(); $clubs = $model->getClubs(); if (!$clubs && $page > 1) { return false; } if ($page > 1) { foreach ($clubs as $c) { $keys[] = $c['title']; } $inPage->setKeywords(implode(',', $keys)); } cmsPage::initTemplate('components', 'com_clubs_view')-> assign('pagetitle', $pagetitle)-> assign('can_create', ($inUser->id && $model->config['cancreate'] || $inUser->is_admin))-> assign('clubs', $clubs)-> assign('total', $total)-> assign('pagination', cmsPage::getPagebar($total, $page, $model->config['perpage'], '/clubs/page-%page%'))-> display(); } /////////////////////// ПРОСМОТР КЛУБА ///////////////////////////////////////// if ($do=='club'){ $club = $model->getClub($id); if (!$club) { return false; } if (!$club['published'] && !$inUser->is_admin) { return false; } $inPage->setTitle($club['pagetitle'] ? $club['pagetitle'] : $club['title']); $inPage->setKeywords($club['meta_keys'] ? $club['meta_keys'] : $club['title']); if (!$club['meta_desc']) { if ($club['description']) { $inPage->setDescription(crop($club['description'])); } else { $inPage->setDescription($club['title']); } } else { $inPage->setDescription($club['meta_desc']); } $inPage->addPathway($club['title']); $inPage->addHeadJsLang(array('NEW_POST_ON_WALL','CONFIRM_DEL_POST_ON_WALL')); // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); $is_member = $model->checkUserRightsInClub('member'); // Приватный или публичный клуб $is_access = true; if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){ $is_access = false; } // Общее количество участников $club['members'] = $model->club_total_members; // Общее количество участников $club['moderators'] = $model->club_total_moderators; // Массив членов клуба if($club['members']){ $inDB->limit($model->config['club_perpage']); $club['members_list'] = $model->getClubMembers($club['id'], 'member'); } else { $club['members_list'] = array(); } // Массив модераторов клуба if($club['moderators']){ $club['moderators_list'] = $model->getClubMembers($club['id'], 'moderator'); } // Стена клуба // количество записей на стене берем из настроек $inDB->limitPage(1, $model->config['wall_perpage']); $club['wall_html'] = cmsUser::getUserWall($club['id'], 'clubs', ($is_moder || $is_admin), ($is_moder || $is_admin)); ///////////////////////////////////////////// //////////// ПОСТЫ БЛОГА КЛУБА ////////////// ///////////////////////////////////////////// if ($club['enabled_blogs']){ $inBlog = $model->initBlog(); $inBlog->whereBlogUserIs($club['id']); $club['total_posts'] = $inBlog->getPostsCount($is_admin || $is_moder); $inDB->addSelect('b.user_id as bloglink'); $inDB->orderBy('p.pubdate', 'DESC'); $inDB->limit($model->config['club_posts_perpage']); $club['blog_posts'] = $inBlog->getPosts(($is_admin || $is_moder), $model, true); } ///////////////////////////////////////////// //////////// ФОТОАЛЬБОМЫ КЛУБА ////////////// ///////////////////////////////////////////// if ($club['enabled_photos']){ // Общее количество альбомов $club['all_albums'] = $inDB->rows_count('cms_photo_albums', "NSDiffer = 'club{$club['id']}' AND user_id = '{$club['id']}' AND parent_id > 0"); // получаем альбомы if($club['all_albums']){ $inDB->limit($model->config['club_album_perpage']); $inDB->orderBy('f.pubdate', 'DESC'); $club['photo_albums'] = $inPhoto->getAlbums(0, 'club'.$club['id']); } else { $club['photo_albums'] = array(); } } // Получаем плагины $plugins = cmsCore::callTabEventPlugins('GET_SINGLE_CLUB', $club); cmsPage::initTemplate('components', 'com_clubs_view_club')-> assign('club', $club)-> assign('is_access', $is_access)-> assign('user_id', $inUser->id)-> assign('is_admin', $is_admin)-> assign('is_moder', $is_moder)-> assign('plugins', $plugins)-> assign('is_member', $is_member)-> assign('is_photo_karma_enabled', ((($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false))-> assign('is_blog_karma_enabled', ((($inUser->karma >= $club['blog_min_karma']) && $is_member) ? true : false))-> assign('cfg', $model->config)-> display(); } ///////////////////////// СОЗДАНИЕ КЛУБА /////////////////////////////////////// if ($do == 'create'){ if(!cmsCore::isAjax()) { return false; } if(!$inUser->id){ return false; } $can_create = $model->canCreate(); // показываем форму if (!cmsCore::inRequest('create') ){ cmsPage::initTemplate('components', 'com_clubs_create')-> assign('can_create', $can_create)-> assign('last_message', $model->last_message)-> display(); cmsCore::jsonOutput(array('error' => false, 'can_create' => (bool)$can_create, 'html' => ob_get_clean())); } if (cmsCore::inRequest('create')){ if (!$can_create){ return false; } $title = $inCore->request('title', 'str'); $clubtype = $inCore->request('clubtype', 'str'); if (!$title || !in_array($clubtype, array('public','private'))){ cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CLUB_REQ_TITLE'])); } if ($inDB->get_field('cms_clubs', "LOWER(title) = '".mb_strtolower($title)."'", 'id')){ cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CLUB_EXISTS'])); } if(!cmsUser::checkCsrfToken()) { return false; } $club_id = $model->addClub(array('admin_id'=>$inUser->id, 'title'=>$title, 'clubtype'=>$clubtype, 'create_karma'=>$inUser->karma, 'enabled_blogs'=>$model->config['enabled_blogs'], 'enabled_photos'=>$model->config['enabled_photos'])); if($club_id){ //регистрируем событие cmsActions::log('add_club', array( 'object' => $title, 'object_url' => '/clubs/'.$club_id, 'object_id' => $club_id, 'target' => '', 'target_url' => '', 'target_id' => 0, 'description' => '' )); } cmsCore::addSessionMessage($_LANG['CLUB_IS_CREATED'], 'success'); cmsCore::jsonOutput(array('error' => false, 'club_id' => $club_id)); } } ///////////////////////// НАСТРОЙКИ КЛУБА ////////////////////////////////////// if ($do == 'config'){ if (!$inUser->id){ return false; } $club = $model->getClub($id); if (!$club){ return false; } // Инициализируем участников клуба $model->initClubMembers($club['id']); // настраивать клуб могут только администраторы $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); if (!$is_admin){ return false; } if (cmsCore::inRequest('save')){ if (!cmsUser::checkCsrfToken()) { return false; } $description = cmsCore::badTagClear(cmsCore::request('description', 'html', '')); $new_club['description'] = $inDB->escape_string($description); $new_club['title'] = cmsCore::request('title', 'str', $club['title']); $new_club['clubtype'] = cmsCore::request('clubtype', 'str', 'public'); $new_club['maxsize'] = cmsCore::request('maxsize', 'int', 0); $new_club['blog_min_karma'] = cmsCore::request('blog_min_karma', 'int', 0); $new_club['photo_min_karma'] = cmsCore::request('photo_min_karma', 'int', 0); $new_club['album_min_karma'] = cmsCore::request('album_min_karma', 'int', 0); $new_club['blog_premod'] = cmsCore::request('blog_premod', 'int', 0); $new_club['photo_premod'] = cmsCore::request('photo_premod', 'int', 0); $new_club['join_karma_limit'] = cmsCore::request('join_karma_limit', 'int', 0); $new_club['join_min_karma'] = cmsCore::request('join_min_karma', 'int', 0); if ($model->config['seo_user_access'] || $inUser->is_admin) { $new_club['pagetitle'] = cmsCore::request('pagetitle', 'str', ''); $new_club['meta_keys'] = cmsCore::request('meta_keys', 'str', ''); $new_club['meta_desc'] = cmsCore::request('meta_desc', 'str', ''); } // загружаем изображение клуба $new_imageurl = $model->uploadClubImage($club['imageurl']); $new_club['imageurl'] = @$new_imageurl['filename'] ? $new_imageurl['filename'] : $club['imageurl']; // Сохраняем $model->updateClub($club['id'], $new_club); // Обновляем ленту активности cmsActions::updateLog('add_club', array('object' => $new_club['title']), $club['id']); cmsActions::updateLog('add_club_user', array('object' => $new_club['title']), $club['id']); if ($inUser->is_admin && IS_BILLING){ $is_vip = cmsCore::request('is_vip', 'int', 0); $join_cost = cmsCore::request('join_cost', 'int', 0); $model->setVip($club['id'], $is_vip, $join_cost); } $moders = cmsCore::request('moderslist', 'array_int', array()); $members = cmsCore::request('memberslist', 'array_int', array()); $all_users = array_merge($members, $moders); // Сохраняем пользователей $model->clubSaveUsers($club['id'], $all_users); $model->clubSetRole($club['id'], $moders, 'moderator'); // Кешируем количество $model->setClubMembersCount($club['id']); cmsCore::addSessionMessage($_LANG['CONFIG_SAVE_OK'], 'info'); cmsCore::redirect('/clubs/'.$club['id']); } if (!cmsCore::inRequest('save')){ // Заголовки и пафвей $inPage->addPathway($club['title'], '/clubs/'.$club['id']); $inPage->addPathway($_LANG['CONFIG_CLUB']); $inPage->setTitle($_LANG['CONFIG_CLUB']); // Список друзей, отсутствующих в клубе $friends_list = ''; // массив id друзей не в клубе $friends_ids = array(); // Получаем список друзей $friends = cmsUser::getFriends($inUser->id); // Получаем список участников $members = $model->getClubMembersIds(); // Формируем список друзей, которые еще не в клубе foreach($friends as $key=>$friend){ if (!in_array($friend['id'], $members) && $friend['id'] != $club['admin_id']){ $friends_list .= '<option value="'.$friend['id'].'">'.$friend['nickname'].'</option>'; $friends_ids[] = $friend['id']; } } // Получаем модераторов клуба $moderators = $model->getClubMembersIds('moderator'); // формируем список друзья не в клубе + участники клуба кроме модераторов $fr_plus_members = $members ? array_merge($friends_ids, $members) : $friends_ids; // Убираем модераторов если они есть $fr_plus_members = $moderators ? array_diff($fr_plus_members, $moderators) : $fr_plus_members; // Формируем список option друзей (которые еще не в этом клубе) и участников if ($fr_plus_members) { $fr_members_list = cmsUser::getAuthorsList($fr_plus_members); } else { $fr_members_list = ''; } // Формируем список option участников клуба if ($moderators) { $moders_list = cmsUser::getAuthorsList($moderators); } else { $moders_list = ''; } if ($members) { $members_list = cmsUser::getAuthorsList($members); } else { $members_list = ''; } cmsPage::initTemplate('components', 'com_clubs_config')-> assign('club', $club)-> assign('moders_list', $moders_list)-> assign('members_list', $members_list)-> assign('friends_list', $friends_list)-> assign('fr_members_list', $fr_members_list)-> assign('is_billing', IS_BILLING)-> assign('is_admin', $inUser->is_admin)-> assign('cfg', $model->config)-> display(); } } ///////////////////////// ВЫХОД ИЗ КЛУБА /////////////////////////////////////////// if ($do == 'leave'){ if(!$inUser->id) { return false; } if(!cmsCore::isAjax()) { return false; } $club = $model->getClub($id); if(!$club){ cmsCore::halt(); } // Инициализируем участников клуба $model->initClubMembers($club['id']); // Выйти из клуба могут только его участники $is_admin = $inUser->id == $club['admin_id']; $is_member = $model->checkUserRightsInClub(); if ($is_admin || !$is_member){ cmsCore::halt(); } if (cmsCore::inRequest('confirm')){ if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); } cmsCore::callEvent('LEAVE_CLUB', $club); $model->removeUserFromClub($club['id'], $inUser->id); // Пересчитываем рейтинг $model->setClubRating($club['id']); // Кешируем (пересчитываем) количество участников $model->setClubMembersCount($club['id']); // Добавляем событие в ленте активности cmsActions::removeObjectLog('add_club_user', $club['id'], $inUser->id); cmsCore::addSessionMessage($_LANG['YOU_LEAVE_CLUB'].'"'.$club['title'].'"', 'success'); cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/'.$club['id'])); } } ///////////////////////// ВСТУПЛЕНИЕ В КЛУБ //////////////////////////////////// if ($do == 'join'){ if (!$inUser->id){ cmsCore::halt(); } $club = $model->getClub($id); if(!$club){ cmsCore::halt(); } // В приватный клуб участников добавляет администратор if ($club['clubtype']=='private'){ cmsCore::halt(); } // Инициализируем участников клуба $model->initClubMembers($club['id']); // проверяем наличие пользователя в клубе $is_admin = $inUser->id == $club['admin_id']; $is_member = $model->checkUserRightsInClub(); if ($is_admin || $is_member){ cmsCore::halt(); } // Проверяем ограничения на количество участников if ($club['maxsize'] && ($model->club_total_members >= $club['maxsize']) && !$inUser->is_admin){ cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CLUB_SIZE_LIMIT'])); } // Проверяем ограничения по карме на вступление if($club['join_karma_limit'] && ($inUser->karma < $club['join_min_karma']) && !$inUser->is_admin){ cmsCore::jsonOutput(array('error' => true, 'text' => '<p><strong>'.$_LANG['NEED_KARMA_TEXT'].'</strong></p><p>'.$_LANG['NEEDED'].' '.$club['join_min_karma'].', '.$_LANG['HAVE_ONLY'].' '.$inUser->karma.'.</p><p>'.$_LANG['WANT_SEE'].' <a href="/users/'.$inUser->id.'/karma.html">'.$_LANG['HISTORY_YOUR_KARMA'].'</a>?</p>')); } // // Обработка заявки // if (cmsCore::inRequest('confirm')){ cmsCore::callEvent('JOIN_CLUB', $club); //списываем оплату если клуб платный if (IS_BILLING && $club['is_vip'] && $club['join_cost'] && !$inUser->is_admin){ if ($inUser->balance >= $club['join_cost']){ //если средств на балансе хватает cmsBilling::pay($inUser->id, $club['join_cost'], sprintf($_LANG['VIP_CLUB_BUY_JOIN'], $club['title'])); } else { //недостаточно средств, создаем тикет //и отправляем оплачивать $billing_ticket = array( 'action' => sprintf($_LANG['VIP_CLUB_BUY_JOIN'], $club['title']), 'cost' => $club['join_cost'], 'amount' => $club['join_cost'] - $inUser->balance, 'url' => $_SERVER['REQUEST_URI'].'?confirm=1' ); cmsUser::sessionPut('billing_ticket', $billing_ticket); cmsCore::jsonOutput(array('error' => false, 'redirect' => '/billing/pay')); } } //добавляем пользователя в клуб $model->addUserToClub($club['id'], $inUser->id); // Пересчитываем рейтинг клуба $model->setClubRating($club['id']); // Кешируем (пересчитываем) количество участников $model->setClubMembersCount($club['id']); //регистрируем событие cmsActions::log('add_club_user', array( 'object' => $club['title'], 'object_url' => '/clubs/'.$club['id'], 'object_id' => $club['id'], 'target' => '', 'target_url' => '', 'target_id' => 0, 'description' => '' )); cmsCore::addSessionMessage($_LANG['YOU_JOIN_CLUB'].'"'.$club['title'].'"', 'success'); if($_SERVER['REQUEST_URI'] != '/clubs/'.$club['id'].'/join.html'){ cmsCore::redirect('/clubs/'.$club['id']); } else { cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/'.$club['id'])); } } // // Форма подтверждения заявки // if (!cmsCore::inRequest('confirm')){ $text = '<p>'.$_LANG['YOU_REALY_JOIN_TO'].' <strong>"'.$club['title'].'"</strong>?</p>'; if ($club['is_vip'] && $club['join_cost'] && !$inUser->is_admin){ $text .= '<p>'.$_LANG['VIP_CLUB_JOIN_COST'].' — <strong>'.$club['join_cost'].' '.$_LANG['BILLING_POINT10'].'</strong></p>'; } cmsCore::jsonOutput(array('error' => false, 'text' => $text)); } } ///////////////////// РАССЫЛКА СООБЩЕНИЯ УЧАСТНИКАМ //////////////////////////// if ($do == 'send_message'){ if(!$inUser->id) { return false; } if(!cmsCore::isAjax()) { return false; } $club = $model->getClub($id); if(!$club){ cmsCore::halt(); } // Инициализируем участников клуба $model->initClubMembers($club['id']); // Расылать могут только участники и администраторы $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); if (!$is_admin){ cmsCore::halt(); } if (!cmsCore::inRequest('gosend')){ $inPage->setRequestIsAjax(); cmsPage::initTemplate('components', 'com_clubs_messages_member')-> assign('club', $club)-> assign('bbcodetoolbar', cmsPage::getBBCodeToolbar('message'))-> assign('smilestoolbar', cmsPage::getSmilesPanel('message'))-> display(); cmsCore::jsonOutput(array('error' => false,'html' => ob_get_clean())); } else { // Здесь не эскейпим, в методе sendMessage эскейпится $message = cmsCore::parseSmiles(cmsCore::request('content', 'html', ''), true); $moderators_list = $model->getClubMembersIds('moderator'); $members_list = $model->getClubMembersIds(); $result_list = cmsCore::inRequest('only_mod') ? $moderators_list : $members_list; if (mb_strlen($message)<3){ cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_SEND_MESS'])); } if (!$result_list){ cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_SEND_MESS_NO_MEMBERS'])); } if (!cmsUser::checkCsrfToken()) { return false; } $message = str_replace('%club%', '<a href="/clubs/'.$club['id'].'">'.$club['title'].'</a>', $_LANG['MESSAGE_FROM ADMIN']).$message; cmsUser::sendMessages(USER_UPDATER, $result_list, $message); $info = cmsCore::inRequest('only_mod') ? $_LANG['SEND_MESS_TO_MODERS_OK'] : $_LANG['SEND_MESS_TO_MEMBERS_OK']; cmsCore::jsonOutput(array('error' => false, 'text' => $info)); } } ///////////////////////// ПРИГЛАСИТЬ ДРУЗЕЙ В КЛУБ ///////////////////////////// if ($do == 'join_member'){ if (!$inUser->id) { return false; } if (!cmsCore::isAjax()) { return false; } $club = $model->getClub($id); if(!$club){ cmsCore::halt(); } if (!$club['published'] && !$inUser->is_admin) { cmsCore::halt(); } // Инициализируем участников клуба $model->initClubMembers($club['id']); // Расылать могут только участники и администраторы $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_member = $model->checkUserRightsInClub(); if (!$is_admin && !$is_member){ cmsCore::halt(); } // В приватный клуб приглашения не рассылаем if ($club['clubtype']=='private'){ cmsCore::halt(); } // Получаем список друзей $friends = cmsUser::getFriends($inUser->id); // Получаем список участников $members = $model->getClubMembersIds(); // Проверяем наличие друга в списке участников клуба или является ли он администратором foreach($friends as $key=>$friend){ if (in_array($friend['id'], $members) || $friend['id'] == $club['admin_id']) { unset($friends[$key]); } } // Если нет друзей или все друзья уже в этом клубе, то выводим ошибку и возвращаемся назад if (!$friends){ cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['SEND_INVITE_ERROR'])); } // показываем форму для приглашения if (!cmsCore::inRequest('join')){ // Выводим шаблон cmsPage::initTemplate('components', 'com_clubs_join_member')-> assign('club', $club)-> assign('friends', $friends)-> display(); cmsCore::jsonOutput(array('error' => false,'html' => ob_get_clean())); } else { // Приглашаем $users = cmsCore::request('users', 'array_int', array()); if ($users){ $club_link = '<a href="/clubs/'.$club['id'].'">'.$club['title'].'</a>'; $user_link = cmsUser::getProfileLink($inUser->login, $inUser->nickname); $link_join = '<a href="/clubs/'.$club['id'].'">'.$_LANG['JOIN_CLUB'] .'</a>'; $message = str_replace(array('%user%','%club%','%link_join%'), array($user_link,$club_link,$link_join), $_LANG['INVITE_CLUB_TEXT']); cmsUser::sendMessages(USER_UPDATER, $users, $message); } cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['SEND_INVITE_OK'])); } } ///////////////////////// ПРОСМОТР УЧАСТНИКОВ ////////////////////////////////// if ($do=='members'){ $club = $model->getClub($id); if(!$club){ return false; } if (!$club['published'] && !$inUser->is_admin) { return false; } $inPage->setTitle($_LANG['CLUB_MEMBERS'].' - '.$club['title']); $inPage->setDescription($_LANG['CLUB_MEMBERS'].' - '.$club['title']); $inPage->addPathway($club['title'], '/clubs/'.$club['id']); $inPage->addPathway($_LANG['CLUB_MEMBERS'].' - '.$club['title']); // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); $is_member = $model->checkUserRightsInClub(); // Приватный или публичный клуб if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){ return false; } // Общее количество участников $total_members = $model->club_total_members; // Массив членов клуба if($total_members){ $inDB->limitPage($page, $model->config['member_perpage']); $members = $model->getClubMembers($club['id']); if(!$members) { return false; } } else { return false; } $pagebar = cmsPage::getPagebar($total_members, $page, $model->config['member_perpage'], '/clubs/%id%/members-%page%', array('id'=>$club['id'])); cmsPage::initTemplate('components', 'com_clubs_view_member')-> assign('pagebar', $pagebar)-> assign('page', $page)-> assign('members', $members)-> assign('club', $club)-> assign('total_members', $total_members)-> display(); } ////////////////////////////// ВСЕ АЛЬБОМЫ КЛУБА ////////////////////////////// if ($do=='view_albums'){ $club = $model->getClub($id); if(!$club){ return false; } if (!$club['published'] && !$inUser->is_admin) { return false; } $pagetitle = $_LANG['PHOTOALBUMS'].' - '.$club['title']; $inPage->setTitle($pagetitle); $inPage->addPathway($club['title'], '/clubs/'.$club['id']); $inPage->addPathway($_LANG['PHOTOALBUMS']); // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); $is_member = $model->checkUserRightsInClub('member'); $is_karma_enabled = (($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false; // Приватный или публичный клуб if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){ return false; } $inDB->orderBy('f.pubdate', 'DESC'); $club['photo_albums'] = $inPhoto->getAlbums(0, 'club'.$club['id']); if(!$club['photo_albums']) { return false; } // SEO $inPage->setDescription($pagetitle); $keys = array($club['title'], $_LANG['PHOTOALBUMS']); foreach ($club['photo_albums'] as $p) { $keys[] = $p['title']; } $inPage->setKeywords(implode(',', $keys)); cmsPage::initTemplate('components', 'com_clubs_albums')-> assign('club', $club)-> assign('is_admin', $is_admin)-> assign('is_moder', $is_moder)-> assign('is_karma_enabled', $is_karma_enabled)-> assign('show_title', true)-> assign('pagetitle', $pagetitle)-> display(); } ///////////////////////// ПРОСМОТР АЛЬБОМА КЛУБА /////////////////////////////// if ($do=='view_album'){ // Получаем альбом $album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null); if (!$album) { return false; } // Неопубликованные альбомы показываем только админам if (!$album['published'] && !$inUser->is_admin) { return false; } if ($album['NSDiffer'] != 'club'. $album['user_id']) { return false; } // получаем клуб $club = $model->getClub($album['user_id']); if(!$club) { return false; } if (!$club['published'] && !$inUser->is_admin) { return false; } // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); $is_member = $model->checkUserRightsInClub(); // Приватный или публичный клуб if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){ return false; } $hidden = (bool)($is_admin || $is_moder); // Устанавливаем альбом $inPhoto->whereAlbumIs($album['id']); // Общее количество фото по заданным выше условиям $total = $inPhoto->getPhotosCount($hidden); //устанавливаем сортировку $inDB->orderBy('f.id', 'DESC'); //устанавливаем номер текущей страницы и кол-во фото на странице $inDB->limitPage($page, $model->config['photo_perpage']); $photos = $inPhoto->getPhotos($hidden); if (!$photos && $page > 1) { cmsCore::error404(); } $inPage->addPathway($club['title'], '/clubs/'.$club['id']); $inPage->addPathway($album['title'], '/clubs/photoalbum'.$album['id']); $inPage->setTitle($album['title']); $inPage->setDescription($album['title'].' - '.$_LANG['CLUB_PHOTO_ALBUM'].' "'.$club['title'].'"'); $keys = array($album['title'], $club['title']); if ($photos) { foreach ($photos as $p) { $keys[] = $p['title']; } } $inPage->setKeywords(implode(',', $keys)); cmsPage::initTemplate('components', 'com_clubs_view_album')-> assign('club', $club)-> assign('total', $total)-> assign('album', $album)-> assign('photos', $photos)-> assign('is_admin', $is_admin)-> assign('is_moder', $is_moder)-> assign('is_member', $is_member)-> assign('cfg', $model->config)-> assign('pagebar', cmsPage::getPagebar($total, $page, $model->config['photo_perpage'], '/clubs/photoalbum'.$album['id'].'/page-%page%'))-> display(); } ///////////////////////// УДАЛЕНИЕ АЛЬБОМА ///////////////////////////////////// if ($do=='delete_album'){ if(!$inUser->id) { return false; } if(!cmsCore::isAjax()) { return false; } if(!cmsUser::checkCsrfToken()) { return false; } $album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null); if (!$album) { cmsCore::halt(); } $club = $model->getClub($album['user_id']); if(!$club) { cmsCore::halt(); } $model->initClubMembers($club['id']); $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); if(!$is_admin && !$is_moder) { cmsCore::halt(); } $inPhoto->deleteAlbum($album['id'], 'club'.$club['id'], $model->initUploadClass()); cmsCore::addSessionMessage($_LANG['ALBUM_DELETED'], 'success'); cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/'.$club['id'])); } //////////////////////////////// ПРОСМОТР ФОТО ///////////////////////////////// if ($do=='view_photo'){ // Получаем фото $photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0)); if (!$photo) { return false; } $photo = cmsCore::callEvent('VIEW_CLUB_PHOTO', $photo); // получаем клуб $club = $model->getClub($photo['auser_id']); if(!$club) { return false; } if (!$club['published'] && !$inUser->is_admin) { return false; } // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); $is_member = $model->checkUserRightsInClub(); $is_author = $photo['user_id'] == $inUser->id; if (!$photo['published'] && !$is_admin && !$is_moder) { return false; } // Фото приватного клуба показываем только участникам if ($club['clubtype']=='private' && !$is_member && !$is_admin){ return false; } $inPage->addPathway($club['title'], '/clubs/'. $club['id']); $inPage->addPathway($photo['cat_title'], '/clubs/photoalbum'.$photo['album_id']); $inPage->addPathway($photo['title']); $inPage->setTitle($photo['pagetitle'] ? $photo['pagetitle'] : $photo['title']); $inPage->setKeywords($photo['meta_keys'] ? $photo['meta_keys'] : $photo['title']); if (!$photo['meta_desc']) { if ($photo['description']) { $inPage->setDescription(crop($photo['description'])); } else { $inPage->setDescription($photo['title']); } } else { $inPage->setDescription($photo['meta_desc']); } // ссылки вперед назад $photo['nextid'] = $inDB->get_fields('cms_photo_files', 'id<'.$photo['id'].' AND album_id = '.$photo['album_id'], 'id, file, title', 'id DESC'); $photo['previd'] = $inDB->get_fields('cms_photo_files', 'id>'.$photo['id'].' AND album_id = '.$photo['album_id'], 'id, file, title', 'id ASC'); // кнопки голосования $photo['karma_buttons'] = cmsKarmaButtons('club_photo', $photo['id'], $photo['rating'], $is_author); // Обновляем кол-во просмотров if(!$is_author){ $inDB->setFlag('cms_photo_files', $photo['id'], 'hits', $photo['hits']+1); } // выводим в шаблон cmsPage::initTemplate('components', 'com_clubs_view_photo')-> assign('club', $club)-> assign('photo', $photo)-> assign('is_admin', $is_admin)-> assign('is_moder', $is_moder)-> assign('is_exists_original', (file_exists(PATH.'/images/photos/'. $photo['file'])))-> assign('is_author', $is_author)-> display(); //если есть, выводим комментарии if ($photo['comments'] && $inCore->isComponentEnable('comments')) { cmsCore::includeComments(); comments('club_photo', $photo['id'], array(), $is_author); } } ////////////////////////////// УДАЛИТЬ ФОТО //////////////////////////////////// if ($do=='delete_photo'){ if(!$inUser->id) { return false; } if(!cmsCore::isAjax()) { return false; } if(!cmsUser::checkCsrfToken()) { return false; } $photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0)); if (!$photo) { cmsCore::halt(); } // получаем клуб $club = $model->getClub($photo['auser_id']); if(!$club) { cmsCore::halt(); } // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); // удалять могут только модераторы и администраторы if(!$is_admin && !$is_moder) { cmsCore::halt(); } $inPhoto->deletePhoto($photo, $model->initUploadClass()); cmsCore::addSessionMessage($_LANG['PHOTO_DELETED'], 'success'); cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/photoalbum'.$photo['album_id'])); } ///////////////////////// РЕДАКТИРОВАТЬ ФОТО /////////////////////////////////// if ($do=='edit_photo'){ if(!$inUser->id) { return false; } if(!cmsCore::isAjax()) { return false; } $photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0)); if (!$photo) { cmsCore::halt(); } // получаем клуб $club = $model->getClub($photo['auser_id']); if(!$club) { cmsCore::halt(); } if (!$club['published'] && !$inUser->is_admin) { return false; } // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); $is_author = $photo['user_id'] == $inUser->id; if(!$is_admin && !$is_moder && !$is_author) { cmsCore::halt(); } if (!cmsCore::inRequest('edit_photo')){ cmsPage::initTemplate('components', 'com_photos_edit')-> assign('photo', $photo)-> assign('form_action', '/clubs/editphoto'.$photo['id'].'.html')-> assign('no_tags', true)-> assign('is_admin', ($is_admin || $is_moder))-> display(); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } else { $mod['title'] = cmsCore::request('title', 'str', ''); $mod['title'] = $mod['title'] ? $mod['title'] : $photo['title']; $mod['description'] = cmsCore::request('description', 'str', ''); $mod['comments'] = ($is_admin || $is_moder) ? cmsCore::request('comments', 'int') : $photo['comments']; if ($model->config['seo_user_access'] || $inUser->is_admin) { $mod['pagetitle'] = cmsCore::request('pagetitle', 'str', ''); $mod['meta_keys'] = cmsCore::request('meta_keys', 'str', ''); $mod['meta_desc'] = cmsCore::request('meta_desc', 'str', ''); } $file = $model->initUploadClass()->uploadPhoto($photo['file']); $mod['file'] = $file['filename'] ? $file['filename'] : $photo['file']; $inPhoto->updatePhoto($mod, $photo['id']); $description = '<a href="/clubs/photo'.$photo['id'].'.html" class="act_photo"><img border="0" src="/images/photos/small/'.$mod['file'].'" /></a>'; cmsActions::updateLog('add_photo_club', array('object' => $mod['title'], 'description' => $description), $photo['id']); cmsCore::addSessionMessage($_LANG['PHOTO_SAVED'], 'success'); cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/photo'.$photo['id'].'.html')); } } /////////////////////////////// PHOTO PUBLISH ////////////////////////////////// if ($do=='publish_photo'){ if(!$inUser->id) { return false; } if(!cmsCore::isAjax()) { return false; } $photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0)); if (!$photo) { cmsCore::halt(); } // получаем клуб $club = $model->getClub($photo['auser_id']); if(!$club) { cmsCore::halt(); } if (!$club['published'] && !$inUser->is_admin) { return false; } // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); if(!$is_admin && !$is_moder) { cmsCore::halt(); } $inPhoto->publishPhoto($photo['id']); $description = $club['clubtype']=='private' ? '' : '<a href="/clubs/photo'.$photo['id'].'.html" class="act_photo"><img border="0" src="/images/photos/small/'.$photo['file'].'" /></a>'; cmsActions::log('add_photo_club', array( 'object' => $photo['title'], 'object_url' => '/clubs/photo'.$photo['id'].'.html', 'object_id' => $photo['id'], 'user_id' => $photo['user_id'], 'target' => $club['title'], 'target_id' => $photo['album_id'], 'target_url' => '/clubs/'.$club['id'], 'description' => $description )); cmsCore::halt('ok'); } ///////////////////////// ЗАГРУЗКА ФОТО //////////////////////////////////////// if ($do=='add_photo'){ // Неавторизованных просим авторизоваться if (!$inUser->id) { cmsUser::goToLogin(); } $do_photo = cmsCore::request('do_photo', 'str', 'addphoto'); $album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null); if (!$album) { return false; } if (!$album['published'] && !$inUser->is_admin) { return false; } $club = $model->getClub($album['user_id']); if(!$club) { return false; } // если фотоальбомы запрещены if(!$club['enabled_photos']){ return false; } // Инициализируем участников клуба $model->initClubMembers($club['id']); // права доступа $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']); $is_moder = $model->checkUserRightsInClub('moderator'); $is_member = $model->checkUserRightsInClub('member'); $is_karma_enabled = (($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false; if(!$is_karma_enabled && !$is_admin && !$is_moder) { cmsCore::addSessionMessage('<p><strong>'.$_LANG['NEED_KARMA_PHOTO'].'</strong></p><p>'.$_LANG['NEEDED'].' '.$club['photo_min_karma'].', '.$_LANG['HAVE_ONLY'].' '.$inUser->karma.'.</p><p>'.$_LANG['WANT_SEE'].' <a href="/users/'.$inUser->id.'/karma.html">'.$_LANG['HISTORY_YOUR_KARMA'].'</a>?</p>', 'error'); cmsCore::redirectBack(); } $inPage->addPathway($club['title'], '/clubs/'.$club['id']); $inPage->addPathway($album['title'], '/clubs/photoalbum'.$album['id']); return include 'components/clubs/add_photo.php'; } ///////////////////////// БЛОГИ КЛУБОВ ///////////////////////////////////////// if ($do == 'club_blogs') { $bdo = cmsCore::request('bdo', 'str', 'view_clubs_posts'); $post_id = cmsCore::request('post_id', 'int', 0); $cat_id = cmsCore::request('cat_id', 'int', 0); $seolink = cmsCore::request('seolink', 'str', ''); $on_moderate = cmsCore::request('on_moderate', 'int', 0); $inBlog = $model->initBlog(); $inPage->addHeadJsLang(array('NEW_CAT','RENAME_CAT','YOU_REALY_DELETE_CAT','YOU_REALY_DELETE_POST','NO_PUBLISHED')); return include 'components/clubs/club_blogs.php'; } }
$inPage->addHeadJS('includes/jquery/jquery.form.js'); /* ==================================================================================================== */ /* ==================================================================================================== */ if ($do == 'edit') { // получаем комментарий $comment = $model->getComment($comment_id); if (!$comment) { cmsCore::halt(); } $is_author = $comment['user_id'] == $inUser->id; // редактировать могут авторы (если время редактирования есть) // модераторы и администраторы if (!$model->is_can_moderate && !$inUser->is_admin && !($is_author && $comment['is_editable'])) { cmsCore::halt(); } // Для авторов показываем сколько осталось для редактирования if ($is_author && $comment['is_editable'] && !$inUser->is_admin && !$model->is_can_moderate) { $notice = str_replace('{min}', cmsCore::spellCount($comment['is_editable'], $_LANG['MINUTE1'], $_LANG['MINUTE2'], $_LANG['MINUTE10']), $_LANG['EDIT_INFO']); } } if ($model->is_can_bbcode) { $bb_toolbar = cmsPage::getBBCodeToolbar('content', true, 'comments', 'comment', $comment_id); $smilies = cmsPage::getSmilesPanel('content'); } /* ==================================================================================================== */ /* ==================================================================================================== */ $karma_need = $model->config['min_karma_add']; $can_by_karma = $model->config['min_karma'] && $inUser->karma >= $karma_need || $inUser->is_admin; $need_captcha = $model->config['regcap'] ? true : ($inUser->id ? false : true); cmsPage::initTemplate('components', 'com_comments_add')->assign('user_can_add', $model->is_can_add)->assign('is_can_bbcode', $model->is_can_bbcode)->assign('do', $do)->assign('comment', isset($comment) ? $comment : array())->assign('is_user', $inUser->id)->assign('cfg', $model->config)->assign('target', $target)->assign('target_id', $target_id)->assign('parent_id', $parent_id)->assign('user_subscribed', cmsUser::isSubscribed($inUser->id, $target, $target_id))->assign('can_by_karma', $can_by_karma)->assign('karma_need', $karma_need)->assign('karma_has', $inUser->karma)->assign('need_captcha', $need_captcha)->assign('bb_toolbar', isset($bb_toolbar) ? $bb_toolbar : '')->assign('smilies', isset($smilies) ? $smilies : '')->assign('notice', isset($notice) ? $notice : '')->display('com_comments_add.tpl'); cmsCore::halt();
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()); if ($component == 'blog_posts') { //получаем код панелей bbcode и смайлов $bb_toolbar = cmsPage::getBBCodeToolbar('message', true, 'blogs', 'blog_post', $item['id']); $smilies = cmsPage::getSmilesPanel('message'); $smarty->assign('smilies', $smilies); $smarty->assign('bb_toolbar', $bb_toolbar); } $smarty->display($template); $html = ob_get_clean(); cmsCore::jsonOutput(array('error' => false, 'html' => $html)); ?>
if ($bdo=='editpost'){ $inPage->addPathway($post['title'], $model->getPostURL($club['id'], $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', true, 'clubs', 'blog_post', $post_id); $smilies = cmsPage::getSmilesPanel('message'); $inCore->initAutoGrowText('#message'); //показываем форму cmsPage::initTemplate('components', 'com_blog_edit_post')-> assign('blog', $blog)-> assign('pagetitle', ($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', $inUser->is_admin)-> assign('myblog', ($is_admin || $is_moder))-> assign('user_can_iscomments', cmsUser::isUserCan('comments/iscomments'))->
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(); } }
} /* ==================================================================================================== */ /* ==================================================================================================== */ if($do == 'add'){ if (!$inUser->id) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ONLY_REG_USER_CAN_WALL'])); } if (!cmsCore::inRequest('submit')){ ob_start(); cmsPage::initTemplate('components', 'com_users_addwall')-> assign('target_id', $target_id)-> assign('component', $component)-> assign('bb_toolbar', cmsPage::getBBCodeToolbar('message', true, $component, 'wall'))-> assign('smilies', cmsPage::getSmilesPanel('message'))-> display(); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } $message = $inDB->escape_string(cmsCore::parseSmiles(cmsCore::request('message', 'html', ''), true)); if (mb_strlen($message)<2) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_SEND_WALL'])); } if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }
cmsCore::loadLanguage('components/users'); /* ==================================================================================================== */ /* ==================================================================================================== */ if ($do == 'view') { $inDB->limitPage($page, $cfg['wall_perpage']); echo cmsUser::getUserWall($target_id, $component, $my_profile, $is_admin); } /* ==================================================================================================== */ /* ==================================================================================================== */ if ($do == 'add') { if (!$inUser->id) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ONLY_REG_USER_CAN_WALL'])); } if (!cmsCore::inRequest('submit')) { ob_start(); cmsPage::initTemplate('components', 'com_users_addwall')->assign('target_id', $target_id)->assign('component', $component)->assign('bb_toolbar', cmsPage::getBBCodeToolbar('message', true, $component, 'wall'))->assign('smilies', cmsPage::getSmilesPanel('message'))->display('com_users_addwall.tpl'); cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean())); } $message = $inDB->escape_string(cmsCore::parseSmiles(cmsCore::request('message', 'html', ''), true)); if (mb_strlen($message) < 2) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_SEND_WALL'])); } if (!cmsUser::checkCsrfToken()) { cmsCore::halt(); } // добавляем запись методом модели места назначения $wall_id = $model->addWall(array('user_id' => $target_id, 'author_id' => $inUser->id, 'nickname' => $inUser->nickname, 'content' => $message, 'usertype' => $component, 'pubdate' => date('Y-m-d H:i:s'))); if ($wall_id) { // регистрируем загруженные фотографии к записи cmsCore::setIdUploadImage('wall', $wall_id); cmsCore::jsonOutput(array('error' => false, 'html' => $_LANG['WALL_MESG_ADD']));
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'] . ' — ' . $model->config['min_karma_private'] . ', ' . $_LANG['BLOG_HEAVING'] . ' — ' . $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'] . ' — ' . $model->config['min_karma_public'] . ', ' . $_LANG['BLOG_HEAVING'] . ' — ' . $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>«' . $post['title'] . '»</b> ' . $_LANG['WAS_DELETED_FROM_BLOG'] . ' <b>«<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>»</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>«<a href="' . $post['seolink'] . '">' . $post['title'] . '</a>»</b> ' . $_LANG['PUBLISHED_IN_BLOG'] . ' <b>«<a href="' . $model->getBlogURL() . '">' . $blog['title'] . '</a>»</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); }
function calendar() { $inCore = cmsCore::getInstance(); $inPage = cmsPage::getInstance(); $inUser = cmsUser::getInstance(); $inCore->loadModel('calendar'); $model = new cms_model_calendar(); $do = $inCore->request('do', 'str', 'view'); $cfg = $inCore->loadComponentConfig('calendar'); if ($do == 'view') { $inPage->setTitle("Календарь событий"); $inPage->addPathway("Календарь", "/calendar"); $smarty = $inPage->initTemplate('components', 'com_calendar_view.tpl'); $category_id = $inCore->request('category_id', 'int', 0); $can_add = FALSE; $moderated = TRUE; if ($cfg['group_' . $inUser->group_id]) { $can_add = TRUE; $moderated = FALSE; } elseif ($cfg['m_group_' . $inUser->group_id]) { $can_add = TRUE; $moderated = TRUE; } if ($inUser->is_admin) { $can_add = TRUE; } $catigories = $model->getAllCategories(); if ($category_id) { $category = $category_id; $cat = $model->getCategory($category); $inPage->addPathway($cat['name']); } else { $category = "all"; } if ($cfg['calendar_view'] == 'afisha') { $inCore->redirect('/calendar/list.html'); } $smarty->assign('can_add', $can_add); $smarty->assign('cfg', $cfg); $smarty->assign('catigories', $catigories); $smarty->assign('category', $category); $smarty->display('com_calendar_view.tpl'); return; } if ($do == "list") { $inPage->addPathway("Календарь", "/calendar"); $inPage->addPathway("Афиша"); $per_day = 10; //Количество сообытий в дне максимум $display_days = 5; //количество дней которые показывается на странице $dayt = 60 * 60 * 24; //Продолжительность дня в секундах $start_time = strtotime(date('Y-m-d', time()) . " 00:00:00") - $dayt; //Определяем утро сегодняшнего дня $output = array(); for ($i = 0; $i < $display_days; $i++) { $start = strtotime(date('Y-m-d', $start_time + $dayt * $i)); $n = date("N", $start + 1); //Определяем заголовок блока дня if ($i == 0) { $day['title'] = "Сегодня"; } elseif ($i == 1) { $day['title'] = "Завтра"; } else { $day['title'] = $inCore->dateFormat(date('Y-m-d H:i:s', $start_time + $dayt * ($i + 1))); } $day['events'] = $model->getCalendar($start, $start + 86400); //Определяем активные встречи за временной период $output[] = $day; } $inPage->setTitle("Календарь событий"); $smarty = $inPage->initTemplate('components', 'com_calendar_list.tpl'); $smarty->assign('events', $output); $smarty->assign('cfg', $cfg); $smarty->display('com_calendar_list.tpl'); } if ($do == "view_event") { $event_id = $inCore->request('event_id', 'int', 0); $event = $model->getEvent($event_id); /*FOTOLIB*/ include 'fotolib.class.php'; $foto = new FotoLib(); //Проверяем можем ли добавлять фото $allow_add_foto = $foto->addAcces("calendar", $event); if ($_FILES) { $foto->uploadFoto($_FILES, "calendar", $event_id); } $images = $foto->loadImages("calendar", $event_id); /*FOTOLIB*/ if (!$event) { cmsCore::addSessionMessage('Ошибка запроса', 'error'); $inCore->redirect('/calendar'); exit; } elseif ($event['hide'] == 1 and !$inUser->is_admin) { cmsCore::addSessionMessage('Ошибка доступа', 'error'); $inCore->redirect('/calendar'); exit; } else { if ($event['type'] == 'private' and $event['author_id'] != $inUser->id) { cmsCore::addSessionMessage('Ошибка запроса', 'error'); $inCore->redirect('/calendar'); exit; } $msg = $inCore->parseSmiles($event['content'], true); if (count($event['parent']) != 0) { $delta = $event['end_time'] - $event['start_time']; $day = date("d", $event['start_time']); $month = date("n", $event['start_time']) - 1; //Яваскриптики считают с 0 $year = date("Y", $event['start_time']); if ($delta < 24 * 60 * 60) { $calendar_view = "agendaDay"; if (date("d", $event['start_time']) != date("d", $event['end_time'])) { //Если меньше 24 часов но всё же в разные дни включаем недельный вид $calendar_view = "agendaWeek"; } } elseif ($delta < 7 * 24 * 60 * 60) { $calendar_view = "agendaWeek"; } else { $calendar_view = "month"; } $events_string = ""; foreach ($event['parent'] as $parent) { $events_string .= "{\n\t id : '" . $parent['id'] . "',\n\t title : '" . str_replace("'", '"', $parent['title']) . "',\n\t start : '" . date("Y-m-d H:i:s", $parent['start_time']) . "',\n\t end : '" . date("Y-m-d H:i:s", $parent['end_time']) . "',\n\t url : '/calendar/event" . $parent['id'] . ".html',"; if ($parent['end_time'] - $parent['start_time'] > 60 * 60 * 8) { $events_string .= "allDay: true,"; } else { $events_string .= "allDay: false,"; } switch ($parent['type']) { case "public": if ($parent['author_id'] == $inUser->id) { $events_string .= "color: '#B9C3BC',\n"; } else { $events_string .= "color: '#C3BCB9',\n"; } $events_string .= "textColor: '#000000',\n"; break; case "private": $events_string .= "color: '#3366CC'\n"; } $events_string .= "},"; } } $issignup = $model->isSignup($event_id); $singups_user = $model->getSingupsUsers($event_id); $inPage->setTitle('Просмотр события "' . $event['title'] . '"'); $inPage->addPathway("Календарь", "/calendar"); if ($event['parent_id']) { $parent = $model->getEvent($event['parent_id']); $inPage->addPathway($parent['title'], "/calendar/event" . $parent['id'] . ".html"); } $inPage->addPathway($event['title'], "/calendar/event" . $event_id . ".html"); $smarty = $inPage->initTemplate('components', 'com_calendar_event_view.tpl'); $smarty->assign('user_id', $inUser->id); $smarty->assign('event', $event); $smarty->assign('content', $msg); $smarty->assign('parent', $event['parent']); $smarty->assign('calendar_view', $calendar_view); $smarty->assign('events_string', $events_string); $smarty->assign('year', $year); $smarty->assign('month', $month); $smarty->assign('day', $day); $smarty->assign('start_time', date("d.m.Y H:i", $event['start_time'])); $smarty->assign('end_time', date("d.m.Y H:i", $event['end_time'])); $smarty->assign('issngnup', $issignup); $smarty->assign('singups_user', $singups_user); $smarty->assign('images', $images); //fotolib $smarty->assign('allow_add_foto', $allow_add_foto); //fotolib if ($event['start_time'] - time() < 0) { $status = "Прошедшее событие"; } else { if ($event['start_time'] - time() > 86400) { $status = 'Осталось ' . declension(round(($event['start_time'] - time()) / 86400), array("день", "дня", "дней")); } else { $status = 'Осталось ' . declension(round(($event['start_time'] - time()) / 3600), array("час", "часа", "часов")); } } $smarty->assign('status', $status); if ($inUser->id == $event['author_id'] or $inUser->is_admin) { $smarty->assign('admin', TRUE); } $smarty->display('com_calendar_event_view.tpl'); $inCore->includeComments(); comments('calendar', $event_id); return; } } if ($do == "delete_event") { if ($inUser->id == 0) { $inCore->redirect('/'); exit; } $event_id = $inCore->request('event_id', 'int', 0); $deleted = $model->deleteEvent($event_id); if ($deleted) { cmsCore::addSessionMessage('Ваше мероприятие удалено!', 'success'); $inCore->redirect('/calendar'); exit; } else { cmsCore::addSessionMessage('Ошибка', 'error'); $inCore->redirect('/calendar'); exit; } } if ($do == "edit_event") { if ($inUser->id == 0) { $inCore->redirect('/'); exit; } $event_id = $inCore->request('event_id', 'int', 0); $event = $model->getEvent($event_id); if ($event["author_id"] != $inUser->id and !$inUser->is_admin) { cmsCore::addSessionMessage('Ошибка доступа', 'error'); $inCore->redirectBack(); exit; } if ($inUser->is_admin) { $can_moderate = true; } $is_send = $inCore->inRequest('title'); if ($is_send) { $title = $inCore->request('title', 'str'); $type = $inCore->request('type', 'str'); $date_start = $inCore->request('date_start', 'str'); $date_end = $inCore->request('date_end', 'str'); $hour_start = $inCore->request('hour_start', 'str'); $hour_end = $inCore->request('hour_end', 'str'); $min_start = $inCore->request('min_start', 'str'); $min_end = $inCore->request('min_end', 'str'); $content = $inCore->request('content', 'str'); if ($can_moderate) { $m_hide = $inCore->request('hide', 'str'); if ($m_hide == "on") { $hide = 1; } else { $hide = 0; } } if (!$title || !$type || !$date_start || !$hour_start || !$hour_end || !$min_start || !$min_end) { cmsCore::addSessionMessage('Ой, что то не было заполнено...', 'error'); $inCore->redirectBack(); exit; } else { $start_time = strtotime($date_start . ' ' . $hour_start . ':' . $min_start); if ($data_end == "" or $data_end < $data_start) { $data_end = $data_start; } $end_time = strtotime($date_end . ' ' . $hour_end . ':' . $min_end); if (!is_numeric($type)) { $category_id = "0"; } else { $category_id = $type; $type = "public"; } $update = $model->updateEvent($event_id, $type, $category_id, $start_time, $end_time, $title, $content, $hide); if ($update) { cmsCore::addSessionMessage('Ваше мероприятие изменено!', 'success'); $inCore->redirect('/calendar/event' . $event_id . '.html'); exit; } else { cmsCore::addSessionMessage('Ошибка добавления!', 'error'); $inCore->redirect('/calendar/edit' . $event_id . '.html'); exit; } } } else { $event = $model->getEvent($event_id); if (!$event) { cmsCore::addSessionMessage('Ошибка запроса тут', 'error'); $inCore->redirect('/calendar'); exit; } if ($event['category_id']) { $event['type'] = $event['category_id']; } $bb_toolbar = cmsPage::getBBCodeToolbar('calendar', 1, 'forum'); $smilies = cmsPage::getSmilesPanel('calendar'); //Проверяем присоедиялся ли пользователь ко встрече $catigories = $model->getAllCategories(); $inPage->setTitle("Редактировать событие"); $smarty = $inPage->initTemplate('components', 'com_calendar_add.tpl'); $smarty->assign('event', $event); $smarty->assign('edit', 1); $smarty->assign('cfg', $cfg); $smarty->assign('catigories', $catigories); $smarty->assign('title', $event['title']); $smarty->assign('content', $event['content']); $smarty->assign('type', $event['type']); $smarty->assign('start_date', date("d.m.Y", $event['start_time'])); $smarty->assign('start_hour', date("H", $event['start_time'])); $smarty->assign('start_min', date("i", $event['start_time'])); $smarty->assign('end_date', date("d.m.Y", $event['end_time'])); $smarty->assign('end_hour', date("H", $event['end_time'])); $smarty->assign('end_min', date("i", $event['end_time'])); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->assign('can_moderate', $can_moderate); $smarty->display('com_calendar_add.tpl'); return; } } if ($do == "event_signup") { //Если не залогинились то возвращаем обратно if ($inUser->id == 0) { $inCore->redirectBack(); return; } $event_id = $inCore->request('event_id', 'int', 0); $event = $model->getEvent($event_id); //Если приватное событие то отправляем обратно if ($event["type"] == "private") { $inCore->redirectBack(); return; } //Если мероприятие уже прошло говорим ай-яй-яй if ($event['start_time'] - time() < 0) { cmsCore::addSessionMessage('Присоединиться к мероприятию уже невозможно', 'error'); $inCore->redirectBack(); exit; } //Проверяем статус присоединения ко встрече if ($model->isSignup($event_id)) { //Если уже присоединялись то удаляем и выводим статус $model->deleteSignup($event_id); cmsCore::addSessionMessage('Вы отказались от участия в мероприятии ' . $event["title"], 'success'); // Добавляем событие в ленту cmsActions::log('del_signup', array('object' => $event["title"], 'object_url' => '/calendar/event' . $event_id . '.html', 'object_id' => $event_id, 'target' => '', 'target_url' => '/calendar/event' . $event_id . '.html', 'target_id' => '0', 'description' => '')); $inCore->redirect('/calendar/event' . $event_id . '.html'); } else { //Если не присоединялись то добавляем в базу и выводим статус //Если уже присоединялись то удаляем и выводим статус $model->addSignup($event["id"]); cmsCore::addSessionMessage('Вы присоединились к событию ' . $event["title"], 'success'); // Добавляем событие в ленту cmsActions::log('add_signup', array('object' => $event["title"], 'object_url' => '/calendar/event' . $event_id . '.html', 'object_id' => $event["id"], 'target' => '', 'target_url' => '/calendar/event' . $event_id . '.html', 'target_id' => '0', 'description' => '')); $inCore->redirect('/calendar/event' . $event_id . '.html'); } return; } //AJAX if ($do == "ajax_add") { $can_add = FALSE; $moderated = TRUE; if ($cfg['group_' . $inUser->group_id] or $inUser->is_admin) { $can_add = TRUE; $moderated = FALSE; } elseif ($cfg['m_group_' . $inUser->group_id]) { $can_add = TRUE; $moderated = TRUE; } if ($can_add) { $title = $inCore->request('title', 'str'); $type = $inCore->request('type', 'str'); $date_start = $inCore->request('date_start', 'str'); $date_end = $inCore->request('date_end', 'str'); $hour_start = $inCore->request('hour_start', 'str'); $hour_end = $inCore->request('hour_end', 'str'); $min_start = $inCore->request('min_start', 'str'); $min_end = $inCore->request('min_end', 'str'); $content = $inCore->request('content', 'str'); $parent_id = $inCore->request('parent_id', 'int'); $m_hide = $inCore->request('hide', 'str'); if ($m_hide == "on" or $moderated) { $hide = 1; } else { $hide = 0; } $start_time = strtotime($date_start . ' ' . $hour_start . ':' . $min_start); $end_time = strtotime($date_end . ' ' . $hour_end . ':' . $min_end); if ($start_hour < $cfg['calendar_minTime']) { $output['error'] = TRUE; $output['errortext'] = "Событие начинается слишком рано"; } if ($end_hour > $cfg['calendar_maxTime']) { $output['error'] = TRUE; $output['errortext'] = "Событие заканчивается слишком поздно"; } if ($end_hour == $cfg['calendar_maxTime'] and $end_min != 0) { $output['error'] = TRUE; $output['errortext'] = "Событие заканчивается слишком поздно"; } if ($type == "private") { $category_id = 0; $type = "private"; } else { if (is_numeric($type)) { $category_id = $type; } else { $category_id = 0; } $type = "public"; } if ($parent_id) { $parent = $model->getEvent($parent_id); if (!$parent) { $output['error'] = TRUE; $output['errortext'] = "Родительское событие не найдено"; } elseif ($parent['user_id'] != $inUser->id or !$inUser->is_admin) { $output['error'] = TRUE; $output['errortext'] = "Ошибка прав доступа"; } elseif ($parent['hide'] == 1) { $output['error'] = TRUE; $output['errortext'] = "Нельзя добавлять события в скрытое событие"; } } if (!$output['error']) { $event_id = $model->addEvent($inUser->id, $type, $category_id, $start_time, $end_time, $title, $content, $parent_id, $hide); } $output = array(); if (!$event_id) { $output['error'] = TRUE; $output['errortext'] = "Ошибка БД"; } else { $output['error'] = FALSE; $event = $model->getEvent($event_id); $output['event_id'] = $event_id; $output['start'] = $event['start_time']; $output['end'] = $event['end_time']; $output['hide'] = $hide; if ($event['end_time'] - $event['start_time'] > 60 * 60 * 8) { $output['allDay'] = TRUE; } else { $output['allDay'] = FALSE; } $output['bg'] = $event['bg']; $output['tx'] = $event['tx']; if ($type != "private" and $hide != 1) { cmsActions::log('add_event', array('object' => 'событие', 'object_url' => '/calendar/event' . $event_id . '.html', 'object_id' => $event_id, 'target' => $title, 'target_url' => '/calendar/event' . $event_id . '.html', 'target_id' => '0', 'description' => $title)); } } } else { $output['error'] = TRUE; $output['errortext'] = "Ошибка доступа"; } print json_encode($output); exit; } if ($do == "ajax_edit") { $type_act = $inCore->request('type', 'str'); $id = $inCore->request('id', 'int'); $dayDelta = $inCore->request('dayDelta', 'str'); $minuteDelta = $inCore->request('minuteDelta', 'str'); $event = $model->getEvent($id); if ($event['author_id'] == $inUser->id or $inUser->is_admin) { $type = $event['type']; $category_id = $event['category_id']; $start_time = $event['start_time']; $end_time = $event['end_time']; $title = $event['title']; $content = $event['content']; $delta = $dayDelta * 24 * 60 * 60 + $minuteDelta * 60; if ($type_act == "drop") { $start_time = $start_time + $delta; $end_time = $end_time + $delta; } if ($type_act == "resize") { if ($end_time - $start_time > 0) { $end_time = $end_time + $delta; } else { print "Ошибка смещения"; } } $model->updateEvent($id, $type, $category_id, $start_time, $end_time, $title, $content); } else { print "Ошибка доступа"; } exit; } if ($do == "ajax_get_event") { $starttime = $inCore->request('start', 'int'); $endtime = $inCore->request('end', 'int'); $parent_id = $inCore->request('parent_id', 'parent_id'); $category = $inCore->request('category', 'int'); if ($category == "all" and !is_numeric($category)) { $category = FALSE; } if (!$parent_id) { $parent_id = 0; } if ($inUser->is_admin) { $show_hidden = true; } $events = $model->getCalendar($starttime, $endtime, $category, $parent_id, $show_hidden); $output = array(); foreach ($events as $data) { $data['start'] = date("Y-m-d H:i:s", $data["start_time"]); $data['end'] = date("Y-m-d H:i:s", $data["end_time"]); $data['url'] = "/calendar/event" . $data['id'] . ".html"; // $data['image'] = "/components/calendar/images/no_image.png"; if ($data["author_id"] == $inUser->id or $inUser->is_admin) { $data['editable'] = true; } else { $data['editable'] = false; } if ($data["end_time"] - $data["start_time"] > 60 * 60 * 8) { $data['allDay'] = "true"; } if (!$data['category_id']) { switch ($data["type"]) { case "public": $data['color'] = $cfg['public_bg_color']; $data['textColor'] = $cfg['public_tx_color']; break; case "private": $data['color'] = $cfg['private_bg_color']; $data['textColor'] = $cfg['private_tx_color']; break; } } else { $data['color'] = $data['bg']; $data['textColor'] = $data['tx']; } if ($data["type"] == "private" and $data['author_id'] != $inUser->id) { } else { $output[] = $data; } } print json_encode($output); exit; } if ($do == "isc_calendar") { header('Content-type: text/calendar; charset=utf-8'); header('Content-Disposition: inline; filename=calendar.ics'); echo "BEGIN:VCALENDAR\n"; echo "VERSION:2.0\n"; echo "PRODID:-//hacksw/handcal//NONSGML v1.0//EN'\n"; $events = $model->getCalendar(time() - 60 * 60 * 24 * 30, time() + 60 * 60 * 24 * 30, 0); foreach ($events as $event) { if ($event['type'] == "public") { $title = $event["title"]; $dtstart = date("Ymd", $event["start_time"] - 60 * 60 * 4) . "T" . date("His", $event["start_time"] - 60 * 60 * 4); $dtend = date("Ymd", $event["end_time"] - 60 * 60 * 4) . "T" . date("His", $event["end_time"] - 60 * 60 * 4); echo "BEGIN:VEVENT\n"; echo "DTSTART:{$dtstart}\n"; echo "DTEND:{$dtend}\n"; echo "SUMMARY:{$title}\n"; echo "END:VEVENT\n"; } } echo "END:VCALENDAR\n"; exit; } if ($do == "ajax_add_form") { $start = strtotime($inCore->request('start', 'str')); $end = strtotime($inCore->request('end', 'str')); if ($start < strtotime('now 00:00:00')) { echo 'error'; exit; } if (!$cfg['group_' . $inUser->group_id] and !$inUser->is_admin and !$cfg['m_group_' . $inUser->group_id]) { echo 'error'; exit; } //Коректность времени добавления $start_hour = date("H", $start); if ($start_hour < $cfg['calendar_minTime']) { $start_hour = $cfg['calendar_minTime']; } $end_hour = date("H", $end); $end_min = date("i", $end); if ($end_hour > $cfg['calendar_maxTime']) { $end_hour = $cfg['calendar_maxTime']; $end_min = "00"; } if ($inUser->is_admin) { $can_moderate = true; } $catigories = $model->getAllCategories(); $bb_toolbar = cmsPage::getBBCodeToolbar('message', $cfg['img_on'], 'forum'); $smilies = cmsPage::getSmilesPanel('message'); $smarty = $inPage->initTemplate('components', 'com_calendar_add.tpl'); $smarty->assign('catigories', $catigories); $smarty->assign('start_date', date("d.m.Y", $start)); $smarty->assign('start_hour', $start_hour); $smarty->assign('start_min', date("i", $start)); $smarty->assign('end_date', date("d.m.Y", $end)); $smarty->assign('end_hour', $end_hour); $smarty->assign('end_min', $end_min); $smarty->assign('can_moderate', $can_moderate); $smarty->assign('bb_toolbar', $bb_toolbar); $smarty->assign('smilies', $smilies); $smarty->assign('cfg', $cfg); //print_r($cfg); $smarty->display('com_calendar_add.tpl'); exit; } if ($do == "ajax_get_config") { print json_encode($cfg); exit; } // FOTOLIB if ($do == "imagerotate") { $side = $md5 = $inCore->request('side', 'str'); $image_id = $inCore->request('image_id', 'int'); include 'fotolib.class.php'; $foto = new FotoLib(); $foto->Rotate($side, $image_id); $inCore->redirectBack(); exit; } if ($do == "imagedelete") { include 'fotolib.class.php'; $image_id = $inCore->request('image_id', 'int'); $foto = new FotoLib(); $foto->Delete($image_id); $inCore->redirectBack(); exit; } if ($do == "ajax_format_date") { print cmsCore::dateFormat(date('Y-m-d H:i:s', $inCore->request('time', 'int')), 0, 0, 0); exit; } }