1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-26 11:40:48 +03:00

Лента событий

This commit is contained in:
kirsan 2011-06-06 11:58:19 +00:00
parent 9d321e1ad2
commit e3bf7d1bfd
15 changed files with 1375 additions and 545 deletions

View file

@ -19,52 +19,52 @@
* Класс обработки ajax запросов
*
*/
class ActionAjax extends Action {
class ActionAjax extends Action {
public function Init() {
$this->Viewer_SetResponseAjax('json');
//$this->Security_ValidateSendForm();
$this->oUserCurrent=$this->User_GetUserCurrent();
}
protected function RegisterEvent() {
protected function RegisterEvent() {
$this->AddEventPreg('/^vote$/i','/^comment$/','EventVoteComment');
$this->AddEventPreg('/^vote$/i','/^topic$/','EventVoteTopic');
$this->AddEventPreg('/^vote$/i','/^blog$/','EventVoteBlog');
$this->AddEventPreg('/^vote$/i','/^user$/','EventVoteUser');
$this->AddEventPreg('/^vote$/i','/^question$/','EventVoteQuestion');
$this->AddEventPreg('/^favourite$/i','/^topic$/','EventFavouriteTopic');
$this->AddEventPreg('/^favourite$/i','/^comment$/','EventFavouriteComment');
$this->AddEventPreg('/^favourite$/i','/^talk$/','EventFavouriteTalk');
$this->AddEventPreg('/^stream$/i','/^comment$/','EventStreamComment');
$this->AddEventPreg('/^stream$/i','/^topic$/','EventStreamTopic');
$this->AddEventPreg('/^blogs$/i','/^top$/','EventBlogsTop');
$this->AddEventPreg('/^blogs$/i','/^self$/','EventBlogsSelf');
$this->AddEventPreg('/^blogs$/i','/^join$/','EventBlogsJoin');
$this->AddEventPreg('/^preview$/i','/^text$/','EventPreviewText');
$this->AddEventPreg('/^upload$/i','/^image$/','EventUploadImage');
$this->AddEventPreg('/^autocompleter$/i','/^tag$/','EventAutocompleterTag');
$this->AddEventPreg('/^autocompleter$/i','/^city$/','EventAutocompleterCity');
$this->AddEventPreg('/^autocompleter$/i','/^country$/','EventAutocompleterCountry');
$this->AddEventPreg('/^autocompleter$/i','/^user$/','EventAutocompleterUser');
$this->AddEventPreg('/^comment$/i','/^delete$/','EventCommentDelete');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
*/
/**
* Голосование за комментарий
*
@ -74,38 +74,38 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
if (!($oComment=$this->Comment_GetCommentById(getRequest('idComment',null,'post')))) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_vote_error_noexists'),$this->Lang_Get('error'));
return;
}
if ($oComment->getUserId()==$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_vote_error_self'),$this->Lang_Get('attention'));
return;
}
if ($oTopicCommentVote=$this->Vote_GetVote($oComment->getId(),'comment',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_vote_error_already'),$this->Lang_Get('attention'));
return;
}
if (strtotime($oComment->getDate())<=time()-Config::Get('acl.vote.comment.limit_time')) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_vote_error_time'),$this->Lang_Get('attention'));
return;
}
if (!$this->ACL_CanVoteComment($this->oUserCurrent,$oComment)) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_vote_error_acl'),$this->Lang_Get('attention'));
return;
}
$iValue=getRequest('value',null,'post');
if (!in_array($iValue,array('1','-1'))) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_vote_error_value'),$this->Lang_Get('attention'));
return;
}
$oTopicCommentVote=Engine::GetEntity('Vote');
$oTopicCommentVote->setTargetId($oComment->getId());
$oTopicCommentVote->setTargetType('comment');
@ -116,16 +116,20 @@ class ActionAjax extends Action {
$oTopicCommentVote->setValue($iVal);
$oComment->setCountVote($oComment->getCountVote()+1);
if ($this->Vote_AddVote($oTopicCommentVote) and $this->Comment_UpdateComment($oComment)) {
if ($this->Vote_AddVote($oTopicCommentVote) and $this->Comment_UpdateComment($oComment)) {
$this->Message_AddNoticeSingle($this->Lang_Get('comment_vote_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('iRating',$oComment->getRating());
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oTopicCommentVote->getVoterId(), ModuleStream::EVENT_VOTE_COMMENT, $oComment->getId());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('comment_vote_error'),$this->Lang_Get('error'));
return;
}
}
/**
* Голосование за топик
*
@ -135,38 +139,38 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
if (!($oTopic=$this->Topic_GetTopicById(getRequest('idTopic',null,'post')))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($oTopic->getUserId()==$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_vote_error_self'),$this->Lang_Get('attention'));
return;
}
if ($oTopicVote=$this->Vote_GetVote($oTopic->getId(),'topic',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_vote_error_already'),$this->Lang_Get('attention'));
return;
}
if (strtotime($oTopic->getDateAdd())<=time()-Config::Get('acl.vote.topic.limit_time')) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_vote_error_time'),$this->Lang_Get('attention'));
return;
}
$iValue=getRequest('value',null,'post');
if (!in_array($iValue,array('1','-1','0'))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('attention'));
return;
}
if (!$this->ACL_CanVoteTopic($this->oUserCurrent,$oTopic) and $iValue) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_vote_error_acl'),$this->Lang_Get('attention'));
return;
}
$oTopicVote=Engine::GetEntity('Vote');
$oTopicVote->setTargetId($oTopic->getId());
$oTopicVote->setTargetType('topic');
@ -179,21 +183,25 @@ class ActionAjax extends Action {
}
$oTopicVote->setValue($iVal);
$oTopic->setCountVote($oTopic->getCountVote()+1);
if ($this->Vote_AddVote($oTopicVote) and $this->Topic_UpdateTopic($oTopic)) {
if ($this->Vote_AddVote($oTopicVote) and $this->Topic_UpdateTopic($oTopic)) {
if ($iValue) {
$this->Message_AddNoticeSingle($this->Lang_Get('topic_vote_ok'),$this->Lang_Get('attention'));
} else {
$this->Message_AddNoticeSingle($this->Lang_Get('topic_vote_ok_abstain'),$this->Lang_Get('attention'));
}
$this->Viewer_AssignAjax('iRating',$oTopic->getRating());
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oTopicVote->getVoterId(), ModuleStream::EVENT_VOTE_TOPIC, $oTopic->getId());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
}
}
/**
* Голосование за блог
*
@ -203,22 +211,22 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
if (!($oBlog=$this->Blog_GetBlogById(getRequest('idBlog',null,'post')))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($oBlog->getOwnerId()==$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('blog_vote_error_self'),$this->Lang_Get('attention'));
return;
}
if ($oBlogVote=$this->Vote_GetVote($oBlog->getId(),'blog',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('blog_vote_error_already'),$this->Lang_Get('attention'));
return;
}
switch($this->ACL_CanVoteBlog($this->oUserCurrent,$oBlog)) {
case ModuleACL::CAN_VOTE_BLOG_TRUE:
$iValue=getRequest('value',null,'post');
@ -232,10 +240,14 @@ class ActionAjax extends Action {
$iVal=(float)$this->Rating_VoteBlog($this->oUserCurrent,$oBlog,$iValue);
$oBlogVote->setValue($iVal);
$oBlog->setCountVote($oBlog->getCountVote()+1);
if ($this->Vote_AddVote($oBlogVote) and $this->Blog_UpdateBlog($oBlog)) {
if ($this->Vote_AddVote($oBlogVote) and $this->Blog_UpdateBlog($oBlog)) {
$this->Viewer_AssignAjax('iCountVote',$oBlog->getCountVote());
$this->Viewer_AssignAjax('iRating',$oBlog->getRating());
$this->Message_AddNoticeSingle($this->Lang_Get('blog_vote_ok'),$this->Lang_Get('attention'));
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oBlogVote->getVoterId(), ModuleStream::EVENT_VOTE_BLOG, $oBlog->getId());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('attention'));
return;
@ -257,9 +269,9 @@ class ActionAjax extends Action {
break;
}
}
/**
* Голосование за блог
*
@ -269,34 +281,34 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
if (!($oUser=$this->User_GetUserById(getRequest('idUser',null,'post')))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($oUser->getId()==$this->oUserCurrent->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('user_vote_error_self'),$this->Lang_Get('attention'));
return;
}
if ($oUserVote=$this->Vote_GetVote($oUser->getId(),'user',$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('user_vote_error_already'),$this->Lang_Get('attention'));
return;
}
if (!$this->ACL_CanVoteUser($this->oUserCurrent,$oUser)) {
$this->Message_AddErrorSingle($this->Lang_Get('user_vote_error_acl'),$this->Lang_Get('attention'));
return;
}
$iValue=getRequest('value',null,'post');
if (!in_array($iValue,array('1','-1'))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('attention'));
return;
}
$oUserVote=Engine::GetEntity('Vote');
$oUserVote->setTargetId($oUser->getId());
$oUserVote->setTargetType('user');
@ -307,18 +319,22 @@ class ActionAjax extends Action {
$oUserVote->setValue($iVal);
//$oUser->setRating($oUser->getRating()+$iValue);
$oUser->setCountVote($oUser->getCountVote()+1);
if ($this->Vote_AddVote($oUserVote) and $this->User_Update($oUser)) {
$this->Message_AddNoticeSingle($this->Lang_Get('user_vote_ok'),$this->Lang_Get('attention'));
if ($this->Vote_AddVote($oUserVote) and $this->User_Update($oUser)) {
$this->Message_AddNoticeSingle($this->Lang_Get('user_vote_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('iRating',$oUser->getRating());
$this->Viewer_AssignAjax('iSkill',$oUser->getSkill());
$this->Viewer_AssignAjax('iCountVote',$oUser->getCountVote());
$this->Viewer_AssignAjax('iCountVote',$oUser->getCountVote());
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oUserVote->getVoterId(), ModuleStream::EVENT_VOTE_USER, $oUser->getId());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
}
/**
* Голосование за вариант ответа в опросе
*
@ -328,31 +344,31 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
$idAnswer=getRequest('idAnswer',null,'post');
$idTopic=getRequest('idTopic',null,'post');
if (!($oTopic=$this->Topic_GetTopicById($idTopic))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($oTopic->getType()!='question') {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($oTopicQuestionVote=$this->Topic_GetTopicQuestionVote($oTopic->getId(),$this->oUserCurrent->getId())) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_question_vote_already'),$this->Lang_Get('error'));
return;
}
$aAnswer=$oTopic->getQuestionAnswers();
if (!isset($aAnswer[$idAnswer]) and $idAnswer!=-1) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($idAnswer==-1) {
$oTopic->setQuestionCountVoteAbstain($oTopic->getQuestionCountVoteAbstain()+1);
} else {
@ -368,14 +384,14 @@ class ActionAjax extends Action {
if ($this->Topic_AddTopicQuestionVote($oTopicQuestionVote) and $this->Topic_updateTopic($oTopic)) {
$this->Message_AddNoticeSingle($this->Lang_Get('topic_question_vote_ok'),$this->Lang_Get('attention'));
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('oTopic',$oTopic);
$oViewer->Assign('oTopic',$oTopic);
$this->Viewer_AssignAjax('sText',$oViewer->Fetch("topic_question.tpl"));
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
}
/**
* Обработка избранного - топик
*
@ -385,19 +401,19 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
$iType=getRequest('type',null,'post');
if (!in_array($iType,array('1','0'))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if (!($oTopic=$this->Topic_GetTopicById(getRequest('idTopic',null,'post')))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
$oFavouriteTopic=$this->Topic_GetFavouriteTopic($oTopic->getId(),$this->oUserCurrent->getId());
if (!$oFavouriteTopic and $iType) {
$oFavouriteTopicNew=Engine::GetEntity('Favourite',
@ -408,35 +424,35 @@ class ActionAjax extends Action {
'target_publish' => $oTopic->getPublish()
)
);
if ($this->Topic_AddFavouriteTopic($oFavouriteTopicNew)) {
$this->Message_AddNoticeSingle($this->Lang_Get('topic_favourite_add_ok'),$this->Lang_Get('attention'));
if ($this->Topic_AddFavouriteTopic($oFavouriteTopicNew)) {
$this->Message_AddNoticeSingle($this->Lang_Get('topic_favourite_add_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('bState',true);
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
}
if (!$oFavouriteTopic and !$iType) {
if (!$oFavouriteTopic and !$iType) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_favourite_add_no'),$this->Lang_Get('error'));
return;
}
if ($oFavouriteTopic and $iType) {
if ($oFavouriteTopic and $iType) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_favourite_add_already'),$this->Lang_Get('error'));
return;
}
if ($oFavouriteTopic and !$iType) {
if ($this->Topic_DeleteFavouriteTopic($oFavouriteTopic)) {
if ($this->Topic_DeleteFavouriteTopic($oFavouriteTopic)) {
$this->Message_AddNoticeSingle($this->Lang_Get('topic_favourite_del_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('bState',false);
} else {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
}
}
}
/**
* Обработка избранного - комментарий
*
@ -446,18 +462,18 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
$iType=getRequest('type',null,'post');
if (!in_array($iType,array('1','0'))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if (!($oComment=$this->Comment_GetCommentById(getRequest('idComment',null,'post')))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
$oFavouriteComment=$this->Comment_GetFavouriteComment($oComment->getId(),$this->oUserCurrent->getId());
if (!$oFavouriteComment and $iType) {
$oFavouriteCommentNew=Engine::GetEntity('Favourite',
@ -468,7 +484,7 @@ class ActionAjax extends Action {
'target_publish' => $oComment->getPublish()
)
);
if ($this->Comment_AddFavouriteComment($oFavouriteCommentNew)) {
if ($this->Comment_AddFavouriteComment($oFavouriteCommentNew)) {
$this->Message_AddNoticeSingle($this->Lang_Get('comment_favourite_add_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('bState',true);
} else {
@ -476,16 +492,16 @@ class ActionAjax extends Action {
return;
}
}
if (!$oFavouriteComment and !$iType) {
if (!$oFavouriteComment and !$iType) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_favourite_add_no'),$this->Lang_Get('error'));
return;
}
if ($oFavouriteComment and $iType) {
if ($oFavouriteComment and $iType) {
$this->Message_AddErrorSingle($this->Lang_Get('comment_favourite_add_already'),$this->Lang_Get('error'));
return;
}
if ($oFavouriteComment and !$iType) {
if ($this->Comment_DeleteFavouriteComment($oFavouriteComment)) {
if ($this->Comment_DeleteFavouriteComment($oFavouriteComment)) {
$this->Message_AddNoticeSingle($this->Lang_Get('comment_favourite_del_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('bState',false);
} else {
@ -494,8 +510,8 @@ class ActionAjax extends Action {
}
}
}
/**
* Обработка избранного - письмо
*
@ -505,19 +521,19 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
$iType=getRequest('type',null,'post');
$iType=getRequest('type',null,'post');
if (!in_array($iType,array('1','0'))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if (!($oTalk=$this->Talk_GetTalkById(getRequest('idTalk',null,'post')))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
$oFavouriteTalk=$this->Talk_GetFavouriteTalk($oTalk->getId(),$this->oUserCurrent->getId());
if (!$oFavouriteTalk and $iType) {
$oFavouriteTalkNew=Engine::GetEntity('Favourite',
@ -528,7 +544,7 @@ class ActionAjax extends Action {
'target_publish' => '1'
)
);
if ($this->Talk_AddFavouriteTalk($oFavouriteTalkNew)) {
if ($this->Talk_AddFavouriteTalk($oFavouriteTalkNew)) {
$this->Message_AddNoticeSingle($this->Lang_Get('talk_favourite_add_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('bState',true);
} else {
@ -536,16 +552,16 @@ class ActionAjax extends Action {
return;
}
}
if (!$oFavouriteTalk and !$iType) {
if (!$oFavouriteTalk and !$iType) {
$this->Message_AddErrorSingle($this->Lang_Get('talk_favourite_add_no'),$this->Lang_Get('error'));
return;
}
if ($oFavouriteTalk and $iType) {
if ($oFavouriteTalk and $iType) {
$this->Message_AddErrorSingle($this->Lang_Get('talk_favourite_add_already'),$this->Lang_Get('error'));
return;
}
if ($oFavouriteTalk and !$iType) {
if ($this->Talk_DeleteFavouriteTalk($oFavouriteTalk)) {
if ($this->Talk_DeleteFavouriteTalk($oFavouriteTalk)) {
$this->Message_AddNoticeSingle($this->Lang_Get('talk_favourite_del_ok'),$this->Lang_Get('attention'));
$this->Viewer_AssignAjax('bState',false);
} else {
@ -553,10 +569,10 @@ class ActionAjax extends Action {
return;
}
}
}
/**
* Обработка получения последних комментов
*
@ -564,16 +580,16 @@ class ActionAjax extends Action {
protected function EventStreamComment() {
if ($aComments=$this->Comment_GetCommentsOnline('topic',Config::Get('block.stream.row'))) {
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aComments',$aComments);
$oViewer->Assign('aComments',$aComments);
$sTextResult=$oViewer->Fetch("block.stream_comment.tpl");
$this->Viewer_AssignAjax('sText',$sTextResult);
} else {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('block_stream_comments_no'),$this->Lang_Get('attention'));
return;
}
}
/**
* Обработка получения последних топиков
*
@ -581,16 +597,16 @@ class ActionAjax extends Action {
protected function EventStreamTopic() {
if ($oTopics=$this->Topic_GetTopicsLast(Config::Get('block.stream.row'))) {
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('oTopics',$oTopics);
$oViewer->Assign('oTopics',$oTopics);
$sTextResult=$oViewer->Fetch("block.stream_topic.tpl");
$this->Viewer_AssignAjax('sText',$sTextResult);
} else {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('block_stream_topics_no'),$this->Lang_Get('attention'));
return;
}
}
/**
* Обработка получения TOP блогов
*
@ -599,15 +615,15 @@ class ActionAjax extends Action {
if ($aResult=$this->Blog_GetBlogsRating(1,Config::Get('block.blogs.row'))) {
$aBlogs=$aResult['collection'];
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aBlogs',$aBlogs);
$oViewer->Assign('aBlogs',$aBlogs);
$sTextResult=$oViewer->Fetch("block.blogs_top.tpl");
$this->Viewer_AssignAjax('sText',$sTextResult);
} else {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
}
/**
* Обработка получения своих блогов
*
@ -617,18 +633,18 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
if ($aBlogs=$this->Blog_GetBlogsRatingSelf($this->oUserCurrent->getId(),Config::Get('block.blogs.row'))) {
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aBlogs',$aBlogs);
$oViewer->Assign('aBlogs',$aBlogs);
$sTextResult=$oViewer->Fetch("block.blogs_top.tpl");
$this->Viewer_AssignAjax('sText',$sTextResult);
} else {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('block_blogs_self_error'),$this->Lang_Get('attention'));
return;
}
}
}
/**
* Обработка получения подключенных блогов
*
@ -638,18 +654,18 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
if ($aBlogs=$this->Blog_GetBlogsRatingJoin($this->oUserCurrent->getId(),Config::Get('block.blogs.row'))) {
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aBlogs',$aBlogs);
$oViewer->Assign('aBlogs',$aBlogs);
$sTextResult=$oViewer->Fetch("block.blogs_top.tpl");
$this->Viewer_AssignAjax('sText',$sTextResult);
} else {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('block_blogs_join_error'),$this->Lang_Get('attention'));
return;
}
}
}
/**
* Предпросмотр текста
*
@ -659,7 +675,7 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
$sText=getRequest('text',null,'post');
$bSave=getRequest('save',null,'post');
@ -670,8 +686,8 @@ class ActionAjax extends Action {
}
$this->Viewer_AssignAjax('sText',$sTextResult);
}
/**
* Загрузка изображения
*
@ -682,11 +698,11 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
$aForm=getRequest('value',null,'post');
$sFile=null;
if (is_uploaded_file($_FILES['img_file']['tmp_name'])) {
if(!$sFile=$this->Topic_UploadTopicImageFile($_FILES['img_file'],$this->oUserCurrent)) {
if(!$sFile=$this->Topic_UploadTopicImageFile($_FILES['img_file'],$this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Lang_Get('uploadimg_file_error'),$this->Lang_Get('error'));
return;
}
@ -697,30 +713,30 @@ class ActionAjax extends Action {
break;
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR_READ):
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR_READ):
$this->Message_AddErrorSingle($this->Lang_Get('uploadimg_url_error_read'),$this->Lang_Get('error'));
return;
return;
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR_SIZE):
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR_SIZE):
$this->Message_AddErrorSingle($this->Lang_Get('uploadimg_url_error_size'),$this->Lang_Get('error'));
return;
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR_TYPE):
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR_TYPE):
$this->Message_AddErrorSingle($this->Lang_Get('uploadimg_url_error_type'),$this->Lang_Get('error'));
return;
default:
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR):
case ($sFile==ModuleImage::UPLOAD_IMAGE_ERROR):
$this->Message_AddErrorSingle($this->Lang_Get('uploadimg_url_error'),$this->Lang_Get('error'));
return;
}
}
if ($sFile) {
if ($sFile) {
$sText=$this->Image_BuildHTML($sFile, $_REQUEST);
$this->Viewer_AssignAjax('sText',$sText);
}
}
/**
* Автоподставновка тегов
*
@ -729,7 +745,7 @@ class ActionAjax extends Action {
if (!($sValue=getRequest('value',null,'post'))) {
return ;
}
$aItems=array();
$aTags=$this->Topic_GetTopicTagsByLike($sValue,10);
foreach ($aTags as $oTag) {
@ -737,7 +753,7 @@ class ActionAjax extends Action {
}
$this->Viewer_AssignAjax('aItems',$aItems);
}
/**
* Автоподставновка городов
*
@ -746,7 +762,7 @@ class ActionAjax extends Action {
if (!($sValue=getRequest('value',null,'post'))) {
return ;
}
$aItems=array();
$aCity=$this->User_GetCityByNameLike($sValue,10);
foreach ($aCity as $oCity) {
@ -754,7 +770,7 @@ class ActionAjax extends Action {
}
$this->Viewer_AssignAjax('aItems',$aItems);
}
/**
* Автоподставновка стран
*
@ -763,7 +779,7 @@ class ActionAjax extends Action {
if (!($sValue=getRequest('value',null,'post'))) {
return ;
}
$aItems=array();
$aCountry=$this->User_GetCountryByNameLike($sValue,10);
foreach ($aCountry as $oCountry) {
@ -771,7 +787,7 @@ class ActionAjax extends Action {
}
$this->Viewer_AssignAjax('aItems',$aItems);
}
/**
* Автоподставновка пользователей
*
@ -780,7 +796,7 @@ class ActionAjax extends Action {
if (!($sValue=getRequest('value',null,'post'))) {
return ;
}
$aItems=array();
$aUsers=$this->User_GetUsersByLoginLike($sValue,10);
foreach ($aUsers as $oUser) {
@ -788,8 +804,8 @@ class ActionAjax extends Action {
}
$this->Viewer_AssignAjax('aItems',$aItems);
}
/**
* Удаление/восстановление комментария
*
@ -799,19 +815,19 @@ class ActionAjax extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('not_access'),$this->Lang_Get('error'));
return;
}
$idComment=getRequest('idComment',null,'post');
if (!($oComment=$this->Comment_GetCommentById($idComment))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
$oComment->setDelete(($oComment->getDelete()+1)%2);
if (!$this->Comment_UpdateCommentStatus($oComment)) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($bState=(bool)$oComment->getDelete()) {
$sMsg=$this->Lang_Get('comment_delete_ok');
$sTextToggle=$this->Lang_Get('comment_repair');
@ -823,8 +839,8 @@ class ActionAjax extends Action {
$this->Viewer_AssignAjax('bState',$bState);
$this->Viewer_AssignAjax('sTextToggle',$sTextToggle);
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -32,21 +32,21 @@ class ActionProfile extends Action {
* @var unknown_type
*/
protected $oUserProfile;
public function Init() {
}
protected function RegisterEvent() {
protected function RegisterEvent() {
$this->AddEvent('friendoffer','EventFriendOffer');
$this->AddEvent('ajaxfriendadd', 'EventAjaxFriendAdd');
$this->AddEvent('ajaxfrienddelete', 'EventAjaxFriendDelete');
$this->AddEvent('ajaxfriendaccept', 'EventAjaxFriendAccept');
$this->AddEventPreg('/^.+$/i','/^(whois)?$/i','EventWhois');
$this->AddEventPreg('/^.+$/i','/^favourites$/i','/^comments$/i','/^(page(\d+))?$/i','EventFavouriteComments');
$this->AddEventPreg('/^.+$/i','/^favourites$/i','/^(page(\d+))?$/i','EventFavourite');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
@ -55,33 +55,33 @@ class ActionProfile extends Action {
* Выводит список избранноего юзера
*
*/
protected function EventFavourite() {
protected function EventFavourite() {
/**
* Получаем логин из УРЛа
*/
$sUserLogin=$this->sCurrentEvent;
$sUserLogin=$this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
return parent::EventNotFound();
}
}
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(1,2) ? $this->GetParamEventMatch(1,2) : 1;
*/
$iPage=$this->GetParamEventMatch(1,2) ? $this->GetParamEventMatch(1,2) : 1;
/**
* Получаем список избранных топиков
*/
$aResult=$this->Topic_GetTopicsFavouriteByUserId($this->oUserProfile->getId(),$iPage,Config::Get('module.topic.per_page'));
*/
$aResult=$this->Topic_GetTopicsFavouriteByUserId($this->oUserProfile->getId(),$iPage,Config::Get('module.topic.per_page'));
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),4,Router::GetPath('profile').$this->oUserProfile->getLogin().'/favourites');
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),4,Router::GetPath('profile').$this->oUserProfile->getLogin().'/favourites');
/**
* Загружаем переменные в шаблон
*/
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_AddHtmlTitle($this->Lang_Get('user_menu_profile').' '.$this->oUserProfile->getLogin());
@ -95,33 +95,33 @@ class ActionProfile extends Action {
* Выводит список избранноего юзера
*
*/
protected function EventFavouriteComments() {
protected function EventFavouriteComments() {
/**
* Получаем логин из УРЛа
*/
$sUserLogin=$this->sCurrentEvent;
$sUserLogin=$this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
return parent::EventNotFound();
}
}
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(2,2) ? $this->GetParamEventMatch(2,2) : 1;
*/
$iPage=$this->GetParamEventMatch(2,2) ? $this->GetParamEventMatch(2,2) : 1;
/**
* Получаем список избранных комментариев
*/
$aResult=$this->Comment_GetCommentsFavouriteByUserId($this->oUserProfile->getId(),$iPage,Config::Get('module.comment.per_page'));
*/
$aResult=$this->Comment_GetCommentsFavouriteByUserId($this->oUserProfile->getId(),$iPage,Config::Get('module.comment.per_page'));
$aComments=$aResult['collection'];
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.comment.per_page'),4,Router::GetPath('profile').$this->oUserProfile->getLogin().'/favourites/comments');
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.comment.per_page'),4,Router::GetPath('profile').$this->oUserProfile->getLogin().'/favourites/comments');
/**
* Загружаем переменные в шаблон
*/
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aComments',$aComments);
$this->Viewer_AddHtmlTitle($this->Lang_Get('user_menu_profile').' '.$this->oUserProfile->getLogin());
@ -130,7 +130,7 @@ class ActionProfile extends Action {
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('comments');
}
}
/**
* Показывает инфу профиля
*
@ -139,36 +139,36 @@ class ActionProfile extends Action {
/**
* Получаем логин из УРЛа
*/
$sUserLogin=$this->sCurrentEvent;
$sUserLogin=$this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
return parent::EventNotFound();
}
/**
* Получаем список друзей
*/
$aUsersFriend=$this->User_GetUsersFriend($this->oUserProfile->getId());
if (Config::Get('general.reg.invite')) {
/**
* Получаем список тех кого пригласил юзер
*/
$aUsersInvite=$this->User_GetUsersInvite($this->oUserProfile->getId());
$aUsersInvite=$this->User_GetUsersInvite($this->oUserProfile->getId());
$this->Viewer_Assign('aUsersInvite',$aUsersInvite);
/**
* Получаем того юзера, кто пригласил текущего
*/
$oUserInviteFrom=$this->User_GetUserInviteFrom($this->oUserProfile->getId());
$oUserInviteFrom=$this->User_GetUserInviteFrom($this->oUserProfile->getId());
$this->Viewer_Assign('oUserInviteFrom',$oUserInviteFrom);
}
}
/**
* Получаем список юзеров блога
*/
$aBlogUsers=$this->Blog_GetBlogUsersByUserId($this->oUserProfile->getId(),ModuleBlog::BLOG_USER_ROLE_USER);
$aBlogModerators=$this->Blog_GetBlogUsersByUserId($this->oUserProfile->getId(),ModuleBlog::BLOG_USER_ROLE_MODERATOR);
$aBlogAdministrators=$this->Blog_GetBlogUsersByUserId($this->oUserProfile->getId(),ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR);
$aBlogAdministrators=$this->Blog_GetBlogUsersByUserId($this->oUserProfile->getId(),ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR);
/**
* Получаем список блогов которые создал юзер
*/
@ -176,7 +176,7 @@ class ActionProfile extends Action {
/**
* Вызов хуков
*/
$this->Hook_Run('profile_whois_show',array("oUserProfile"=>$this->oUserProfile));
$this->Hook_Run('profile_whois_show',array("oUserProfile"=>$this->oUserProfile));
/**
* Загружаем переменные в шаблон
*/
@ -184,28 +184,28 @@ class ActionProfile extends Action {
$this->Viewer_Assign('aBlogModerators',$aBlogModerators);
$this->Viewer_Assign('aBlogAdministrators',$aBlogAdministrators);
$this->Viewer_Assign('aBlogsOwner',$aBlogsOwner);
$this->Viewer_Assign('aUsersFriend',$aUsersFriend);
$this->Viewer_Assign('aUsersFriend',$aUsersFriend);
$this->Viewer_AddHtmlTitle($this->Lang_Get('user_menu_profile').' '.$this->oUserProfile->getLogin());
$this->Viewer_AddHtmlTitle($this->Lang_Get('user_menu_profile_whois'));
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('whois');
}
$this->SetTemplateAction('whois');
}
/**
* Добавление пользователя в друзья, по отправленной заявке
*/
public function EventFriendOffer() {
require_once Config::Get('path.root.engine').'/lib/external/XXTEA/encrypt.php';
public function EventFriendOffer() {
require_once Config::Get('path.root.engine').'/lib/external/XXTEA/encrypt.php';
$sUserId=xxtea_decrypt(base64_decode(rawurldecode(getRequest('code'))), Config::Get('module.talk.encrypt'));
if (!$sUserId) {
return $this->EventNotFound();
}
list($sUserId,)=explode('_',$sUserId,2);
$sAction=$this->GetParam(0);
/**
* Получаем текущего пользователя
*/
@ -213,7 +213,7 @@ class ActionProfile extends Action {
return $this->EventNotFound();
}
$this->oUserCurrent = $this->User_GetUserCurrent();
/**
* Получаем объект пользователя приславшего заявку,
* если пользователь не найден, переводим в раздел сообщений (Talk) -
@ -225,16 +225,16 @@ class ActionProfile extends Action {
Router::Location(Router::GetPath('talk'));
return ;
}
/**
* Получаем связь дружбы из базы данных.
* Если связь не найдена либо статус отличен от OFFER,
* переходим в раздел Talk и возвращаем сообщение об ошибке
*/
$oFriend=$this->User_GetFriend($this->oUserCurrent->getId(),$oUser->getId(),0);
if(!$oFriend
if(!$oFriend
|| !in_array(
$oFriend->getFriendStatus(),
$oFriend->getFriendStatus(),
array(
ModuleUser::USER_FRIEND_OFFER+ModuleUser::USER_FRIEND_NULL,
)
@ -244,11 +244,11 @@ class ActionProfile extends Action {
? $this->Lang_Get('user_friend_offer_already_done')
: $this->Lang_Get('user_friend_offer_not_found');
$this->Message_AddError($sMessage,$this->Lang_Get('error'),true);
Router::Location(Router::GetPath('talk'));
return ;
}
return ;
}
/**
* Устанавливаем новый статус связи
*/
@ -257,12 +257,12 @@ class ActionProfile extends Action {
? ModuleUser::USER_FRIEND_ACCEPT
: ModuleUser::USER_FRIEND_REJECT
);
if ($this->User_UpdateFriend($oFriend)) {
$sMessage=($sAction=='accept')
? $this->Lang_Get('user_friend_add_ok')
: $this->Lang_Get('user_friend_offer_reject');
$this->Message_AddNoticeSingle($sMessage,$this->Lang_Get('attention'),true);
$this->NoticeFriendOffer($oUser,$sAction);
} else {
@ -274,20 +274,20 @@ class ActionProfile extends Action {
}
Router::Location(Router::GetPath('talk'));
}
public function EventAjaxFriendAccept() {
$this->Viewer_SetResponseAjax('json');
$sUserId=getRequest('idUser',null,'post');
/**
* Если пользователь не авторизирован, возвращаем ошибку
*/
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle(
$this->Lang_Get('need_authorization'),
$this->Lang_Get('error')
);
return;
return;
}
$this->oUserCurrent=$this->User_GetUserCurrent();
/**
@ -300,43 +300,43 @@ class ActionProfile extends Action {
);
return;
}
/**
* Если пользователь не найден, возвращаем ошибку
*/
if( !$oUser=$this->User_GetUserById($sUserId) ) {
if( !$oUser=$this->User_GetUserById($sUserId) ) {
$this->Message_AddErrorSingle(
$this->Lang_Get('user_not_found'),
$this->Lang_Get('error')
);
return;
return;
}
$this->oUserProfile=$oUser;
/**
* Получаем статус дружбы между пользователями
*/
$oFriend=$this->User_GetFriend($oUser->getId(),$this->oUserCurrent->getId());
$oFriend=$this->User_GetFriend($oUser->getId(),$this->oUserCurrent->getId());
/**
* При попытке потдвердить ранее отклоненную заявку,
* проверяем, чтобы изменяющий был принимающей стороной
*/
if($oFriend
&& ($oFriend->getStatusFrom()==ModuleUser::USER_FRIEND_OFFER||$oFriend->getStatusFrom()==ModuleUser::USER_FRIEND_ACCEPT)
&& ($oFriend->getStatusTo()==ModuleUser::USER_FRIEND_REJECT||$oFriend->getStatusTo()==ModuleUser::USER_FRIEND_NULL)
if($oFriend
&& ($oFriend->getStatusFrom()==ModuleUser::USER_FRIEND_OFFER||$oFriend->getStatusFrom()==ModuleUser::USER_FRIEND_ACCEPT)
&& ($oFriend->getStatusTo()==ModuleUser::USER_FRIEND_REJECT||$oFriend->getStatusTo()==ModuleUser::USER_FRIEND_NULL)
&& $oFriend->getUserTo()==$this->oUserCurrent->getId()) {
/**
* Меняем статус с отвергнутое, на акцептованное
* Меняем статус с отвергнутое, на акцептованное
*/
$oFriend->setStatusByUserId(ModuleUser::USER_FRIEND_ACCEPT,$this->oUserCurrent->getId());
if($this->User_UpdateFriend($oFriend)) {
$this->Message_AddNoticeSingle($this->Lang_Get('user_friend_add_ok'),$this->Lang_Get('attention'));
$this->NoticeFriendOffer($oUser,'accept');
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriend);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
} else {
$this->Message_AddErrorSingle(
$this->Lang_Get('system_error'),
@ -350,7 +350,7 @@ class ActionProfile extends Action {
$this->Lang_Get('system_error'),
$this->Lang_Get('error')
);
return;
return;
}
/**
@ -372,7 +372,7 @@ class ActionProfile extends Action {
if(!Config::Get("module.user.friend_notice.{$sAction}")) {
return false;
}
$sTitle=$this->Lang_Get("user_friend_{$sAction}_notice_title");
$sText=$this->Lang_Get(
"user_friend_{$sAction}_notice_text",
@ -383,7 +383,7 @@ class ActionProfile extends Action {
$oTalk=$this->Talk_SendTalk($sTitle,$sText,$this->oUserCurrent,array($oUser),false,false);
$this->Talk_DeleteTalkUserByArray($oTalk->getId(),$this->oUserCurrent->getId());
}
public function EventAjaxFriendAdd() {
$this->Viewer_SetResponseAjax('json');
$sUserId=getRequest('idUser');
@ -397,10 +397,10 @@ class ActionProfile extends Action {
$this->Lang_Get('need_authorization'),
$this->Lang_Get('error')
);
return;
return;
}
$this->oUserCurrent=$this->User_GetUserCurrent();
/**
* При попытке добавить в друзья себя, возвращаем ошибку
*/
@ -411,16 +411,16 @@ class ActionProfile extends Action {
);
return;
}
/**
* Если пользователь не найден, возвращаем ошибку
*/
if( !$oUser=$this->User_GetUserById($sUserId) ) {
if( !$oUser=$this->User_GetUserById($sUserId) ) {
$this->Message_AddErrorSingle(
$this->Lang_Get('user_not_found'),
$this->Lang_Get('error')
);
return;
return;
}
$this->oUserProfile=$oUser;
/**
@ -430,12 +430,12 @@ class ActionProfile extends Action {
/**
* Если связи ранее не было в базе данных, добавляем новую
*/
if( !$oFriend ) {
if( !$oFriend ) {
$this->SubmitAddFriend($oUser,$sUserText,$oFriend);
return;
return;
}
/**
* Если статус связи соответствует статусам отправленной и акцептованной заявки,
* Если статус связи соответствует статусам отправленной и акцептованной заявки,
* то предупреждаем что этот пользователь уже является нашим другом
*/
if($oFriend->getFriendStatus()==ModuleUser::USER_FRIEND_OFFER + ModuleUser::USER_FRIEND_ACCEPT) {
@ -446,40 +446,41 @@ class ActionProfile extends Action {
return;
}
/**
* Если пользователь ранее отклонил нашу заявку,
* Если пользователь ранее отклонил нашу заявку,
* возвращаем сообщение об ошибке
*/
if($oFriend->getUserFrom()==$this->oUserCurrent->getId()
if($oFriend->getUserFrom()==$this->oUserCurrent->getId()
&& $oFriend->getStatusTo()==ModuleUser::USER_FRIEND_REJECT ) {
$this->Message_AddErrorSingle(
$this->Lang_Get('user_friend_offer_reject'),
$this->Lang_Get('error')
);
return;
return;
}
/**
* Если дружба была удалена, то проверяем кто ее удалил
* и разрешаем восстановить только удалившему
*/
if($oFriend->getFriendStatus()>ModuleUser::USER_FRIEND_DELETE
if($oFriend->getFriendStatus()>ModuleUser::USER_FRIEND_DELETE
&& $oFriend->getFriendStatus()<ModuleUser::USER_FRIEND_REJECT) {
/**
* Определяем статус связи текущего пользователя
*/
$iStatusCurrent = $oFriend->getStatusByUserId($this->oUserCurrent->getId());
if($iStatusCurrent==ModuleUser::USER_FRIEND_DELETE) {
/**
* Меняем статус с удаленного, на акцептованное
* Меняем статус с удаленного, на акцептованное
*/
$oFriend->setStatusByUserId(ModuleUser::USER_FRIEND_ACCEPT,$this->oUserCurrent->getId());
if($this->User_UpdateFriend($oFriend)) {
$this->Stream_write($oFriend->getUserFrom(), ModuleStream::EVENT_MAKE_FRIENDS, $oFriend->getUserTo());
$this->Message_AddNoticeSingle($this->Lang_Get('user_friend_add_ok'),$this->Lang_Get('attention'));
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriend);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
} else {
$this->Message_AddErrorSingle(
$this->Lang_Get('system_error'),
@ -492,7 +493,7 @@ class ActionProfile extends Action {
$this->Lang_Get('user_friend_add_deleted'),
$this->Lang_Get('error')
);
return;
return;
}
}
}
@ -515,27 +516,27 @@ class ActionProfile extends Action {
$oViewerLocal->Assign('USER_FRIEND_ACCEPT',ModuleUser::USER_FRIEND_ACCEPT);
$oViewerLocal->Assign('USER_FRIEND_REJECT',ModuleUser::USER_FRIEND_REJECT);
$oViewerLocal->Assign('USER_FRIEND_DELETE',ModuleUser::USER_FRIEND_DELETE);
return $oViewerLocal;
}
protected function SubmitAddFriend($oUser,$sUserText,$oFriend=null) {
$sUserText=$this->Text_Parser($sUserText);
$oFriendNew=Engine::GetEntity('User_Friend');
$oFriendNew->setUserTo($oUser->getId());
$oFriendNew->setUserFrom($this->oUserCurrent->getId());
// Добавляем заявку в друзья
$oFriendNew->setStatusFrom(ModuleUser::USER_FRIEND_OFFER);
$oFriendNew->setStatusTo(ModuleUser::USER_FRIEND_NULL);
$bStateError=($oFriend)
? !$this->User_UpdateFriend($oFriendNew)
: !$this->User_AddFriend($oFriendNew);
if ( !$bStateError ) {
$this->Message_AddNoticeSingle($this->Lang_Get('user_friend_offer_send'),$this->Lang_Get('attention'));
$sTitle=$this->Lang_Get(
'user_friend_offer_title',
array(
@ -543,16 +544,16 @@ class ActionProfile extends Action {
'friend'=>$oUser->getLogin()
)
);
require_once Config::Get('path.root.engine').'/lib/external/XXTEA/encrypt.php';
$sCode=$this->oUserCurrent->getId().'_'.$oUser->getId();
$sCode=rawurlencode(base64_encode(xxtea_encrypt($sCode, Config::Get('module.talk.encrypt'))));
$aPath=array(
'accept'=>Router::GetPath('profile').'friendoffer/accept/?code='.$sCode,
'reject'=>Router::GetPath('profile').'friendoffer/reject/?code='.$sCode
);
$sText=$this->Lang_Get(
'user_friend_offer_text',
array(
@ -569,36 +570,36 @@ class ActionProfile extends Action {
$this->Notify_SendUserFriendNew(
$oUser,$this->oUserCurrent,$sUserText,
Router::GetPath('talk').'read/'.$oTalk->getId().'/'
);
);
/**
* Удаляем отправляющего юзера из переписки
*/
*/
$this->Talk_DeleteTalkUserByArray($oTalk->getId(),$this->oUserCurrent->getId());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
}
}
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriendNew);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
$oViewerLocal->Assign('oUserFriend',$oFriendNew);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
}
/**
* Удаление пользователя из друзей
*/
public function EventAjaxFriendDelete() {
$this->Viewer_SetResponseAjax('json');
$sUserId=getRequest('idUser',null,'post');
/**
* Если пользователь не авторизирован, возвращаем ошибку
*/
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle(
$this->Lang_Get('need_authorization'),
$this->Lang_Get('error')
);
return;
return;
}
$this->oUserCurrent=$this->User_GetUserCurrent();
@ -612,11 +613,11 @@ class ActionProfile extends Action {
);
return;
}
/**
* Если пользователь не найден, возвращаем ошибку
*/
if( !$oUser=$this->User_GetUserById($sUserId) ) {
if( !$oUser=$this->User_GetUserById($sUserId) ) {
$this->Message_AddErrorSingle(
$this->Lang_Get('user_friend_del_no'),
$this->Lang_Get('error')
@ -638,14 +639,14 @@ class ActionProfile extends Action {
);
return;
}
if( $this->User_DeleteFriend($oFriend) ) {
$this->Message_AddNoticeSingle($this->Lang_Get('user_friend_del_ok'),$this->Lang_Get('attention'));
$oViewerLocal=$this->GetViewerLocal();
$oViewerLocal->Assign('oUserFriend',$oFriend);
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
$this->Viewer_AssignAjax('sToggleText',$oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
/**
* Отправляем пользователю сообщение об удалении дружеской связи
*/
@ -661,15 +662,15 @@ class ActionProfile extends Action {
$sText,$this->oUserCurrent,
array($oUser),false,false
);
$this->Talk_DeleteTalkUserByArray($oTalk->getId(),$this->oUserCurrent->getId());
$this->Talk_DeleteTalkUserByArray($oTalk->getId(),$this->oUserCurrent->getId());
}
return;
return;
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
}
/**
* Выполняется при завершении работы экшена
*/
@ -684,10 +685,10 @@ class ActionProfile extends Action {
$iCountTopicUser=$this->Topic_GetCountTopicsPersonalByUser($this->oUserProfile->getId(),1);
$iCountCommentUser=$this->Comment_GetCountCommentsByUserId($this->oUserProfile->getId(),'topic');
$iCountCommentFavourite=$this->Comment_GetCountCommentsFavouriteByUserId($this->oUserProfile->getId());
$this->Viewer_Assign('oUserProfile',$this->oUserProfile);
$this->Viewer_Assign('iCountTopicUser',$iCountTopicUser);
$this->Viewer_Assign('iCountCommentUser',$iCountCommentUser);
$this->Viewer_Assign('oUserProfile',$this->oUserProfile);
$this->Viewer_Assign('iCountTopicUser',$iCountTopicUser);
$this->Viewer_Assign('iCountCommentUser',$iCountCommentUser);
$this->Viewer_Assign('iCountTopicFavourite',$iCountTopicFavourite);
$this->Viewer_Assign('iCountCommentFavourite',$iCountCommentFavourite);
$this->Viewer_Assign('USER_FRIEND_NULL',ModuleUser::USER_FRIEND_NULL);

View file

@ -0,0 +1,162 @@
<?php
class ActionStream extends Action
{
protected $oUserCurrent;
public function Init()
{
$this->oUserCurrent = $this->User_getUserCurrent();
if (!$this->oUserCurrent) {
parent::EventNotFound();
}
$this->SetDefaultEvent('index');
$this->Viewer_Assign('STREAM_EVENT_TYPE', array ( 'ADD_TOPIC' => array('id' => ModuleStream::EVENT_ADD_TOPIC, 'name' => $this->Lang_Get('stream_event_type_add_topic')),
'ADD_COMMENT' => array('id' => ModuleStream::EVENT_ADD_COMMENT, 'name' => $this->Lang_Get('stream_event_type_add_comment')),
'ADD_BLOG' => array('id' => ModuleStream::EVENT_ADD_BLOG, 'name' => $this->Lang_Get('stream_event_type_add_blog')),
'VOTE_TOPIC' => array('id' => ModuleStream::EVENT_VOTE_TOPIC, 'name' => $this->Lang_Get('stream_event_type_vote_topic')),
'VOTE_COMMENT' => array('id' => ModuleStream::EVENT_VOTE_COMMENT, 'name' => $this->Lang_Get('stream_event_type_vote_comment')),
'VOTE_BLOG' => array('id' => ModuleStream::EVENT_VOTE_BLOG, 'name' => $this->Lang_Get('stream_event_type_vote_blog')),
'VOTE_USER' => array('id' => ModuleStream::EVENT_VOTE_USER, 'name' => $this->Lang_Get('stream_event_type_vote_user')),
'MAKE_FRIENDS' => array('id' => ModuleStream::EVENT_MAKE_FRIENDS, 'name' => $this->Lang_Get('stream_event_type_make_friends')),
'JOIN_BLOG' => array('id' => ModuleStream::EVENT_JOIN_BLOG, 'name' => $this->Lang_Get('stream_event_type_join_blog'))
));
}
public function Shutdown()
{
}
protected function RegisterEvent()
{
$this->AddEvent('index', 'EventIndex');
$this->AddEvent('update', 'EventUpdateSubscribes');
$this->AddEvent('subscribe', 'EventSubscribe');
$this->AddEvent('subscribeByLogin', 'EventSubscribeByLogin');
$this->AddEvent('unsubscribe', 'EventUnSubscribe');
$this->AddEvent('switchEventType', 'EventSwitchEventType');
$this->AddEvent('get_more', 'EventGetMore');
}
protected function EventIndex()
{
$aEvents = $this->Stream_read();
$this->Viewer_Assign('aStreamEvents', $aEvents['events']);
if (isset($aEvents['events']) && count($aEvents['events'])) {
$aLastEvent = end($aEvents['events']);
$this->Viewer_Assign('iStreamLastId', $aLastEvent['id']);
$this->Viewer_Assign('aStreamTopics', $aEvents['topics']);
$this->Viewer_Assign('aStreamBlogs', $aEvents['blogs']);
$this->Viewer_Assign('aStreamUsers', $aEvents['users']);
$this->Viewer_Assign('aStreamComments', $aEvents['comments']);
}
$this->SetTemplateAction('list');
}
protected function EventSwitchEventType()
{
$this->Viewer_SetResponseAjax('json');
if (!getRequest('type')) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
}
$this->Stream_switchUserEventType($this->oUserCurrent->getId(), getRequest('type'));
$this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
}
protected function EventGetMore()
{
$iFromId = getRequest('last_id');
if (!$iFromId) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
$this->Viewer_SetResponseAjax('json');
$aEvents = $this->Stream_read(null, $iFromId);
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aStreamEvents', $aEvents['events']);
if (isset($aEvents['events']) && count($aEvents['events'])) {
$aLastEvent = end($aEvents['events']);
$oViewer->Assign('iStreamLastId', $aLastEvent['id']);
$this->Viewer_AssignAjax('iStreamLastId', $aLastEvent['id']);
$oViewer->Assign('aStreamTopics', $aEvents['topics']);
$oViewer->Assign('aStreamBlogs', $aEvents['blogs']);
$oViewer->Assign('aStreamUsers', $aEvents['users']);
$oViewer->Assign('aStreamComments', $aEvents['comments']);
$oViewer->Assign('STREAM_EVENT_TYPE', array ( 'ADD_TOPIC' => array('id' => ModuleStream::EVENT_ADD_TOPIC, 'name' => $this->Lang_Get('stream_event_type_add_topic')),
'ADD_COMMENT' => array('id' => ModuleStream::EVENT_ADD_COMMENT, 'name' => $this->Lang_Get('stream_event_type_add_comment')),
'ADD_BLOG' => array('id' => ModuleStream::EVENT_ADD_BLOG, 'name' => $this->Lang_Get('stream_event_type_add_blog')),
'VOTE_TOPIC' => array('id' => ModuleStream::EVENT_VOTE_TOPIC, 'name' => $this->Lang_Get('stream_event_type_vote_topic')),
'VOTE_COMMENT' => array('id' => ModuleStream::EVENT_VOTE_COMMENT, 'name' => $this->Lang_Get('stream_event_type_vote_comment')),
'VOTE_BLOG' => array('id' => ModuleStream::EVENT_VOTE_BLOG, 'name' => $this->Lang_Get('stream_event_type_vote_blog')),
'VOTE_USER' => array('id' => ModuleStream::EVENT_VOTE_USER, 'name' => $this->Lang_Get('stream_event_type_vote_user')),
'MAKE_FRIENDS' => array('id' => ModuleStream::EVENT_MAKE_FRIENDS, 'name' => $this->Lang_Get('stream_event_type_make_friends')),
'JOIN_BLOG' => array('id' => ModuleStream::EVENT_JOIN_BLOG, 'name' => $this->Lang_Get('stream_event_type_join_blog'))
));
}
$sFeed = $oViewer->Fetch('stream_list.tpl');
$this->Viewer_AssignAjax('result', $sFeed);
$this->Viewer_AssignAjax('events_count', count($aEvents['events']));
}
protected function EventSubscribe()
{
$this->Viewer_SetResponseAjax('json');
if (!getRequest('id')) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
}
$this->Stream_subscribeUser($this->oUserCurrent->getId(), getRequest('id'));
$this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
}
protected function EventSubscribeByLogin()
{
$this->Viewer_SetResponseAjax('json');
if (!getRequest('login')) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
$oUser = $this->User_getUserByLogin(getRequest('login'));
$this->Stream_subscribeUser($this->oUserCurrent->getId(), $oUser->getId());
$this->Viewer_AssignAjax('uid', $oUser->getId());
$this->Viewer_AssignAjax('user_login', $oUser->getLogin());
$this->Viewer_AssignAjax('user_web_path', $oUser->getuserWebPath());
$this->Viewer_AssignAjax('lang_error_msg', $this->Lang_Get('userfeed_subscribes_already_subscribed'));
$this->Viewer_AssignAjax('lang_error_title', $this->Lang_Get('error'));
$this->Message_AddNotice($this->Lang_Get('userfeed_subscribes_updated'), $this->Lang_Get('attention'));
}
protected function EventUnsubscribe()
{
$this->Viewer_SetResponseAjax('json');
if (!getRequest('id')) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
}
$this->Stream_unsubscribeUser($this->oUserCurrent->getId(), getRequest('id'));
$this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
}
protected function EventUpdateSubscribes()
{
$this->Viewer_SetResponseAjax('json');
$sType = getRequest('type');
$iType = null;
switch($sType) {
case 'blogs':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG;
break;
case 'users':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER;
break;
default:
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
$aIds = explode(',', getRequest('ids'));
$aUserSubscribes = array('users' => array(), 'blogs' => array());
$aUserSubscribes[$sType] = $aIds;
$this->Userfeed_updateSubscribes($this->oUserCurrent->getId(), $aUserSubscribes, $iType);
$this->Message_AddNotice($this->Lang_Get('userfeed_subscribes_updated'), $this->Lang_Get('attention'));
}
}

View file

@ -44,7 +44,7 @@ class ActionTopic extends Action {
* @var unknown_type
*/
protected $oUserCurrent=null;
/**
* Инициализация
*
@ -58,27 +58,27 @@ class ActionTopic extends Action {
return parent::EventNotFound();
}
$this->oUserCurrent=$this->User_GetUserCurrent();
$this->SetDefaultEvent('add');
$this->SetDefaultEvent('add');
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_title'));
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('add','EventAdd');
$this->AddEventPreg('/^published$/i','/^(page(\d+))?$/i','EventShowTopics');
$this->AddEventPreg('/^saved$/i','/^(page(\d+))?$/i','EventShowTopics');
$this->AddEvent('edit','EventEdit');
protected function RegisterEvent() {
$this->AddEvent('add','EventAdd');
$this->AddEventPreg('/^published$/i','/^(page(\d+))?$/i','EventShowTopics');
$this->AddEventPreg('/^saved$/i','/^(page(\d+))?$/i','EventShowTopics');
$this->AddEvent('edit','EventEdit');
$this->AddEvent('delete','EventDelete');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Редактирование топика
*
@ -99,10 +99,10 @@ class ActionTopic extends Action {
}
/**
* Если права на редактирование
*/
*/
if (!$this->ACL_IsAllowEditTopic($oTopic,$this->oUserCurrent)) {
return parent::EventNotFound();
}
}
/**
* Вызов хуков
*/
@ -115,10 +115,10 @@ class ActionTopic extends Action {
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('add');
$this->SetTemplateAction('add');
/**
* Проверяем отправлена ли форма с данными(хотяб одна кнопка)
*/
*/
if (isset($_REQUEST['submit_topic_publish']) or isset($_REQUEST['submit_topic_save'])) {
/**
* Обрабатываем отправку формы
@ -136,7 +136,7 @@ class ActionTopic extends Action {
$_REQUEST['topic_id']=$oTopic->getId();
$_REQUEST['topic_publish_index']=$oTopic->getPublishIndex();
$_REQUEST['topic_forbid_comment']=$oTopic->getForbidComment();
}
}
}
/**
* Удаление топика
@ -154,7 +154,7 @@ class ActionTopic extends Action {
}
/**
* проверяем есть ли право на удаление топика
*/
*/
if (!$this->ACL_IsAllowDeleteTopic($oTopic,$this->oUserCurrent)) {
return parent::EventNotFound();
}
@ -178,7 +178,7 @@ class ActionTopic extends Action {
/**
* Меню
*/
$this->sMenuSubItemSelect='add';
$this->sMenuSubItemSelect='add';
/**
* Вызов хуков
*/
@ -186,18 +186,18 @@ class ActionTopic extends Action {
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogsAllow',$this->Blog_GetBlogsAllowByUser($this->oUserCurrent));
$this->Viewer_Assign('aBlogsAllow',$this->Blog_GetBlogsAllowByUser($this->oUserCurrent));
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_topic_create'));
/**
* Обрабатываем отправку формы
*/
return $this->SubmitAdd();
}
return $this->SubmitAdd();
}
/**
* Выводит список топиков
*
*/
protected function EventShowTopics() {
protected function EventShowTopics() {
/**
* Меню
*/
@ -205,20 +205,20 @@ class ActionTopic extends Action {
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsPersonalByUser($this->oUserCurrent->getId(),$this->sCurrentEvent=='published' ? 1 : 0,$iPage,Config::Get('module.topic.per_page'));
*/
$aResult=$this->Topic_GetTopicsPersonalByUser($this->oUserCurrent->getId(),$this->sCurrentEvent=='published' ? 1 : 0,$iPage,Config::Get('module.topic.per_page'));
$aTopics=$aResult['collection'];
/**
* Формируем постраничность
*/
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),4,Router::GetPath('topic').$this->sCurrentEvent);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_menu_'.$this->sCurrentEvent));
}
@ -230,50 +230,50 @@ class ActionTopic extends Action {
protected function SubmitAdd() {
/**
* Проверяем отправлена ли форма с данными(хотяб одна кнопка)
*/
*/
if (!isPost('submit_topic_publish') and !isPost('submit_topic_save')) {
return false;
}
}
/**
* Проверка корректности полей формы
*/
if (!$this->checkTopicFields()) {
return false;
}
return false;
}
/**
* Определяем в какой блог делаем запись
*/
$iBlogId=getRequest('blog_id');
$iBlogId=getRequest('blog_id');
if ($iBlogId==0) {
$oBlog=$this->Blog_GetPersonalBlogByUserId($this->oUserCurrent->getId());
} else {
$oBlog=$this->Blog_GetBlogById($iBlogId);
}
}
/**
* Если блог не определен выдаем предупреждение
*/
if (!$oBlog) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'),$this->Lang_Get('error'));
return false;
}
}
/**
* Проверяем права на постинг в блог
*/
if (!$this->ACL_IsAllowBlog($oBlog,$this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'),$this->Lang_Get('error'));
return false;
}
}
/**
* Проверяем топик на уникальность
*/
if ($oTopicEquivalent=$this->Topic_GetTopicUnique($this->oUserCurrent->getId(),md5(getRequest('topic_text')))) {
if ($oTopicEquivalent=$this->Topic_GetTopicUnique($this->oUserCurrent->getId(),md5(getRequest('topic_text')))) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_text_error_unique'),$this->Lang_Get('error'));
return false;
}
}
/**
* Проверяем разрешено ли постить топик по времени
*/
if (isPost('submit_topic_publish') and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
if (isPost('submit_topic_publish') and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'),$this->Lang_Get('error'));
return;
}
@ -290,11 +290,11 @@ class ActionTopic extends Action {
* Получаемый и устанавливаем разрезанный текст по тегу <cut>
*/
list($sTextShort,$sTextNew,$sTextCut) = $this->Text_Cut(getRequest('topic_text'));
$oTopic->setCutText($sTextCut);
$oTopic->setText($this->Text_Parser($sTextNew));
$oTopic->setTextShort($this->Text_Parser($sTextShort));
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setDateAdd(date("Y-m-d H:i:s"));
@ -308,7 +308,7 @@ class ActionTopic extends Action {
} else {
$oTopic->setPublish(0);
$oTopic->setPublishDraft(0);
}
}
/**
* Принудительный вывод на главную
*/
@ -316,8 +316,8 @@ class ActionTopic extends Action {
if ($this->oUserCurrent->isAdministrator()) {
if (getRequest('topic_publish_index')) {
$oTopic->setPublishIndex(1);
}
}
}
}
/**
* Запрет на комментарии к топику
*/
@ -332,7 +332,7 @@ class ActionTopic extends Action {
$this->Hook_Run('topic_add_before', array('oTopic'=>$oTopic,'oBlog'=>$oBlog));
/**
* Добавляем топик
*/
*/
if ($this->Topic_AddTopic($oTopic)) {
$this->Hook_Run('topic_add_after', array('oTopic'=>$oTopic,'oBlog'=>$oBlog));
/**
@ -343,13 +343,17 @@ class ActionTopic extends Action {
* Делаем рассылку спама всем, кто состоит в этом блоге
*/
if ($oTopic->getPublish()==1 and $oBlog->getType()!='personal') {
$this->Topic_SendNotifyTopicNew($oBlog,$oTopic,$this->oUserCurrent);
}
$this->Topic_SendNotifyTopicNew($oBlog,$oTopic,$this->oUserCurrent);
}
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oTopic->getUserId(), ModuleStream::EVENT_ADD_TOPIC, $oTopic->getId());
Router::Location($oTopic->getUrl());
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return Router::Action('error');
}
}
}
/**
* Обработка редактирования топика
@ -357,17 +361,17 @@ class ActionTopic extends Action {
* @param unknown_type $oTopic
* @return unknown
*/
protected function SubmitEdit($oTopic) {
protected function SubmitEdit($oTopic) {
/**
* Проверка корректности полей формы
*/
if (!$this->checkTopicFields()) {
return false;
}
return false;
}
/**
* Определяем в какой блог делаем запись
*/
$iBlogId=getRequest('blog_id');
$iBlogId=getRequest('blog_id');
if ($iBlogId==0) {
$oBlog=$this->Blog_GetPersonalBlogByUserId($oTopic->getUserId());
} else {
@ -390,7 +394,7 @@ class ActionTopic extends Action {
/**
* Проверяем топик на уникальность
*/
if ($oTopicEquivalent=$this->Topic_GetTopicUnique($oTopic->getUserId(),md5(getRequest('topic_text')))) {
if ($oTopicEquivalent=$this->Topic_GetTopicUnique($oTopic->getUserId(),md5(getRequest('topic_text')))) {
if ($oTopicEquivalent->getId()!=$oTopic->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_text_error_unique'),$this->Lang_Get('error'));
return false;
@ -399,7 +403,7 @@ class ActionTopic extends Action {
/**
* Проверяем разрешено ли постить топик по времени
*/
if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'),$this->Lang_Get('error'));
return;
}
@ -409,7 +413,7 @@ class ActionTopic extends Action {
$sBlogIdOld = $oTopic->getBlogId();
/**
* Теперь можно смело редактировать топик
*/
*/
$oTopic->setBlogId($oBlog->getId());
$oTopic->setTitle(getRequest('topic_title'));
$oTopic->setTextHash(md5(getRequest('topic_text')));
@ -421,7 +425,7 @@ class ActionTopic extends Action {
$oTopic->setCutText($sTextCut);
$oTopic->setText($this->Text_Parser($sTextNew));
$oTopic->setTextShort($this->Text_Parser($sTextShort));
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setUserIp(func_getIp());
@ -482,7 +486,7 @@ class ActionTopic extends Action {
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return Router::Action('error');
}
}
}
/**
* Проверка полей формы
@ -491,7 +495,7 @@ class ActionTopic extends Action {
*/
protected function checkTopicFields() {
$this->Security_ValidateSendForm();
$bOk=true;
/**
* Проверяем есть ли блог в кторый постим
@ -522,7 +526,7 @@ class ActionTopic extends Action {
$bOk=false;
}
/**
* проверяем ввод тегов
* проверяем ввод тегов
*/
$sTags=getRequest('topic_tags',null,'post');
$aTags=explode(',',$sTags);
@ -545,7 +549,7 @@ class ActionTopic extends Action {
* Выполнение хуков
*/
$this->Hook_Run('check_topic_fields', array('bOk'=>&$bOk));
return $bOk;
}
/**

View file

@ -0,0 +1,13 @@
<?php
class BlockStreamConfig extends Block
{
public function Exec() {
$aStreamConfig = $this->Stream_getUserConfig($this->User_getUserCurrent()->getId());
$this->Viewer_Assign('aStreamConfig', $aStreamConfig);
$aUserSubscribes = $this->Stream_getUserSubscribes($this->User_getUserCurrent()->getId());
$aFriends = $this->User_getUsersFriend($this->User_getUserCurrent()->getId());
$this->Viewer_Assign('aStreamSubscribedUsers', $aUserSubscribes);
$this->Viewer_Assign('aStreamFriends', $aFriends);
}
}

View file

@ -0,0 +1,189 @@
<?php
class ModuleStream extends Module
{
const EVENT_ALL = 1023;
const EVENT_ADD_TOPIC = 2;
const EVENT_ADD_COMMENT = 4;
const EVENT_ADD_BLOG = 8;
const EVENT_VOTE_TOPIC = 16;
const EVENT_VOTE_COMMENT = 32;
const EVENT_VOTE_BLOG = 64;
const EVENT_VOTE_USER = 128;
const EVENT_MAKE_FRIENDS = 256;
const EVENT_JOIN_BLOG = 512;
protected $oMapper = null;
public function Init()
{
$this->oMapper=Engine::GetMapper(__CLASS__);
}
/**
* Подписать пользователя
* @param type $iUserId Id подписываемого пользователя
* @param type $iSubscribeType Тип подписки (см. константы класса)
* @param type $iTargetId Id цели подписки
*/
public function subscribeUser($iUserId, $iTargetUserId)
{
return $this->oMapper->subscribeUser($iUserId, $iTargetUserId);
}
/**
* Отписать пользователя
* @param type $iUserId Id подписываемого пользователя
* @param type $iSubscribeType Тип подписки (см. константы класса)
* @param type $iTargetId Id цели подписки
*/
public function unsubscribeUser($iUserId, $iTargetUserId)
{
return $this->oMapper->unsubscribeUser($iUserId, $iTargetUserId);
}
/**
* Редактирвоание списка событий, на которые подписан юзер
* @param type $iUserId
* @param type $iType
* @return type
*/
public function switchUserEventType($iUserId, $iType)
{
return $this->oMapper->switchUserEventType($iUserId, $iType);
}
/**
* Запись события в ленту
* @param type $oUser
* @param type $iEventType
* @param type $iTargetId
*/
public function write($oUser, $iEventType, $iTargetId)
{
$this->oMapper->addEvent($oUser, $iEventType, $iTargetId);
}
/**
* Удалеине события из ленты
* @param type $oUser
* @param type $iEventType
* @param type $iTargetId
*/
public function delete($oUser, $iEventType, $iTargetId)
{
$this->oMapper->deleteEvent($oUser, $iEventType, $iTargetId);
}
/**
* Чтение ленты событий
* @param type $iCount
* @param type $iFromId
* @return type
*/
public function read($iCount = null, $iFromId = null)
{
if (!$iCount) $iCount = Config::Get('module.stream.count_default');
$oUser = $this->User_getUserCurrent();
$aUserConfig = $this->getUserConfig($oUser->getId());
$aEventTypes = $aUserConfig['event_types'];
if (!count($aEventTypes)) return array('events' => array());
$aUsesrList = $this->getUsersList();
if (!$aUsesrList) return array('events' => array());
$aEvents = array();
$aEvents = $this->oMapper->read($aEventTypes, $aUsesrList, $iCount, $iFromId);
$aNeededObjects = array('topics' => array(), 'blogs' => array(), 'users' => array(), 'comments' => array());
if (!count($aEvents)) array('events' => array());
foreach ($aEvents as $aEvent) {
if (!in_array($aEvent['initiator'], $aNeededObjects['users'])) {
$aNeededObjects['users'][] = $aEvent['initiator'];
}
switch ($aEvent['event_type']) {
case self::EVENT_ADD_TOPIC: case self::EVENT_VOTE_TOPIC:
if (!in_array($aEvent['target_id'], $aNeededObjects['topics'])) {
$aNeededObjects['topics'][] = $aEvent['target_id'];
}
break;
case self::EVENT_ADD_COMMENT: case self::EVENT_VOTE_COMMENT:
if (!in_array($aEvent['target_id'], $aNeededObjects['comments'])) {
$aNeededObjects['comments'][] = $aEvent['target_id'];
}
break;
case self::EVENT_ADD_BLOG: case self::EVENT_VOTE_BLOG: case self::EVENT_JOIN_BLOG:
if (!in_array($aEvent['target_id'], $aNeededObjects['blogs'])) {
$aNeededObjects['blogs'][] = $aEvent['target_id'];
}
break;
case self::EVENT_VOTE_USER: case self::EVENT_MAKE_FRIENDS:
if (!in_array($aEvent['target_id'], $aNeededObjects['users'])) {
$aNeededObjects['users'][] = $aEvent['target_id'];
}
break;
}
}
$aTopics = array();
if (count($aNeededObjects['topics'])) {
$aTopics = $this->Topic_getTopicsAdditionalData($aNeededObjects['topics']);
}
$aBlogs = array();
if (count($aNeededObjects['blogs'])) {
$aBlogs = $this->Blog_getBlogsByArrayId($aNeededObjects['blogs']);
}
$aUsers = array();
if (count($aNeededObjects['users'])) {
$aUsers = $this->User_getUsersByArrayId($aNeededObjects['users']);
}
$aComments = array();
if (count($aNeededObjects['comments'])) {
$aComments = $this->Comment_getCommentsByArrayId($aNeededObjects['comments']);
foreach($aComments as $oComment) {
if (!isset($aTopics[$oComment->getTargetId()])) {
$aTopics[$oComment->getTargetId()] = $this->Topic_getTopicById($oComment->getTargetId());
}
}
}
return array('events' => $aEvents, 'topics' => $aTopics, 'blogs' => $aBlogs, 'users' => $aUsers, 'comments' => $aComments);
}
/**
* Получение списка пользователей, на которых подписан пользователь
* @param type $iUserId
* @return type
*/
public function getUserSubscribes($iUserId)
{
$aIds = $this->oMapper->getUserSubscribes($iUserId);
$aResult = array();
if (count($aIds)) {
$aUsers = $this->User_getUsersByArrayId($aIds);
foreach ($aUsers as $oUser) {
$aResult[$oUser->getId()] = $oUser;
}
}
return $aResult;
}
/**
* Получение настроек ленты
* @param type $iUserId
* @return type
*/
public function getUserConfig($iUserId)
{
return $this->oMapper->getUserConfig($iUserId);
}
/**
* Получение списка id пользователей, на которых подписан пользователь
* @return type
*/
protected function getUsersList()
{
$iUserId = $this->User_getUserCurrent()->getId();
$aList = $this->oMapper->getUserSubscribes($iUserId);
return $aList;
}
}

View file

@ -0,0 +1,128 @@
<?php
class ModuleStream_MapperStream extends Mapper
{
public function subscribeUser($iUserId, $iTargetUserId)
{
$sql = 'SELECT * FROM ' . Config::Get('db.table.stream_subscribe') . ' WHERE
user_id = ?d AND target_user_id = ?d';
if (!$this->oDb->select($sql, $iUserId, $iTargetUserId)) {
$sql = 'INSERT INTO ' . Config::Get('db.table.stream_subscribe') . ' SET
user_id = ?d, target_user_id = ?d';
$this->oDb->query($sql, $iUserId, $iTargetUserId);
}
}
public function unsubscribeUser($iUserId, $iTargetUserId)
{
$sql = 'DELETE FROM ' . Config::Get('db.table.stream_subscribe') . ' WHERE
user_id = ?d AND target_user_id = ?d';
$this->oDb->query($sql, $iUserId, $iTargetUserId);
}
public function readByFilter($aParams, $aLimit)
{
if (!is_array($aParams) || !count($aParams)) return array();
$sql = 'SELECT * FROM ' . Config::Get('db.table.stream_event'). 'WHERE 1=2';
$aSqlParams = array();
// Перебирается каждый тип события, т.к. для каждого типа событий назначаются свои фильтры
foreach ($aParams as $iEventType => $aFilter) {
$sql .= ' OR (event_type = ?d';
$aSqlParams[] = $iEventType;
if (is_array($aFilter) && count($aFilter)) {
// Перебор кажого элементра фильтра для обрабатываемого типа событий
foreach ($aFilter as $sKey => $sValue) {
$sql .= ' AND ?# = ?';
$aSqlParams[] = $sKey;
$aSqlParams[] = $sValue;
}
}
$sql .= ')';
}
$sql .= ' ORDER BY `id` DESC';
$sLimit='';
if ($aLimit) { // допустимы варианты: limit=10 , limit=array(10) , limit=array(10,15)
if (is_numeric($aLimit)) {
$iBegin=0;
$iEnd=$aLimit;
} elseif (is_array($aLimit)) {
if (count($aLimit)>1) {
$iBegin=$aLimit[0];
$iEnd=$aLimit[1];
} else {
$iBegin=0;
$iEnd=$aLimit[0];
}
}
$sLimit=" LIMIT {$iBegin}, {$iEnd}";
}
$sql .= $sLimit;
return call_user_func_array(array($this->oDb, 'select'), array_merge(array($sql), $aSqlParams));
}
public function read($iEventTypes, $aUsesrList, $iCount, $iFromId)
{
$sql = 'SELECT * FROM ' . Config::Get('db.table.stream_event'). ' WHERE
event_type & ?d AND initiator IN (?a)';
$aParams = array($iEventTypes, $aUsesrList);
if ($iFromId) {
$sql .= ' AND id < ?d';
$aParams[] = $iFromId;
}
$sql .= ' ORDER BY id DESC';
if ($iCount) {
$sql .= ' LIMIT 0,?d';
$aParams[] = $iCount;
}
return call_user_func_array(array($this->oDb, 'select'), array_merge(array($sql), $aParams));
}
public function addEvent($oUserId, $iEventType, $iTargetId)
{
$sql = 'INSERT INTO ' . Config::Get('db.table.stream_event'). ' SET
event_type = ?d, target_id = ?d, initiator = ?d';
$this->oDb->query($sql, $iEventType, $iTargetId, $oUserId);
}
public function deleteEvent($oUser, $iEventType, $iTargetId)
{
$sql = 'DELETE FROM' . Config::Get('db.table.stream_event'). ' WHERE
event_type = ?d AND target_id = ?d AND initiator = ?d';
$this->oDb->query($sql, $iEventType, $iTargetId, $oUser->getId());
}
public function getUserSubscribes($iUserId)
{
$sql = 'SELECT target_user_id FROM ' . Config::Get('db.table.stream_subscribe') . ' WHERE user_id = ?d';
return $this->oDb->selectCol($sql, $iUserId);
}
public function getUserConfig($iUserId)
{
$this->initUserConfig($iUserId);
$sql = 'SELECT * FROM ' . Config::Get('db.table.stream_config') . ' WHERE user_id = ?d';
$ret = $this->oDb->selectRow($sql, $iUserId);
return $ret;
}
public function switchUserEventType($iUserId, $iEventType)
{
$sql = 'UPDATE ' . Config::Get('db.table.stream_config') . ' SET
event_types = event_types ^ ?d
WHERE user_id = ?d';
$this->oDb->query($sql, $iEventType, $iUserId);
}
public function initUserConfig($iUserId)
{
$sql = 'SELECT * FROM ' . Config::Get('db.table.stream_config') . ' WHERE user_id = ?d';
if (!$this->oDb->select($sql, $iUserId)) {
$sql = 'INSERT INTO ' . Config::Get('db.table.stream_config') . ' SET user_id = ?d, event_types = ?d';
$this->oDb->query($sql, $iUserId, ModuleStream::EVENT_ALL);
}
}
}

View file

@ -27,11 +27,11 @@ $config['view']['noindex'] = true; // "прятать" или нет
$config['view']['img_resize_width'] = 500; // до какого размера в пикселях ужимать картинку по щирине при загрузки её в топики и комменты
$config['view']['img_max_width'] = 3000; // максимальная ширина загружаемых изображений в пикселях
$config['view']['img_max_height'] = 3000; // максимальная высота загружаемых изображений в пикселях
$config['view']['img_max_size_url'] = 500; // максимальный размер картинки в kB для загрузки по URL
$config['view']['img_max_size_url'] = 500; // максимальный размер картинки в kB для загрузки по URL
$config['view']['no_assign'] = array('db'); // список групп конфигурации, которые необходимо исключить из передачи во Viewer. Только для системного пользования.
/**
* Настройка основных блоков
* Настройка основных блоков
*/
$config['block']['stream']['row'] = 20; // сколько записей выводить в блоке "Прямой эфир"
$config['block']['blogs']['row'] = 10; // сколько записей выводить в блоке "Блоги"
@ -40,14 +40,14 @@ $config['block']['blogs']['row'] = 10; // сколько записей выв
* Если необходимо установить движек в директорию(не корень сайта) то следует сделать так:
* $config['path']['root']['web'] = 'http://'.$_SERVER['HTTP_HOST'].'/subdir';
* $config['path']['root']['server'] = $_SERVER['DOCUMENT_ROOT'].'/subdir';
* и возможно придёться увеличить значение SYS_OFFSET_REQUEST_URL на число вложенных директорий,
* например, для директории первой вложенности www.site.ru/livestreet/ поставить значение равное 1
* и возможно придёться увеличить значение SYS_OFFSET_REQUEST_URL на число вложенных директорий,
* например, для директории первой вложенности www.site.ru/livestreet/ поставить значение равное 1
*/
$config['path']['root']['web'] = 'http://'.$_SERVER['HTTP_HOST']; // полный WEB адрес сайта
$config['path']['root']['server'] = dirname(dirname(__FILE__)); // полный путь до сайта в файловой системе
/**
* Для CLI режима использовать
* $config['path']['root']['server'] = dirname(dirname(__FILE__)); // полный путь до сайта в файловой системе
* $config['path']['root']['server'] = dirname(dirname(__FILE__)); // полный путь до сайта в файловой системе
*/
$config['path']['root']['engine'] = '___path.root.server___/engine'; // полный путь до сайта в файловой системе;
$config['path']['root']['engine_lib'] = '___path.root.web___/engine/lib'; // полный путь до сайта в файловой системе
@ -135,13 +135,13 @@ $config['lang']['path'] = '___path.root.server___/templates/language'; // п
*/
$config['acl']['create']['blog']['rating'] = 1; // порог рейтинга при котором юзер может создать коллективный блог
$config['acl']['create']['comment']['rating'] = -10; // порог рейтинга при котором юзер может добавлять комментарии
$config['acl']['create']['comment']['limit_time'] = 10; // время в секундах между постингом комментариев, если 0 то ограничение по времени не будет работать
$config['acl']['create']['comment']['limit_time_rating'] = -1; // рейтинг, выше которого перестаёт действовать ограничение по времени на постинг комментов. Не имеет смысла при $config['acl']['create']['comment']['limit_time']=0
$config['acl']['create']['topic']['limit_time'] = 240;// время в секундах между созданием записей, если 0 то ограничение по времени не будет работать
$config['acl']['create']['topic']['limit_time_rating'] = 5; // рейтинг, выше которого перестаёт действовать ограничение по времени на создание записей
$config['acl']['create']['talk']['limit_time'] = 300; // время в секундах между отправкой инбоксов, если 0 то ограничение по времени не будет работать
$config['acl']['create']['comment']['limit_time'] = 10; // время в секундах между постингом комментариев, если 0 то ограничение по времени не будет работать
$config['acl']['create']['comment']['limit_time_rating'] = -1; // рейтинг, выше которого перестаёт действовать ограничение по времени на постинг комментов. Не имеет смысла при $config['acl']['create']['comment']['limit_time']=0
$config['acl']['create']['topic']['limit_time'] = 240;// время в секундах между созданием записей, если 0 то ограничение по времени не будет работать
$config['acl']['create']['topic']['limit_time_rating'] = 5; // рейтинг, выше которого перестаёт действовать ограничение по времени на создание записей
$config['acl']['create']['talk']['limit_time'] = 300; // время в секундах между отправкой инбоксов, если 0 то ограничение по времени не будет работать
$config['acl']['create']['talk']['limit_time_rating'] = 1; // рейтинг, выше которого перестаёт действовать ограничение по времени на отправку инбоксов
$config['acl']['create']['talk_comment']['limit_time'] = 10; // время в секундах между отправкой инбоксов, если 0 то ограничение по времени не будет работать
$config['acl']['create']['talk_comment']['limit_time'] = 10; // время в секундах между отправкой инбоксов, если 0 то ограничение по времени не будет работать
$config['acl']['create']['talk_comment']['limit_time_rating'] = 5; // рейтинг, выше которого перестаёт действовать ограничение по времени на отправку инбоксов
$config['acl']['vote']['comment']['rating'] = -3; // порог рейтинга при котором юзер может голосовать за комментарии
$config['acl']['vote']['blog']['rating'] = -5; // порог рейтинга при котором юзер может голосовать за блог
@ -169,7 +169,7 @@ $config['module']['user']['per_page'] = 15; // Число юзеро
$config['module']['user']['friend_notice']['delete'] = false; // Отправить talk-сообщение в случае удаления пользователя из друзей
$config['module']['user']['friend_notice']['accept'] = false; // Отправить talk-сообщение в случае одобрения заявки на добавление в друзья
$config['module']['user']['friend_notice']['reject'] = false; // Отправить talk-сообщение в случае отклонения заявки на добавление в друзья
$config['module']['user']['avatar_size'] = array(64,48,24,0); // Список размеров аватаров у пользователя. 0 - исходный размер
$config['module']['user']['avatar_size'] = array(64,48,24,0); // Список размеров аватаров у пользователя. 0 - исходный размер
$config['module']['user']['login']['min_size'] = 3; // Минимальное количество символов в логине
$config['module']['user']['login']['max_size'] = 30; // Максимальное количество символов в логине
// Модуль Comment
@ -188,8 +188,8 @@ $config['module']['talk']['max_errors'] = 4;
$config['module']['talk']['encrypt'] = 'livestreet'; // Ключ XXTEA шифрования идентификаторов в ссылках
// Модуль Lang
$config['module']['lang']['delete_undefined'] = true; // Если установлена true, то модуль будет автоматически удалять из языковых конструкций переменные вида %%var%%, по которым не была произведена замена
// Модуль Notify
$config['module']['notify']['delayed'] = false; // Указывает на необходимость использовать режим отложенной рассылки сообщений на email
// Модуль Notify
$config['module']['notify']['delayed'] = true; // Указывает на необходимость использовать режим отложенной рассылки сообщений на email
$config['module']['notify']['insert_single'] = false; // Если опция установлена в true, систему будет собирать записи заданий удаленной публикации, для вставки их в базу единым INSERT
$config['module']['notify']['per_process'] = 10; // Количество отложенных заданий, обрабатываемых одним крон-процессом
// Модуль Image
@ -222,6 +222,10 @@ $config['module']['image']['topic']['round_corner'] = false;
$config['module']['security']['key'] = "livestreet_security_key"; // ключ сессии для хранения security-кода
$config['module']['security']['hash'] = "livestreet_security_key"; // "примесь" к строке, хешируемой в качестве security-кода
$config['module']['userfeed']['count_default'] = 10; // Число топиков в ленте по умолчанию
$config['module']['stream']['count_default'] = 20; // Число топиков в ленте по умолчанию
// Какие модули должны быть загружены на старте
$config['module']['autoLoad'] = array('Hook','Cache','Security','Session','Lang','Message','User');
/**
@ -264,8 +268,12 @@ $config['db']['table']['country_user'] = '___db.table.prefix___country_us
$config['db']['table']['reminder'] = '___db.table.prefix___reminder';
$config['db']['table']['session'] = '___db.table.prefix___session';
$config['db']['table']['notify_task'] = '___db.table.prefix___notify_task';
$config['db']['table']['userfeed_subscribe'] = '___db.table.prefix___userfeed_subscribe';
$config['db']['table']['stream_subscribe'] = '___db.table.prefix___stream_subscribe';
$config['db']['table']['stream_event'] = '___db.table.prefix___stream_event';
$config['db']['table']['stream_config'] = '___db.table.prefix___stream_config';
$config['db']['tables']['engine'] = 'InnoDB'; // InnoDB или MyISAM
$config['db']['tables']['engine'] = 'InnoDB'; // InnoDB или MyISAM
/**
* Настройка memcache
*/
@ -305,7 +313,9 @@ $config['router']['page']['question'] = 'ActionQuestion';
$config['router']['page']['blogs'] = 'ActionBlogs';
$config['router']['page']['search'] = 'ActionSearch';
$config['router']['page']['admin'] = 'ActionAdmin';
$config['router']['page']['ajax'] = 'ActionAjax';
$config['router']['page']['ajax'] = 'ActionAjax';
$config['router']['page']['feed'] = 'ActionUserfeed';
$config['router']['page']['stream'] = 'ActionStream';
// Глобальные настройки роутинга
$config['router']['config']['action_default'] = 'index';
$config['router']['config']['action_not_found'] = 'error';
@ -314,7 +324,7 @@ $config['router']['config']['action_not_found'] = 'error';
* Настройки вывода блоков
*/
$config['block']['rule_index_blog'] = array(
'path' => array(
'path' => array(
'___path.root.web___/blog$',
'___path.root.web___/blog/*$',
'___path.root.web___/blog/*/page\d+$',
@ -332,10 +342,10 @@ $config['block']['rule_index_blog'] = array(
);
$config['block']['rule_topic_type'] = array(
'action' => array(
'link' => array('add','edit'),
'question' => array('add','edit'),
'topic' => array('add','edit')
'action' => array(
'link' => array('add','edit'),
'question' => array('add','edit'),
'topic' => array('add','edit')
),
'blocks' => array( 'right' => array('block.blogInfo.tpl') ),
);
@ -368,6 +378,31 @@ $config['block']['rule_talk_read'] = array(
'blocks' => array( 'right' => array('actions/ActionTalk/speakers.tpl') ),
);
$config['block']['userfeedBlogs'] = array(
'action' => array('feed'),
'blocks' => array(
'right' => array(
'userfeedBlogs'=> array()
)
)
);
$config['block']['userfeedUsers'] = array(
'action' => array('feed'),
'blocks' => array(
'right' => array(
'userfeedUsers'=> array()
)
)
);
$config['block']['streamconfig'] = array(
'action' => array('stream'),
'blocks' => array(
'right' => array(
'streamConfig'=> array()
)
)
);
/**
* Настройки вывода js и css файлов
@ -400,11 +435,13 @@ $config['head']['default']['js'] = array(
"___path.static.skin___/js/questions.js",
"___path.static.skin___/js/block_loader.js",
"___path.static.skin___/js/friend.js",
"___path.static.skin___/js/blog.js",
"___path.static.skin___/js/blog.js",
"___path.static.skin___/js/other.js",
"___path.static.skin___/js/login.js",
"___path.static.skin___/js/panel.js",
"___path.static.skin___/js/messages.js",
"___path.static.skin___/js/userfeed.js",
"___path.static.skin___/js/stream.js",
"___path.static.skin___/js/Autocompleter.LS.js",
"___path.root.engine_lib___/external/MooTools_1.2/plugs/Piechart/moocanvas.js"=>array('browser'=>'IE'),
);
@ -413,11 +450,11 @@ $config['head']['default']['css'] = array(
"___path.static.skin___/css/Roar.css",
"___path.static.skin___/css/piechart.css",
"___path.static.skin___/css/Autocompleter.css",
"___path.static.skin___/css/prettify.css",
"___path.static.skin___/css/prettify.css",
"___path.static.skin___/css/vlaCal-v2.1.css",
"___path.static.skin___/css/ie6.css?v=1"=>array('browser'=>'IE 6'),
"___path.static.skin___/css/ie7.css?v=1"=>array('browser'=>'gte IE 7'),
"___path.static.skin___/css/simple_comments.css"=>array('browser'=>'gt IE 6'),
"___path.static.skin___/css/ie7.css?v=1"=>array('browser'=>'gte IE 7'),
"___path.static.skin___/css/simple_comments.css"=>array('browser'=>'gt IE 6'),
);
/**

View file

@ -721,6 +721,37 @@ return array(
'userfeed_subscribes_updated' => 'Настройки ленты сохранены',
'userfeed_get_more' => 'Получить ещё статьи',
/**
* Stream
*/
'stream_block_config_title' => 'Настройка ленты',
'stream_block_users_title' => 'Люди',
'stream_block_config_append' => 'Добавить',
'stream_block_users_friends' => 'Друзья',
'stream_subscribes_already_subscribed' => 'Вы уже подписаны на этого пользователя',
'stream_subscribes_updated' => 'Настройки ленты сохранены',
'stream_get_more' => 'Получить ещё события',
'stream_event_type_add_topic' => 'Добавление топика',
'stream_event_type_add_comment' => 'Добавление комментария',
'stream_event_type_add_blog' => 'Добавление блога',
'stream_event_type_vote_topic' => 'Голосование за топик',
'stream_event_type_vote_comment' => 'Голосование за комменатрий',
'stream_event_type_vote_blog' => 'Голосование за блог',
'stream_event_type_vote_user' => 'Голосование за пользователя',
'stream_event_type_make_friends' => 'Добавление в друзья',
'stream_event_type_join_blog' => 'Вступление в блог',
'stream_list_user' => 'Пользователь',
'stream_list_event_add_topic' => 'добавил новый топик',
'stream_list_event_add_blog' => 'добавил новый блог',
'stream_list_event_add_comment' => 'прокомментировал топик',
'stream_list_event_vote_topic' => 'оцнил топик',
'stream_list_event_vote_blog' => 'оценил блог',
'stream_list_event_vote_user' => 'оценил пользователя',
'stream_list_event_vote_comment' => 'оценил комментарий к топику',
'stream_list_event_join_blog' => 'вступил в блог',
'stream_list_event_make_friends' => 'добавил в друзья пользователя',
/**
* Рейтинг TOP
*/

View file

@ -0,0 +1,10 @@
{include file='header.tpl'}
{include file='stream_list.tpl'}
{if count($aStreamEvents)}
<div id="stream_loaded_events"></div>
<input type="hidden" id="stream_last_id" value="{$iStreamLastId}" />
<a class="stream-get-more" id="stream_get_more" href="javascript:lsStream.getMore()">{$aLang.stream_get_more}...</a>
{/if}
{include file='footer.tpl'}

View file

@ -0,0 +1,72 @@
{literal}
<script language="JavaScript" type="text/javascript">
document.addEvent('domready', function() {
new Autocompleter.Request.LS.JSON($('stream_users_complete'), aRouter['ajax']+'autocompleter/user/?security_ls_key='+LIVESTREET_SECURITY_KEY, {
'indicatorClass': 'autocompleter-loading', // class added to the input during request
'minLength': 1, // We need at least 1 character
'selectMode': 'pick', // Instant completion
'multiple': false, // Tag support, by default comma separated
});
$('stream_users_complete').addEvent('keydown', function (event) {
if (event.key == 'enter') {
lsStream.appendUser()
}
});
});
</script>
{/literal}
<div class="block">
<div class="tl"><div class="tr"></div></div>
<div class="cl"><div class="cr">
<h1>{$aLang.stream_block_config_title}</h1>
<ul>
{foreach from=$STREAM_EVENT_TYPE item=aEventType}
<li><input class="streamEventTypeCheckbox"
type="checkbox"
id="strn_et_{$aEventType.id}"
{math equation="x & y" x=$aEventType.id y=$aStreamConfig.event_types assign=bStreamChecked}
{if $bStreamChecked}checked="checked"{/if}
onClick="if ($(this).get('checked')) { lsStream.switchEventType( {$aEventType.id}) } else { lsStream.switchEventType( {$aEventType.id}) } " />
{$aEventType.name}
</li>
{/foreach}
</ul>
<hr />
<strong>{$aLang.stream_block_users_title}</strong><br />
<input type="text" id="stream_users_complete" autocomplete="off" onclick/>
<a href="javascript:lsStream.appendUser()">{$aLang.stream_block_config_append}</a>
<ul id="userfeed_block_users_list">
{if count($aStreamSubscribedUsers)}
{foreach from=$aStreamSubscribedUsers item=oUser}
{assign var=iUserId value=$oUser->getId()}
{if !isset($aStreamFriends.$iUserId)}
<li><input class="streamUserCheckbox"
type="checkbox"
id="strm_u_{$iUserId}"
checked="checked"
onClick="if ($(this).get('checked')) { lsStream.subscribe({$iUserId}) } else { lsStream.unsubscribe({$iUserId}) } " />
<a href="{$oUser->getUserWebPath()}">{$oUser->getLogin()}</a>
</li>
{/if}
{/foreach}
{/if}
</ul>
{if count($aStreamFriends)}
<strong>{$aLang.stream_block_users_friends}</strong>
<ul>
{foreach from=$aStreamFriends item=oUser}
{assign var=iUserId value=$oUser->getId()}
<li><input class="streamUserCheckbox"
type="checkbox"
id="strm_u_{$iUserId}"
{if isset($aStreamSubscribedUsers.$iUserId)} checked="checked"{/if}
onClick="if ($(this).get('checked')) { lsStream.subscribe({$iUserId}) } else { lsStream.unsubscribe({$iUserId}) } " />
<a href="{$oUser->getUserWebPath()}">{$oUser->getLogin()}</a>
</li>
{/foreach}
</ul>
{/if}
</div></div>
<div class="bl"><div class="br"></div></div>
</div>

View file

@ -832,6 +832,11 @@ table.admin_page td { /* IE: */ border-left: expression(previousSibling == nul
.userfeed-get-more:hover { background: #f0f7fd;}
.userfeed_loading {background: #F7F7F7 url(../images/loader.gif) no-repeat center;}
/* Stream
-------------------------------------------------------------------*/
.stream-get-more {display:block; width:90%; margin:0px auto; text-align:center; height:2.5em; padding-top:1em;}
.stream-get-more:hover { background: #f0f7fd;}
.stream_loading {background: #F7F7F7 url(../images/loader.gif) no-repeat center;}

View file

@ -0,0 +1,99 @@
function lsStreamClass() {
this.isBusy = false;
this.subscribe = function (iTargetUserId) {
new Request.JSON({
url: aRouter['stream']+'subscribe',
data: {'id':iTargetUserId, 'security_ls_key':LIVESTREET_SECURITY_KEY},
onSuccess: function(data) { // запрос выполнен уcпешно
if (!data.bStateError) {
msgNoticeBox.alert(data.sMsgTitle,data.sMsg);
}
}
}).send();
}
this.unsubscribe = function (iId) {
new Request.JSON({
url: aRouter['stream']+'unsubscribe',
data: { 'id':iId, 'security_ls_key':LIVESTREET_SECURITY_KEY},
onSuccess: function(data) { // запрос выполнен уcпешно
if (!data.bStateError) {
msgNoticeBox.alert(data.sMsgTitle,data.sMsg);
}
}
}).send();
}
this.switchEventType = function (iType) {
new Request.JSON({
url: aRouter['stream']+'switchEventType',
data: { 'type':iType, 'security_ls_key':LIVESTREET_SECURITY_KEY},
onSuccess: function(data) { // запрос выполнен уcпешно
if (!data.bStateError) {
msgNoticeBox.alert(data.sMsgTitle,data.sMsg);
}
}
}).send();
}
this.appendUser = function() {
sLogin = $('stream_users_complete').get('value');
if (!sLogin) return;
new Request.JSON({
url: aRouter['stream']+'subscribeByLogin',
data: {'login':sLogin, 'security_ls_key':LIVESTREET_SECURITY_KEY},
onSuccess: function(data) { // запрос выполнен уcпешно
if (!data.bStateError) {
checkbox = $('strm_u_'+data.uid);
if (checkbox) {
if ($(checkbox).get('checked')) {
msgErrorBox.alert(data.lang_error_title,data.lang_error_msg);
} else {
$(checkbox).set('checked', 'on');
msgNoticeBox.alert(data.sMsgTitle,data.sMsg);
}
} else {
var liElement = new Element('li');
var checkboxElement = new Element('input', {
'type':'checkbox',
'class':'streamUserCheckbox',
'id':'strm_u_'+data.uid,
'checked':'checked',
'onClick':'if ($(this).get(\'checked\')) {lsStream.subscribe('+data.uid+')} else {lsStream.unsubscribe('+data.uid+')}'
});
checkboxElement.inject(liElement);
var linkElement = new Element('a', {
'href':data.user_web_path,
'html':data.user_login
});
linkElement.inject(liElement);
liElement.inject($('stream_block_users_list'));
msgNoticeBox.alert(data.sMsgTitle,data.sMsg);
}
}
}
}).send();
}
this.getMore = function () {
if (this.isBusy) {
return;
}
lastId = $('stream_last_id').get('value');
if (!lastId) return;
$('stream_get_more').addClass('stream_loading');
this.isBusy = true;
new Request.JSON({
url: aRouter['stream']+'get_more',
data: {'last_id':lastId, 'security_ls_key':LIVESTREET_SECURITY_KEY},
onSuccess: function(data) { // запрос выполнен уcпешно
if (!data.bStateErro && data.events_count) {
$('stream_loaded_events').set('html', $('stream_loaded_events').get('html')+data.result);
$('stream_last_id').set('value', data.iStreamLastId);
}
if (!data.events_count) {
$('stream_get_more').setStyles({'display':'none'});
}
$('stream_get_more').removeClass('stream_loading');
lsStream.isBusy = false;
}
}).send();
}
}
var lsStream = new lsStreamClass;

View file

@ -0,0 +1,50 @@
{if count($aStreamEvents)}
<ul>
{foreach from=$aStreamEvents item=aEvent}
{assign var=initiatorId value=$aEvent.initiator}
{assign var=initiator value=$aStreamUsers.$initiatorId}
<li>{date_format date=$aEvent.date_added}: {$aLang.stream_list_user} <a href="{$initiator->getUserWebPath()}">{$initiator->getLogin()}</a>
{if $aEvent.event_type == $STREAM_EVENT_TYPE.ADD_TOPIC.id}
{assign var=topicId value=$aEvent.target_id}
{assign var=topic value=$aStreamTopics.$topicId}
{$aLang.stream_list_event_add_topic} <a href="{$topic->getUrl()}">{$topic->getTitle()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.ADD_COMMENT.id}
{assign var=commentId value=$aEvent.target_id}
{assign var=topicId value=$aStreamComments.$commentId->getTargetId()}
{assign var=topic value=$aStreamTopics.$topicId}
{$aLang.stream_list_event_add_comment} <a href="{$topic->getUrl()}#comment{$aStreamComments.$commentId->getId()}">{$topic->getTitle()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.ADD_BLOG.id}
{assign var=blogId value=$aEvent.target_id}
{assign var=blog value=$aStreamBlogs.$blogId}
{$aLang.stream_list_event_add_blog} <a href="{$blog->getUrl()}">{$blog->getTitle()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.VOTE_BLOG.id}
{assign var=blogId value=$aEvent.target_id}
{assign var=blog value=$aStreamBlogs.$blogId}
{$aLang.stream_list_event_vote_blog} <a href="{$blog->getUrl()}">{$blog->getTitle()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.VOTE_TOPIC.id}
{assign var=topicId value=$aEvent.target_id}
{assign var=topic value=$aStreamTopics.$topicId}
{$aLang.stream_list_event_vote_topic} <a href="{$topic->getUrl()}">{$topic->getTitle()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.VOTE_COMMENT.id}
{assign var=commentId value=$aEvent.target_id}
{assign var=topicId value=$aStreamComments.$commentId->getTargetId()}
{assign var=topic value=$aStreamTopics.$topicId}
{$aLang.stream_list_event_vote_comment} <a href="{$topic->getUrl()}#comment{$aStreamComments.$commentId->getId()}">{$topic->getTitle()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.VOTE_USER.id}
{assign var=userId value=$aEvent.target_id}
{assign var=user value=$aStreamUsers.$userId}
{$user}
{$aLang.stream_list_event_vote_user} <a href="{$user->getUserWebPath()}">{$user->getLogin()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.JOIN_BLOG.id}
{assign var=blogId value=$aEvent.target_id}
{assign var=blog value=$aStreamBlogs.$blogId}
{$aLang.stream_list_event_join_blog} <a href="{$blog->getUrl()}">{$blog->getTitle()}</a>
{elseif $aEvent.event_type == $STREAM_EVENT_TYPE.MAKE_FRIENDS.id}
{assign var=userId value=$aEvent.target_id}
{assign var=user value=$aStreamUsers.$userId}
{$aLang.stream_list_event_make_friends} <a href="{$user->getUserWebPath()}">{$user->getLogin()}</a>
{/if}
</li>
{/foreach}
</ul>
{/if}