1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-16 23:00:51 +03:00

Вынос стандартных прав в модуль rbac

This commit is contained in:
Mzhelskiy Maxim 2014-10-07 19:36:53 +07:00
parent 565180d1ad
commit 288f6e9a10
10 changed files with 473 additions and 319 deletions

View file

@ -1021,31 +1021,11 @@ class ActionAjax extends Action {
return parent::EventNotFound();
}
}
/**
* Голосует автор комментария?
*/
if ($oComment->getUserId()==$this->oUserCurrent->getId()) {
return $this->EventErrorDebug();
}
/**
* Пользователь уже голосовал?
*/
if ($oTopicCommentVote=$this->Vote_GetVote($oComment->getId(),'comment',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_already_voted'),$this->Lang_Get('attention'));
return;
}
/**
* Время голосования истекло?
*/
if (strtotime($oComment->getDate())<=time()-Config::Get('acl.vote.comment.limit_time')) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_time'),$this->Lang_Get('attention'));
return;
}
/**
* Пользователь имеет право голоса?
*/
if (!$this->ACL_CanVoteComment($this->oUserCurrent,$oComment)) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_acl'),$this->Lang_Get('attention'));
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return;
}
/**
@ -1106,27 +1086,6 @@ class ActionAjax extends Action {
if (!$this->ACL_IsAllowShowTopic($oTopic,$this->oUserCurrent)) {
return parent::EventNotFound();
}
/**
* Голосует автор топика?
*/
if ($oTopic->getUserId()==$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_self'),$this->Lang_Get('attention'));
return;
}
/**
* Пользователь уже голосовал?
*/
if ($oTopicVote=$this->Vote_GetVote($oTopic->getId(),'topic',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_already_voted'),$this->Lang_Get('attention'));
return;
}
/**
* Время голосования истекло?
*/
if (strtotime($oTopic->getDateAdd())<=time()-Config::Get('acl.vote.topic.limit_time')) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_time'),$this->Lang_Get('attention'));
return;
}
/**
* Как проголосовал пользователь
*/
@ -1137,8 +1096,8 @@ class ActionAjax extends Action {
/**
* Права на голосование
*/
if (!$this->ACL_CanVoteTopic($this->oUserCurrent,$oTopic) and $iValue) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_acl'),$this->Lang_Get('attention'));
if (!$this->ACL_CanVoteTopic($this->oUserCurrent,$oTopic,$iValue)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return;
}
/**
@ -1199,66 +1158,43 @@ class ActionAjax extends Action {
if (!($oBlog=$this->Blog_GetBlogById(getRequestStr('iTargetId',null,'post')))) {
return $this->EventErrorDebug();
}
/**
* Голосует за свой блог?
*/
if ($oBlog->getOwnerId()==$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_self'),$this->Lang_Get('attention'));
return;
}
/**
* Уже голосовал?
*/
if ($oBlogVote=$this->Vote_GetVote($oBlog->getId(),'blog',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_already_voted'),$this->Lang_Get('attention'));
return;
}
/**
* Имеет право на голосование?
*/
switch($this->ACL_CanVoteBlog($this->oUserCurrent,$oBlog)) {
case ModuleACL::CAN_VOTE_BLOG_TRUE:
$iValue=getRequestStr('value',null,'post');
if (in_array($iValue,array('1','-1'))) {
$oBlogVote=Engine::GetEntity('Vote');
$oBlogVote->setTargetId($oBlog->getId());
$oBlogVote->setTargetType('blog');
$oBlogVote->setVoterId($this->oUserCurrent->getId());
$oBlogVote->setDirection($iValue);
$oBlogVote->setDate(date("Y-m-d H:i:s"));
$iVal=(float)$this->Rating_VoteBlog($this->oUserCurrent,$oBlog,$iValue);
$oBlogVote->setValue($iVal);
$oBlog->setCountVote($oBlog->getCountVote()+1);
if (!$this->ACL_CanVoteBlog($this->oUserCurrent,$oBlog)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return;
}
$this->Hook_Run("vote_{$oBlogVote->getTargetType()}_before",array('oTarget'=>$oBlog,'oVote'=>$oBlogVote,'iValue' => $iValue));
if ($this->Vote_AddVote($oBlogVote) and $this->Blog_UpdateBlog($oBlog)) {
$this->Hook_Run("vote_{$oBlogVote->getTargetType()}_after",array('oTarget'=>$oBlog,'oVote'=>$oBlogVote,'iValue' => $iValue));
$iValue=getRequestStr('value',null,'post');
if (in_array($iValue,array('1','-1'))) {
$oBlogVote=Engine::GetEntity('Vote');
$oBlogVote->setTargetId($oBlog->getId());
$oBlogVote->setTargetType('blog');
$oBlogVote->setVoterId($this->oUserCurrent->getId());
$oBlogVote->setDirection($iValue);
$oBlogVote->setDate(date("Y-m-d H:i:s"));
$iVal=(float)$this->Rating_VoteBlog($this->oUserCurrent,$oBlog,$iValue);
$oBlogVote->setValue($iVal);
$oBlog->setCountVote($oBlog->getCountVote()+1);
$this->Viewer_AssignAjax('iCountVote',$oBlog->getCountVote());
$this->Viewer_AssignAjax('iRating',$oBlog->getRating());
$this->Message_AddNoticeSingle($this->Lang_Get('vote.notices.success'),$this->Lang_Get('attention'));
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oBlogVote->getVoterId(), 'vote_blog', $oBlog->getId());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('attention'));
return;
}
} else {
return $this->EventErrorDebug();
}
break;
case ModuleACL::CAN_VOTE_BLOG_ERROR_CLOSE:
$this->Message_AddErrorSingle($this->Lang_Get('blog.vote.notices.error_close'),$this->Lang_Get('attention'));
$this->Hook_Run("vote_{$oBlogVote->getTargetType()}_before",array('oTarget'=>$oBlog,'oVote'=>$oBlogVote,'iValue' => $iValue));
if ($this->Vote_AddVote($oBlogVote) and $this->Blog_UpdateBlog($oBlog)) {
$this->Hook_Run("vote_{$oBlogVote->getTargetType()}_after",array('oTarget'=>$oBlog,'oVote'=>$oBlogVote,'iValue' => $iValue));
$this->Viewer_AssignAjax('iCountVote',$oBlog->getCountVote());
$this->Viewer_AssignAjax('iRating',$oBlog->getRating());
$this->Message_AddNoticeSingle($this->Lang_Get('vote.notices.success'),$this->Lang_Get('attention'));
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oBlogVote->getVoterId(), 'vote_blog', $oBlog->getId());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('attention'));
return;
break;
default:
case ModuleACL::CAN_VOTE_BLOG_FALSE:
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_acl'),$this->Lang_Get('attention'));
return;
break;
}
} else {
return $this->EventErrorDebug();
}
}
/**
@ -1279,25 +1215,11 @@ class ActionAjax extends Action {
if (!($oUser=$this->User_GetUserById(getRequestStr('iTargetId',null,'post')))) {
return $this->EventErrorDebug();
}
/**
* Голосует за себя?
*/
if ($oUser->getId()==$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_self'),$this->Lang_Get('attention'));
return;
}
/**
* Уже голосовал?
*/
if ($oUserVote=$this->Vote_GetVote($oUser->getId(),'user',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_already_voted'),$this->Lang_Get('attention'));
return;
}
/**
* Имеет право на голосование?
*/
if (!$this->ACL_CanVoteUser($this->oUserCurrent,$oUser)) {
$this->Message_AddErrorSingle($this->Lang_Get('vote.notices.error_acl'),$this->Lang_Get('attention'));
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return;
}
/**
@ -1489,10 +1411,11 @@ class ActionAjax extends Action {
return $this->EventErrorDebug();
}
/**
* Есть доступ к комментарию?
* Есть права?
*/
if (!$this->ACL_IsAllowFavouriteComment($oComment,$this->oUserCurrent)) {
return $this->EventErrorDebug();
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return;
}
/**
* Комментарий уже в избранном?

View file

@ -193,10 +193,10 @@ class ActionBlog extends Action {
return Router::Action('error');
}
/**
* Проверяем хватает ли рейтинга юзеру чтоб создать блог
* Проверяем права на создание блога
*/
if (!$this->ACL_CanCreateBlog($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) {
$this->Message_AddErrorSingle($this->Lang_Get('blog.add.alerts.acl'),$this->Lang_Get('error'));
if (!$this->ACL_CanCreateBlog($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return Router::Action('error');
}
$this->Hook_Run('blog_add_show');
@ -1011,17 +1011,10 @@ class ActionBlog extends Action {
/**
* Проверяем разрешено ли постить комменты
*/
if (!$this->ACL_CanPostComment($this->oUserCurrent,$oTopic) and !$this->oUserCurrent->isAdministrator()) {
$this->Message_AddErrorSingle($this->Lang_Get('topic.comments.notices.acl'),$this->Lang_Get('error'));
return;
}
/**
* Проверяем разрешено ли постить комменты по времени
*/
if (!$this->ACL_CanPostCommentTime($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) {
$this->Message_AddErrorSingle($this->Lang_Get('topic.comments.notices.limit'),$this->Lang_Get('error'));
$bOk = false;
}
if (!$this->ACL_CanPostComment($this->oUserCurrent,$oTopic)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
$bOk = false;
}
/**
* Проверяем запрет на добавления коммента автором топика
*/

View file

@ -134,7 +134,8 @@ class ActionContent extends Action {
* проверяем есть ли право на удаление топика
*/
if (!$this->ACL_IsAllowDeleteTopic($oTopic,$this->oUserCurrent)) {
return parent::EventNotFound();
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return Router::Action('error');
}
/**
* Удаляем топик
@ -192,6 +193,13 @@ class ActionContent extends Action {
if (!$oTopicType=$this->Topic_GetTopicType($sTopicType)) {
return parent::EventNotFound();
}
/**
* Проверяем права на создание топика
*/
if (!$this->ACL_CanAddTopic($this->oUserCurrent,$oTopicType)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return Router::Action('error');
}
$this->sMenuSubItemSelect=$sTopicType;
/**
* Вызов хуков
@ -349,18 +357,18 @@ class ActionContent extends Action {
protected function EventAjaxAdd() {
$this->Viewer_SetResponseAjax();
/**
* TODO: Здесь нужна проверка прав на создание топика
* Проверяем тип топика
*/
$sTopicType=getRequestStr('topic_type');
if (!$oTopicType=$this->Topic_GetTopicType($sTopicType)) {
return $this->EventErrorDebug();
}
/**
* Проверяем разрешено ли постить топик по времени
* Проверяем права на создание топика
*/
if (isPost('submit_topic_publish') and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Lang_Get('topic.add.notices.time_limit'),$this->Lang_Get('error'));
return;
if (!$this->ACL_CanAddTopic($this->oUserCurrent,$oTopicType)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return false;
}
/**
* Создаем топик

View file

@ -217,10 +217,10 @@ class ActionSettings extends Action {
$bError=false;
/**
* Есть права на отправку инфайтов?
* Есть права на отправку инвайтов?
*/
if (!$this->ACL_CanSendInvite($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) {
$this->Message_AddError($this->Lang_Get('user.settings.invites.available_no'),$this->Lang_Get('error'));
if (!$this->ACL_CanSendInvite($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
$bError=true;
}
/**

View file

@ -368,19 +368,19 @@ class ActionTalk extends Action {
if (!isPost('submit_talk_add')) {
return false;
}
/**
* Проверяем разрешено ли отправлять личное сообщение
*/
if (!$this->ACL_CanAddTalk($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return Router::Action('error');
}
/**
* Проверка корректности полей формы
*/
if (!$this->checkTalkFields()) {
return false;
}
/**
* Проверяем разрешено ли отправлять инбокс по времени
*/
if (!$this->ACL_CanSendTalkTime($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Lang_Get('talk.notices.time_limit'),$this->Lang_Get('error'));
return false;
}
/**
* Отправляем письмо
*/
@ -626,11 +626,11 @@ class ActionTalk extends Action {
return $this->EventErrorDebug();
}
/**
* Проверяем разрешено ли отправлять инбокс по времени
* Проверяем разрешено ли постить комменты
*/
if (!$this->ACL_CanPostTalkCommentTime($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Lang_Get('talk.add.notices.time_limit'),$this->Lang_Get('error'));
return false;
if (!$this->ACL_CanPostTalkComment($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
return;
}
/**
* Проверяем текст комментария

View file

@ -23,13 +23,6 @@
* @since 1.0
*/
class ModuleACL extends Module {
/**
* Коды ответов на запрос о возможности
* пользователя голосовать за блог
*/
const CAN_VOTE_BLOG_FALSE = 0;
const CAN_VOTE_BLOG_TRUE = 1;
const CAN_VOTE_BLOG_ERROR_CLOSE = 2;
/**
* Коды механизма удаления блога
*/
@ -49,66 +42,94 @@ class ModuleACL extends Module {
* @param ModuleUser_EntityUser $oUser Пользователь
* @return bool
*/
public function CanCreateBlog(ModuleUser_EntityUser $oUser) {
if ($oUser->getRating()>=Config::Get('acl.create.blog.rating')) {
return true;
}
return false;
public function CanCreateBlog($oUser) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'create_blog',array('callback'=>function($oUser,$aParams) use($that) {
if (!$oUser) {
return false;
}
if ($oUser->isAdministrator()) {
return true;
}
/**
* Проверяем хватает ли рейтинга юзеру чтоб создать блог
*/
if ($oUser->getRating()<Config::Get('acl.create.blog.rating')) {
return $that->Lang_Get('blog.add.alerts.acl');
}
return true;
}));
}
/**
* Проверяет может ли пользователь создавать топики в определенном блоге
* Проверяет может ли пользователь создавать топики
*
* @param ModuleUser_EntityUser $oUser Пользователь
* @param ModuleBlog_EntityBlog $oBlog Блог
* @param ModuleTopic_EntityTopicType $oTopicType Объект типа топика
* @return bool
*/
public function CanAddTopic(ModuleUser_EntityUser $oUser, ModuleBlog_EntityBlog $oBlog) {
/**
* Если юзер является создателем блога то разрешаем ему постить
*/
if ($oUser->getId()==$oBlog->getOwnerId()) {
return true;
}
/**
* Если рейтинг юзера больше либо равен порогу постинга в блоге то разрешаем постинг
*/
if ($oUser->getRating()>=$oBlog->getLimitRatingTopic()) {
return true;
}
return false;
public function CanAddTopic($oUser,$oTopicType) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'create_topic',array('callback'=>function($oUser,$aParams) use($that) {
if (!$oUser) {
return false;
}
if ($oUser->isAdministrator()) {
return true;
}
/**
* Проверяем хватает ли рейтинга юзеру чтоб создать топик
*/
if ($oUser->getRating()<=Config::Get('acl.create.topic.limit_rating')) {
return $that->Lang_Get('topic.add.notices.rating_limit');
}
/**
* Проверяем лимит по времени
*/
if (!$that->CanPostTopicTime($oUser)) {
return $that->Lang_Get('topic.add.notices.time_limit');
}
return true;
}));
}
/**
* Проверяет может ли пользователь создавать комментарии
*
* @param ModuleUser_EntityUser $oUser Пользователь
* @param ModuleTopic_EntityTopic|null $oTopic Топик
* @return bool
*/
public function CanPostComment(ModuleUser_EntityUser $oUser,$oTopic=null) {
/**
* Проверяем на закрытый блог
*/
if ($oTopic and !$this->IsAllowShowBlog($oTopic->getBlog(),$oUser)) {
return false;
}
if ($oUser->getRating()>=Config::Get('acl.create.comment.rating')) {
return true;
}
return false;
}
/**
* Проверяет может ли пользователь создавать комментарии по времени(например ограничение максимум 1 коммент в 5 минут)
*
* @param ModuleUser_EntityUser $oUser Пользователь
* @return bool
*/
public function CanPostCommentTime(ModuleUser_EntityUser $oUser) {
if (Config::Get('acl.create.comment.limit_time')>0 and $oUser->getDateCommentLast()) {
$sDateCommentLast=strtotime($oUser->getDateCommentLast());
if ($oUser->getRating()<Config::Get('acl.create.comment.limit_time_rating') and ((time()-$sDateCommentLast)<Config::Get('acl.create.comment.limit_time'))) {
return false;
}
}
return true;
public function CanPostComment($oUser,$oTopic=null) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'create_topic_comment',array('callback'=>function($oUser,$aParams) use($that,$oTopic) {
if (!$oUser) {
return false;
}
if ($oUser->isAdministrator()) {
return true;
}
/**
* Проверяем на закрытый блог
*/
if ($oTopic and !$that->IsAllowShowBlog($oTopic->getBlog(),$oUser)) {
return $that->Lang_Get('topic.comments.notices.acl');
}
/**
* Ограничение на рейтинг
*/
if ($oUser->getRating()<Config::Get('acl.create.comment.rating')) {
return $that->Lang_Get('topic.comments.notices.acl');
}
/**
* Ограничение по времени
*/
if (Config::Get('acl.create.comment.limit_time')>0 and $oUser->getDateCommentLast()) {
$sDateCommentLast=strtotime($oUser->getDateCommentLast());
if ($oUser->getRating()<Config::Get('acl.create.comment.limit_time_rating') and ((time()-$sDateCommentLast)<Config::Get('acl.create.comment.limit_time'))) {
return $that->Lang_Get('topic.comments.notices.limit');
}
}
return true;
}));
}
/**
* Проверяет может ли пользователь создавать топик по времени
@ -116,7 +137,7 @@ class ModuleACL extends Module {
* @param ModuleUser_EntityUser $oUser Пользователь
* @return bool
*/
public function CanPostTopicTime(ModuleUser_EntityUser $oUser) {
public function CanPostTopicTime($oUser) {
// Для администраторов ограничение по времени не действует
if($oUser->isAdministrator()
or Config::Get('acl.create.topic.limit_time')==0
@ -132,13 +153,34 @@ class ModuleACL extends Module {
}
return true;
}
/**
* Проверяет возможность отправки личного сообщения
*
* @param ModuleUser_EntityUser $oUser Пользователь
* @return bool
*/
public function CanAddTalk($oUser) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'create_talk',array('callback'=>function($oUser,$aParams) use($that) {
if (!$oUser) {
return false;
}
if ($oUser->isAdministrator()) {
return true;
}
if (!$that->CanSendTalkTime($oUser)) {
return $that->Lang_Get('talk.notices.time_limit');
}
return true;
}));
}
/**
* Проверяет может ли пользователь отправить инбокс по времени
*
* @param ModuleUser_EntityUser $oUser Пользователь
* @return bool
*/
public function CanSendTalkTime(ModuleUser_EntityUser $oUser) {
public function CanSendTalkTime($oUser) {
// Для администраторов ограничение по времени не действует
if($oUser->isAdministrator()
or Config::Get('acl.create.talk.limit_time')==0
@ -155,39 +197,38 @@ class ModuleACL extends Module {
return true;
}
/**
* Проверяет может ли пользователь создавать комментарии к инбоксу по времени
* Проверяет может ли пользователь создавать комментарии к личным сообщениям
*
* @param ModuleUser_EntityUser $oUser Пользователь
* @return bool
*/
public function CanPostTalkCommentTime(ModuleUser_EntityUser $oUser) {
/**
* Для администраторов ограничение по времени не действует
*/
if($oUser->isAdministrator()
or Config::Get('acl.create.talk_comment.limit_time')==0
or $oUser->getRating()>=Config::Get('acl.create.talk_comment.limit_time_rating'))
return true;
/**
* Проверяем, если топик опубликованный меньше чем acl.create.topic.limit_time секунд назад
*/
$aTalkComments=$this->Comment_GetCommentsByUserId($oUser->getId(),'talk',1,1);
/**
* Если комментариев не было
*/
if(!is_array($aTalkComments) or $aTalkComments['count']==0){
return true;
}
/**
* Достаем последний комментарий
*/
$oComment = array_shift($aTalkComments['collection']);
$sDate = strtotime($oComment->getDate());
public function CanPostTalkComment($oUser) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'create_talk_comment',array('callback'=>function($oUser,$aParams) use($that) {
if (!$oUser) {
return false;
}
if ($oUser->isAdministrator()) {
return true;
}
$aTalkComments=$that->Comment_GetCommentsByUserId($oUser->getId(),'talk',1,1);
/**
* Если комментариев не было
*/
if(!is_array($aTalkComments) or $aTalkComments['count']==0){
return true;
}
/**
* Достаем последний комментарий
*/
$oComment=array_shift($aTalkComments['collection']);
$sDate=strtotime($oComment->getDate());
if($sDate and ((time()-$sDate)<Config::Get('acl.create.talk_comment.limit_time'))) {
return false;
}
return true;
if($sDate and ((time()-$sDate)<Config::Get('acl.create.talk_comment.limit_time'))) {
return $that->Lang_Get('talk.add.notices.time_limit');
}
return true;
}));
}
/**
* Проверяет может ли пользователь голосовать за конкретный комментарий
@ -196,11 +237,38 @@ class ModuleACL extends Module {
* @param ModuleComment_EntityComment $oComment Комментарий
* @return bool
*/
public function CanVoteComment(ModuleUser_EntityUser $oUser, ModuleComment_EntityComment $oComment) {
if ($oUser->getRating()>=Config::Get('acl.vote.comment.rating')) {
return true;
}
return false;
public function CanVoteComment($oUser,$oComment) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'vote_comment',array('callback'=>function($oUser,$aParams) use($that,$oComment) {
if (!$oUser) {
return false;
}
/**
* Голосует автор комментария?
*/
if ($oComment->getUserId()==$oUser->getId()) {
return $that->Lang_Get('vote.notices.error_self');
}
/**
* Пользователь уже голосовал?
*/
if ($oTopicCommentVote=$that->Vote_GetVote($oComment->getId(),'comment',$oUser->getId())) {
return $that->Lang_Get('vote.notices.error_already_voted');
}
/**
* Ограничение по рейтингу
*/
if ($oUser->getRating()<Config::Get('acl.vote.comment.rating')) {
return $that->Lang_Get('vote.notices.error_acl');
}
/**
* Время голосования истекло?
*/
if (strtotime($oComment->getDate())<=time()-Config::Get('acl.vote.comment.limit_time')) {
return $that->Lang_Get('vote.notices.error_time');
}
return true;
}));
}
/**
* Проверяет может ли пользователь голосовать за конкретный блог
@ -209,35 +277,81 @@ class ModuleACL extends Module {
* @param ModuleBlog_EntityBlog $oBlog Блог
* @return bool
*/
public function CanVoteBlog(ModuleUser_EntityUser $oUser, ModuleBlog_EntityBlog $oBlog) {
/**
* Если блог закрытый, проверяем является ли пользователь его читателем
*/
if($oBlog->getType()=='close') {
$oBlogUser = $this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$oUser->getId());
if(!$oBlogUser || $oBlogUser->getUserRole()<ModuleBlog::BLOG_USER_ROLE_GUEST) {
return self::CAN_VOTE_BLOG_ERROR_CLOSE;
}
} elseif($oBlog->getType()=='personal') {
return self::CAN_VOTE_BLOG_FALSE;
}
if ($oUser->getRating()>=Config::Get('acl.vote.blog.rating')) {
return self::CAN_VOTE_BLOG_TRUE;
}
return self::CAN_VOTE_BLOG_FALSE;
public function CanVoteBlog($oUser, $oBlog) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'vote_blog',array('callback'=>function($oUser,$aParams) use($that,$oBlog) {
if (!$oUser) {
return false;
}
/**
* Голосует за свой блог?
*/
if ($oBlog->getOwnerId()==$oUser->getId()) {
return $that->Lang_Get('vote.notices.error_self');
}
/**
* Уже голосовал?
*/
if ($oBlogVote=$that->Vote_GetVote($oBlog->getId(),'blog',$oUser->getId())) {
return $that->Lang_Get('vote.notices.error_already_voted');
}
/**
* Если блог закрытый, проверяем является ли пользователь его читателем
*/
if($oBlog->getType()=='close') {
$oBlogUser = $that->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$oUser->getId());
if(!$oBlogUser || $oBlogUser->getUserRole()<ModuleBlog::BLOG_USER_ROLE_GUEST) {
return $that->Lang_Get('blog.vote.notices.error_close');
}
} elseif($oBlog->getType()=='personal') {
return $that->Lang_Get('vote.notices.error_acl');
}
if ($oUser->getRating()<Config::Get('acl.vote.blog.rating')) {
return $that->Lang_Get('vote.notices.error_acl');
}
return true;
}));
}
/**
* Проверяет может ли пользователь голосовать за конкретный топик
*
* @param ModuleUser_EntityUser $oUser Пользователь
* @param ModuleTopic_EntityTopic $oTopic Топик
* @param int $iValue Направление голосования
* @return bool
*/
public function CanVoteTopic(ModuleUser_EntityUser $oUser, ModuleTopic_EntityTopic $oTopic) {
if ($oUser->getRating()>=Config::Get('acl.vote.topic.rating')) {
return true;
}
return false;
public function CanVoteTopic($oUser, $oTopic, $iValue) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'vote_topic',array('callback'=>function($oUser,$aParams) use($that,$oTopic,$iValue) {
if (!$oUser) {
return false;
}
/**
* Голосует автор топика?
*/
if ($oTopic->getUserId()==$oUser->getId()) {
return $that->Lang_Get('vote.notices.error_self');
}
/**
* Пользователь уже голосовал?
*/
if ($oTopicVote=$that->Vote_GetVote($oTopic->getId(),'topic',$oUser->getId())) {
return $that->Lang_Get('vote.notices.error_already_voted');
}
/**
* Время голосования истекло?
*/
if (strtotime($oTopic->getDateAdd())<=time()-Config::Get('acl.vote.topic.limit_time')) {
return $that->Lang_Get('vote.notices.error_time');
}
/**
* Ограничение по рейтингу
*/
if ($iValue!=0 and $oUser->getRating()<Config::Get('acl.vote.topic.rating')) {
return $that->Lang_Get('vote.notices.error_acl');
}
return true;
}));
}
/**
* Проверяет может ли пользователь голосовать за конкретного пользователя
@ -246,11 +360,32 @@ class ModuleACL extends Module {
* @param ModuleUser_EntityUser $oUserTarget Пользователь за которого голосуем
* @return bool
*/
public function CanVoteUser(ModuleUser_EntityUser $oUser, ModuleUser_EntityUser $oUserTarget) {
if ($oUser->getRating()>=Config::Get('acl.vote.user.rating')) {
return true;
}
return false;
public function CanVoteUser($oUser, $oUserTarget) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'vote_user',array('callback'=>function($oUser,$aParams) use($that,$oUserTarget) {
if (!$oUser) {
return false;
}
/**
* Голосует за себя?
*/
if ($oUserTarget->getId()==$oUser->getId()) {
return $that->Lang_Get('vote.notices.error_self');
}
/**
* Уже голосовал?
*/
if ($oUserVote=$that->Vote_GetVote($oUserTarget->getId(),'user',$oUser->getId())) {
return $that->Lang_Get('vote.notices.error_already_voted');
}
/**
* Ограничение по рейтингу
*/
if ($oUser->getRating()<Config::Get('acl.vote.user.rating')) {
return $that->Lang_Get('vote.notices.error_acl');
}
return true;
}));
}
/**
* Проверяет можно ли юзеру слать инвайты
@ -258,11 +393,20 @@ class ModuleACL extends Module {
* @param ModuleUser_EntityUser $oUser Пользователь
* @return bool
*/
public function CanSendInvite(ModuleUser_EntityUser $oUser) {
if ($this->User_GetCountInviteAvailable($oUser)==0) {
return false;
}
return true;
public function CanSendInvite($oUser) {
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'vote_user',array('callback'=>function($oUser,$aParams) use($that) {
if (!$oUser) {
return false;
}
if ($oUser->isAdministrator()) {
return true;
}
if ($that->User_GetCountInviteAvailable($oUser)==0) {
return $that->Lang_Get('user.settings.invites.available_no');
}
return true;
}));
}
/**
* Проверяет можно или нет юзеру постить в данный блог
@ -275,14 +419,11 @@ class ModuleACL extends Module {
if ($oUser->isAdministrator()) {
return true;
}
if ($oUser->getRating()<=Config::Get('acl.create.topic.limit_rating')) {
return false;
}
if ($oBlog->getOwnerId()==$oUser->getId()) {
return true;
}
if ($oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$oUser->getId())) {
if ($this->ACL_CanAddTopic($oUser,$oBlog) or $oBlogUser->getIsAdministrator() or $oBlogUser->getIsModerator()) {
if ($oUser->getRating()>=$oBlog->getLimitRatingTopic() or $oBlogUser->getIsAdministrator() or $oBlogUser->getIsModerator()) {
return true;
}
}
@ -386,21 +527,27 @@ class ModuleACL extends Module {
* @return bool
*/
public function IsAllowFavouriteComment($oComment,$oUser) {
if (!in_array($oComment->getTargetType(),array('topic'))) {
return false;
}
if (!$oTarget=$oComment->getTarget()) {
return false;
}
if ($oComment->getTargetType()=='topic') {
/**
* Проверяем права на просмотр топика
*/
if (!$this->IsAllowShowTopic($oTarget,$oUser)) {
return false;
}
}
return true;
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'create_comment_favourite',array('callback'=>function($oUser,$aParams) use($that,$oComment) {
if (!$oUser) {
return false;
}
if (!in_array($oComment->getTargetType(),array('topic'))) {
return false;
}
if (!$oTarget=$oComment->getTarget()) {
return false;
}
if ($oComment->getTargetType()=='topic') {
/**
* Проверяем права на просмотр топика
*/
if (!$that->IsAllowShowTopic($oTarget,$oUser)) {
return false;
}
}
return true;
}));
}
/**
* Проверка на удаление комментария
@ -427,35 +574,41 @@ class ModuleACL extends Module {
* @return bool
*/
public function IsAllowDeleteTopic($oTopic,$oUser) {
/**
* Разрешаем если это админ сайта или автор топика
*/
if ($oTopic->getUserId()==$oUser->getId() or $oUser->isAdministrator()) {
return true;
}
/**
* Если автор(смотритель) блога
*/
if ($oTopic->getBlog()->getOwnerId()==$oUser->getId()) {
return true;
}
/**
* Если модер или админ блога
*/
if ($this->User_GetUserCurrent() and $this->User_GetUserCurrent()->getId()==$oUser->getId()) {
/**
* Для авторизованного пользователя данный код будет работать быстрее
*/
if ($oTopic->getBlog()->getUserIsAdministrator() or $oTopic->getBlog()->getUserIsModerator()) {
return true;
}
} else {
$oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oTopic->getBlogId(),$oUser->getId());
if ($oBlogUser and ($oBlogUser->getIsModerator() or $oBlogUser->getIsAdministrator())) {
return true;
}
}
return false;
$that=$this; // fix for PHP < 5.4
return $this->Rbac_IsAllowUser($oUser,'remove_topic',array('callback'=>function($oUser,$aParams) use($that,$oTopic) {
if (!$oUser) {
return false;
}
/**
* Разрешаем если это админ сайта или автор топика
*/
if ($oTopic->getUserId()==$oUser->getId() or $oUser->isAdministrator()) {
return true;
}
/**
* Если автор(смотритель) блога
*/
if ($oTopic->getBlog()->getOwnerId()==$oUser->getId()) {
return true;
}
/**
* Если модер или админ блога
*/
if ($that->User_GetUserCurrent() and $that->User_GetUserCurrent()->getId()==$oUser->getId()) {
/**
* Для авторизованного пользователя данный код будет работать быстрее
*/
if ($oTopic->getBlog()->getUserIsAdministrator() or $oTopic->getBlog()->getUserIsModerator()) {
return true;
}
} else {
$oBlogUser=$that->Blog_GetBlogUserByBlogIdAndUserId($oTopic->getBlogId(),$oUser->getId());
if ($oBlogUser and ($oBlogUser->getIsModerator() or $oBlogUser->getIsAdministrator())) {
return true;
}
}
return false;
}));
}
/**
* Проверка на возможность просмотра топика

View file

@ -727,7 +727,7 @@ class ModuleBlog extends Module {
$aBlogUsers=$this->GetBlogUsersByUserId($oUser->getId());
foreach ($aBlogUsers as $oBlogUser) {
$oBlog=$oBlogUser->getBlog();
if ($this->ACL_CanAddTopic($oUser,$oBlog) or $oBlogUser->getIsAdministrator() or $oBlogUser->getIsModerator()) {
if ($oUser->getRating()>=$oBlog->getLimitRatingTopic() or $oBlogUser->getIsAdministrator() or $oBlogUser->getIsModerator()) {
$aAllowBlogsUser[$oBlog->getId()]=$oBlog;
}
}

View file

@ -106,4 +106,7 @@ class ModuleRbac_EntityPermission extends EntityORM {
return Router::GetPath('admin/users/rbac/permission-remove/'.$this->getId());
}
public function getTitleLang() {
return $this->Lang_Get($this->getTitle());
}
}

View file

@ -1228,6 +1228,7 @@ return array(
'error_type' => 'Неверный тип топика', // TODO: Remove?
'error_favourite_draft' => 'Топик из черновиков нельзя добавить в избранное',
'time_limit' => 'Вам нельзя создавать топики слишком часто',
'rating_limit' => 'Вам не хватает рейтинга для создания топика',
)
),
@ -1979,6 +1980,62 @@ return array(
'all' => 'Все'
),
/**
* Управление правами (RBAC)
*/
'rbac' => array(
'permission' => array(
'create_blog' => array(
'title' => 'Создание блога',
'error' => 'У вас нет прав на создание блога',
),
'vote_blog' => array(
'title' => 'Голосование за блог',
'error' => 'У вас нет прав на голосование за блог',
),
'create_comment_favourite' => array(
'title' => 'Добавление комментария в избранное',
'error' => 'У вас нет прав на добавление в избранное',
),
'vote_comment' => array(
'title' => 'Голосования за комментарии',
'error' => 'У вас нет прав на голосование за комментарии',
),
'create_invite' => array(
'title' => 'Создание инвайта',
'error' => 'У вас нет прав на создание инвайта',
),
'create_talk' => array(
'title' => 'Отправка личного сообщения',
'error' => 'У вас нет прав на отправку личного сообщения',
),
'create_talk_comment' => array(
'title' => 'Комментирование личных сообщений',
'error' => 'У вас нет прав на комментирование личных сообщений',
),
'vote_user' => array(
'title' => 'Голосование за пользователя',
'error' => 'У вас нет прав на голосование за пользователей',
),
'create_topic' => array(
'title' => 'Создание топика',
'error' => 'У вас нет прав на создание топиков',
),
'create_topic_comment' => array(
'title' => 'Комментирование топиков',
'error' => 'У вас нет прав на комментирование топиков',
),
'remove_topic' => array(
'title' => 'Удаление топиков',
'error' => 'У вас нет прав на удаление топиков',
),
'vote_topic' => array(
'title' => 'Голосование за топик',
'error' => 'У вас нет прав на голосования за топики',
),
),
),
/**
* Системные сообщения
*/

View file

@ -681,4 +681,21 @@ CREATE TABLE IF NOT EXISTS `prefix_plugin_version` (
PRIMARY KEY (`id`),
KEY `code` (`code`),
KEY `version` (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 07.10.2014
INSERT INTO `prefix_rbac_permission` (`code`, `plugin`, `title`, `msg_error`, `date_create`, `state`) VALUES
('create_topic', '', 'rbac.permission.create_topic.title', 'rbac.permission.create_topic.error', '2014-08-31 07:59:56', 1),
('create_blog', '', 'rbac.permission.create_blog.title', 'rbac.permission.create_blog.error', '2014-10-02 16:08:54', 1),
('create_topic_comment', '', 'rbac.permission.create_topic_comment.title', 'rbac.permission.create_topic_comment.error', '2014-10-05 11:02:31', 1),
('create_talk', '', 'rbac.permission.create_talk.title', 'rbac.permission.create_talk.error', '2014-10-05 11:54:22', 1),
('create_talk_comment', '', 'rbac.permission.create_talk_comment.title', 'rbac.permission.create_talk_comment.error', '2014-10-05 14:08:15', 1),
('vote_comment', '', 'rbac.permission.vote_comment.title', 'rbac.permission.vote_comment.error', '2014-10-05 14:31:29', 1),
('vote_blog', '', 'rbac.permission.vote_blog.title', 'rbac.permission.vote_blog.error', '2014-10-05 16:51:53', 1),
('vote_topic', '', 'rbac.permission.vote_topic.title', 'rbac.permission.vote_topic.error', '2014-10-05 17:22:56', 1),
('vote_user', '', 'rbac.permission.vote_user.title', 'rbac.permission.vote_user.error', '2014-10-05 17:27:19', 1),
('create_invite', '', 'rbac.permission.create_invite.title', 'rbac.permission.create_invite.error', '2014-10-05 17:28:46', 1),
('create_comment_favourite', '', 'rbac.permission.create_comment_favourite.title', 'rbac.permission.create_comment_favourite.error', '2014-10-05 17:56:23', 1),
('remove_topic', '', 'rbac.permission.remove_topic.title', 'rbac.permission.remove_topic.error', '2014-10-05 18:06:09', 1);