public function deleteQuest($id) { $inCore = cmsCore::getInstance(); $this->inDB->query("DELETE FROM cms_armedlist_quests WHERE id={$id}"); $inCore->deleteComments('armedlist', $id); cmsActions::removeObjectLog('add_quest', $id); return true; }
public function deleteItem($id) { $imageurl = $this->getItemImageUrl($id); @chmod(PATH . "/images/catalog/{$imageurl}", 0777); @chmod(PATH . "/images/catalog/small/{$imageurl}", 0777); @chmod(PATH . "/images/catalog/medium/{$imageurl}", 0777); @unlink(PATH . '/images/catalog/' . $imageurl); @unlink(PATH . '/images/catalog/small/' . $imageurl); @unlink(PATH . '/images/catalog/medium/' . $imageurl); $this->inDB->query("DELETE FROM cms_uc_items WHERE id= '{$id}'"); $this->inDB->query("DELETE FROM cms_tags WHERE target='catalog' AND item_id = '{$id}'"); $this->inDB->query("DELETE FROM cms_uc_ratings WHERE item_id = '{$id}'"); cmsActions::removeObjectLog('add_catalog', $id); cmsCore::deleteComments('catalog', $id); }
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'; } }
/** * Удаляет пост в блоге * @param int $post_id * @return bool */ public function deletePost($post_id) { cmsCore::callEvent('DELETE_POST', $post_id); $post = $this->getPost($post_id); if (!$post) { return false; } // пересчитываем рейтинг блога $this->inDB->query("UPDATE cms_blogs SET rating = rating - ({$post['rating']}) WHERE id = '{$post['blog_id']}'"); $this->inDB->delete('cms_blog_posts', "id = '{$post_id}'", 1); cmsCore::deleteRatings($this->getTarget('rating'), $post_id); cmsCore::deleteComments($this->getTarget('comments'), $post_id); cmsClearTags($this->getTarget('tags'), $post_id); cmsCore::deleteUploadImages($post_id, 'blog_post'); cmsActions::removeObjectLog($this->getTarget('actions_post'), $post_id); return true; }
/** * Удаляет пользователя $user_id из списка друзей текущего пользователя * @param int $user_id * @return bool */ public static function deleteFriend($user_id = 0) { if (!$user_id) { return false; } $friend_field_id = self::getFriendFieldId($user_id); if ($friend_field_id) { cmsCore::callEvent('DELETE_FRIEND', $user_id); cmsDatabase::getInstance()->query("DELETE FROM cms_user_friends WHERE id = '{$friend_field_id}'"); cmsActions::removeObjectLog('add_friend', $friend_field_id); cmsUser::clearSessionFriends(); return true; } return false; }
/** * Удаляет все комментарии для указанной цели * @param string $target * @param int $target_id * @return boolean */ public static function deleteComments($target, $target_id) { $inDB = cmsDatabase::getInstance(); $comments = $inDB->get_table('cms_comments', "target='{$target}' AND target_id='{$target_id}'", 'id'); if (!$comments) { return false; } self::loadClass('actions'); foreach ($comments as $comment) { cmsActions::removeObjectLog('add_comment', $comment['id']); self::deleteUploadImages($comment['id'], 'comment'); self::deleteRatings('comment', $comment['id']); } $inDB->delete('cms_comments', "target='{$target}' AND target_id='{$target_id}'"); return true; }
/** * Удаляет фото * @param array $photo * @param obj $inUploadPhoto * @return bool */ public function deletePhoto($photo, $inUploadPhoto){ $photo = cmsCore::callEvent('DELETE_PHOTO', $photo); if(!$this->deletePhotoFile($photo['file'], $inUploadPhoto)){ return false; } cmsCore::deleteComments($this->getTarget('comments_photo'), $photo['id']); cmsCore::deleteRatings($this->getTarget('rating'), $photo['id']); cmsClearTags($this->getTarget('tags'), $photo['id']); cmsActions::removeObjectLog($this->getTarget('actions_photo'), $photo['id']); cmsCore::c('db')->query("DELETE FROM cms_photo_files WHERE id = '{$photo['id']}' LIMIT 1"); return true; }
public function deleteRecord($item_id) { cmsCore::callEvent('DELETE_BOARD_RECORD', $item_id); $item = $this->getRecord($item_id); if (!$item) { return false; } @unlink(PATH . '/images/board/' . $item['file']); @unlink(PATH . '/images/board/small/' . $item['file']); @unlink(PATH . '/images/board/medium/' . $item['file']); $this->inDB->delete('cms_board_items', " id = '{$item_id}'", 1); cmsCore::deleteComments('boarditem', $item_id); cmsActions::removeObjectLog('add_board', $item_id); return true; }
public function deleteThread($thread_id) { cmsActions::removeObjectLog('add_thread', $thread_id); $this->whereThreadIs($thread_id); $posts = $this->getPosts(); if ($posts) { foreach ($posts as $post) { $this->deletePost($post['id']); } } $this->inDB->query("DELETE FROM cms_forum_threads WHERE id = '{$thread_id}'"); $poll = $this->getThreadPoll($thread_id); if ($poll) { $this->deletePoll($poll['id']); } }
/** * Удаляет статью * @return bool */ public function deleteArticle($id) { cmsCore::callEvent('DELETE_ARTICLE', $id); $this->inDB->delete('cms_content', "id='{$id}'", 1); $this->inDB->delete('cms_tags', "target='content' AND item_id='{$id}'"); cmsCore::clearAccess($id, 'material'); cmsActions::removeObjectLog('add_article', $id); @unlink(PATH . '/images/photos/small/article' . $id . '.jpg'); @unlink(PATH . '/images/photos/medium/article' . $id . '.jpg'); cmsCore::deleteRatings('content', $id); cmsCore::deleteComments('article', $id); translations::deleteTargetTranslation('content_content', $id); return true; }
/** * Удаляет все комментарии для указанной цели * @param string $target * @param int $target_id * @return boolean */ public static function deleteComments($target, $target_id){ $comments = self::c('db')->get_table('cms_comments', "target='". $target ."' AND target_id='". $target_id ."'", 'id'); if (!$comments){ return false; } self::loadClass('actions'); foreach($comments as $comment){ cmsActions::removeObjectLog('add_comment', $comment['id']); self::deleteUploadImages($comment['id'], 'comment'); self::deleteRatings('comment', $comment['id']); } self::c('db')->delete('cms_comments', "target='". $target ."' AND target_id='". $target_id ."'");; return true; }
/** * Удаляет клуб * @return bool */ public function deleteClub($club_id) { cmsCore::callEvent('DELETE_CLUB', $club_id); $club = $this->getClub($club_id); if (!$club) { return false; } $inBlog = $this->initBlog(); cmsCore::loadClass('photo'); $inPhoto = $this->initPhoto(); //Удаляем логотип клуба if ($club['imageurl'] != 'nopic.jpg') { @unlink(PATH . '/images/clubs/' . $club['imageurl']); @unlink(PATH . '/images/clubs/small/' . $club['imageurl']); } //Удаляем клуб и привязки пользователей $this->inDB->query("DELETE FROM cms_clubs WHERE id = '{$club_id}'"); $this->inDB->query("DELETE FROM cms_user_clubs WHERE club_id = '{$club_id}'"); //Удаляем блог клуба $inBlog->deleteBlog($this->getClubBlogId($club_id)); //Удаляем фотоальбомы клуба $inPhoto->deleteAlbum($this->inDB->getNsRootCatId('cms_photo_albums', 'club' . $club_id), 'club' . $club_id, $this->initUploadClass()); $this->inDB->query("DELETE FROM cms_photo_albums WHERE NSDiffer = 'club{$club_id}'"); cmsActions::removeObjectLog('add_club', $club_id); return true; }
/** * Удаляет статью * @return bool */ public function deleteArticle($id) { cmsCore::callEvent('DELETE_ARTICLE', $id); cmsCore::c('db')->delete('cms_content', "id='". $id ."'", 1); cmsCore::c('db')->delete('cms_tags', "target='content' AND item_id='". $id ."'"); cmsCore::clearAccess($id, 'material'); cmsActions::removeObjectLog('add_article', $id); @unlink(PATH .'/images/content/medium/'. ceil($id/100) .'/article'. $id .'.jpg'); @unlink(PATH .'/images/content/small/'. ceil($id/100) .'/article'. $id .'.jpg'); cmsCore::deleteUploadImages($id, '', 'content'); cmsCore::deleteRatings('content', $id); cmsCore::deleteComments('article', $id); return true; }
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)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }
public function deletePhoto($photo_id) { cmsCore::loadLib('tags'); $sql = "SELECT imageurl FROM cms_user_photos WHERE id = '{$photo_id}'"; $result = $this->inDB->query($sql); if ($this->inDB->num_rows($result)){ $photo = $this->inDB->fetch_assoc($result); @unlink(PATH.'/images/users/photos/'.$photo['imageurl']); @unlink(PATH.'/images/users/photos/small/'.$photo['imageurl']); @unlink(PATH.'/images/users/photos/medium/'.$photo['imageurl']); $this->inDB->query("DELETE FROM cms_user_photos WHERE id = $photo_id") ; cmsCore::deleteComments('userphoto', $photo_id); cmsActions::removeObjectLog('add_user_photo', $photo_id); cmsClearTags('userphoto', $photo_id); } return true; }
if (!$inUser->id || $inUser->id != $id && !$inUser->is_admin) { cmsCore::error404(); } $a_list = rtrim(implode(',', $files), ','); $fsql = ''; if ($a_list) { $fsql .= "id IN ({$a_list})"; } else { $fsql .= '1=0'; } $sql = "SELECT id, filename FROM cms_user_files WHERE user_id = '{$id}' AND {$fsql}"; $result = $inDB->query($sql); if ($inDB->num_rows($result)) { while ($file = $inDB->fetch_assoc($result)) { @unlink(PATH . '/upload/userfiles/' . $id . '/' . $file['filename']); cmsActions::removeObjectLog('add_file', $file['id']); } $inDB->query("DELETE FROM cms_user_files WHERE user_id = '{$id}' AND {$fsql}"); } cmsCore::redirect('/users/' . $id . '/files.html'); } /////////////////////////////// MULTIPLE FILES PUBLISHING ///////////////////////////////////////////////////////////////////////////////////////// if ($fdo == 'pubfilelist') { $files = cmsCore::request('files', 'array_int', array()); if (!$files) { cmsCore::error404(); } $allow = cmsCore::request('allow', 'str', 'nobody'); if (!$inUser->id || $inUser->id != $id && !$inUser->is_admin) { cmsCore::error404(); }
public function deleteComment($comment_id) { cmsCore::callEvent('DELETE_COMMENT', $comment_id); $this->childs = array(); $this->getCommentChilds($comment_id); $sql = "DELETE FROM cms_comments WHERE id = '{$comment_id}' LIMIT 1"; $this->inDB->query($sql); cmsCore::deleteRatings('comment', $comment_id); cmsActions::removeObjectLog('add_comment', $comment_id); cmsCore::deleteUploadImages($comment_id, 'comment'); if ($this->childs) { foreach ($this->childs as $child) { cmsCore::callEvent('DELETE_COMMENT', $child['id']); $sql = "DELETE FROM cms_comments WHERE id = '{$child['id']}' LIMIT 1"; $this->inDB->query($sql); cmsCore::deleteRatings('comment', $child['id']); cmsActions::removeObjectLog('add_comment', $child['id']); cmsCore::deleteUploadImages($child['id'], 'comment'); } } return true; }