From e3bf7d1bfdccac68c0e8c599990e95fe76fc8bae Mon Sep 17 00:00:00 2001 From: kirsan Date: Mon, 6 Jun 2011 11:58:19 +0000 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B5=D0=BD=D1=82=D0=B0=20=D1=81=D0=BE?= =?UTF-8?q?=D0=B1=D1=8B=D1=82=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- classes/actions/ActionAjax.class.php | 314 +++++++------- classes/actions/ActionBlog.class.php | 399 +++++++++--------- classes/actions/ActionProfile.class.php | 241 +++++------ classes/actions/ActionStream.class.php | 162 +++++++ classes/actions/ActionTopic.class.php | 120 +++--- classes/blocks/BlockStreamConfig.class.php | 13 + classes/modules/stream/Stream.class.php | 189 +++++++++ .../stream/mapper/Stream.mapper.class.php | 128 ++++++ config/config.php | 87 ++-- templates/language/russian.php | 31 ++ .../skin/new/actions/ActionStream/list.tpl | 10 + templates/skin/new/block.streamConfig.tpl | 72 ++++ templates/skin/new/css/style.css | 5 + templates/skin/new/js/stream.js | 99 +++++ templates/skin/new/stream_list.tpl | 50 +++ 15 files changed, 1375 insertions(+), 545 deletions(-) create mode 100644 classes/actions/ActionStream.class.php create mode 100644 classes/blocks/BlockStreamConfig.class.php create mode 100644 classes/modules/stream/Stream.class.php create mode 100644 classes/modules/stream/mapper/Stream.mapper.class.php create mode 100644 templates/skin/new/actions/ActionStream/list.tpl create mode 100644 templates/skin/new/block.streamConfig.tpl create mode 100644 templates/skin/new/js/stream.js create mode 100644 templates/skin/new/stream_list.tpl diff --git a/classes/actions/ActionAjax.class.php b/classes/actions/ActionAjax.class.php index 5f75a94f..b894bd34 100644 --- a/classes/actions/ActionAjax.class.php +++ b/classes/actions/ActionAjax.class.php @@ -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); } - - - + + + } ?> \ No newline at end of file diff --git a/classes/actions/ActionBlog.class.php b/classes/actions/ActionBlog.class.php index 63bc5935..db6fc0d2 100644 --- a/classes/actions/ActionBlog.class.php +++ b/classes/actions/ActionBlog.class.php @@ -50,7 +50,7 @@ class ActionBlog extends Action { * @var unknown_type */ protected $oUserCurrent=null; - + /** * Число новых топиков в коллективных блогах * @@ -81,7 +81,7 @@ class ActionBlog extends Action { * @var unknown_type */ protected $aBadBlogUrl=array('new','good','bad','edit','add','admin','delete','invite','ajaxaddcomment','ajaxaddbloginvite'); - + /** * Инизиализация экшена * @@ -95,55 +95,55 @@ class ActionBlog extends Action { /** * Достаём текущего пользователя */ - $this->oUserCurrent=$this->User_GetUserCurrent(); - + $this->oUserCurrent=$this->User_GetUserCurrent(); + /** * Подсчитываем новые топики */ $this->iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew(); - $this->iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew(); + $this->iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew(); $this->iCountTopicsBlogNew=$this->iCountTopicsCollectiveNew; $this->iCountTopicsNew=$this->iCountTopicsCollectiveNew+$this->iCountTopicsPersonalNew; } - + /** * Регистрируем евенты, по сути определяем УРЛы вида /blog/.../ * */ - protected function RegisterEvent() { + protected function RegisterEvent() { $this->AddEventPreg('/^good$/i','/^(page(\d+))?$/i','EventTopics'); $this->AddEvent('good','EventTopics'); $this->AddEventPreg('/^bad$/i','/^(page(\d+))?$/i','EventTopics'); $this->AddEventPreg('/^new$/i','/^(page(\d+))?$/i','EventTopics'); - + $this->AddEvent('add','EventAddBlog'); $this->AddEvent('edit','EventEditBlog'); $this->AddEvent('delete','EventDeleteBlog'); $this->AddEventPreg('/^admin$/i','/^\d+$/i','/^(page(\d+))?$/i','EventAdminBlog'); $this->AddEvent('invite','EventInviteBlog'); - + $this->AddEvent('ajaxaddcomment','AjaxAddComment'); $this->AddEvent('ajaxresponsecomment','AjaxResponseComment'); $this->AddEvent('ajaxaddbloginvite', 'AjaxAddBlogInvite'); $this->AddEvent('ajaxrebloginvite', 'AjaxReBlogInvite'); $this->AddEvent('ajaxbloginfo', 'AjaxBlogInfo'); $this->AddEvent('ajaxblogjoin', 'AjaxBlogJoin'); - + $this->AddEventPreg('/^(\d+)\.html$/i','/^$/i','EventShowTopic'); $this->AddEventPreg('/^[\w\-\_]+$/i','/^(\d+)\.html$/i','EventShowTopic'); - + $this->AddEventPreg('/^[\w\-\_]+$/i','/^(page(\d+))?$/i','EventShowBlog'); $this->AddEventPreg('/^[\w\-\_]+$/i','/^bad$/i','/^(page(\d+))?$/i','EventShowBlog'); $this->AddEventPreg('/^[\w\-\_]+$/i','/^new$/i','/^(page(\d+))?$/i','EventShowBlog'); - + $this->AddEventPreg('/^[\w\-\_]+$/i','/^users$/i','/^(page(\d+))?$/i','EventShowUsers'); } - - + + /********************************************************************************** ************************ РЕАЛИЗАЦИЯ ЭКШЕНА *************************************** ********************************************************************************** - */ + */ /** * Добавление нового блога * @@ -155,28 +155,28 @@ class ActionBlog extends Action { * Меню */ $this->sMenuSubItemSelect='add'; - $this->sMenuItemSelect='add_blog'; + $this->sMenuItemSelect='add_blog'; /** * Проверяем авторизован ли пользователь */ if (!$this->User_IsAuthorization()) { $this->Message_AddErrorSingle($this->Lang_Get('not_access'),$this->Lang_Get('error')); return Router::Action('error'); - } + } /** * Проверяем хватает ли рейтинга юзеру чтоб создать блог */ if (!$this->ACL_CanCreateBlog($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) { $this->Message_AddErrorSingle($this->Lang_Get('blog_create_acl'),$this->Lang_Get('error')); return Router::Action('error'); - } + } /** * Запускаем проверку корректности ввода полей при добалении блога. * Дополнительно проверяем, что был отправлен POST запрос. */ if (!$this->checkBlogFields()) { - return false; - } + return false; + } /** * Если всё ок то пытаемся создать блог */ @@ -195,7 +195,7 @@ class ActionBlog extends Action { $oBlog->setAvatar(null); /** * Загрузка аватара, делаем ресайзы - */ + */ if (isset($_FILES['avatar']) and is_uploaded_file($_FILES['avatar']['tmp_name'])) { if ($sPath=$this->Blog_UploadBlogAvatar($_FILES['avatar'],$oBlog)) { $oBlog->setAvatar($sPath); @@ -214,12 +214,17 @@ class ActionBlog extends Action { * Получаем блог, это для получение полного пути блога, если он в будущем будет зависит от других сущностей(компании, юзер и т.п.) */ $oBlog->Blog_GetBlogById($oBlog->getId()); + + /** + * Добавляем событие в ленту + */ + $this->Stream_write($oBlog->getUserId(), ModuleStream::EVENT_ADD_BLOG, $oBlog->getId()); Router::Location($oBlog->getUrlFull()); } else { $this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error')); } } - + /** * Редактирование блога * @@ -231,7 +236,7 @@ class ActionBlog extends Action { */ $this->sMenuSubItemSelect=''; $this->sMenuItemSelect='profile'; - + /** * Проверяем передан ли в УРЛе номер блога */ @@ -255,19 +260,19 @@ class ActionBlog extends Action { /** * Явлется ли авторизованный пользователь хозяином блога, либо его администратором */ - $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); + $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); $bIsAdministratorBlog=$oBlogUser ? $oBlogUser->getIsAdministrator() : false; if ($oBlog->getOwnerId()!=$this->oUserCurrent->getId() and !$this->oUserCurrent->isAdministrator() and !$bIsAdministratorBlog) { return parent::EventNotFound(); - } - + } + $this->Viewer_AddHtmlTitle($oBlog->getTitle()); $this->Viewer_AddHtmlTitle($this->Lang_Get('blog_edit')); - + $this->Viewer_Assign('oBlogEdit',$oBlog); /** * Устанавливаем шалон для вывода - */ + */ $this->SetTemplateAction('add'); /** * Если нажали кнопку "Сохранить" @@ -283,7 +288,7 @@ class ActionBlog extends Action { /** * Парсим описание блога на предмет ХТМЛ тегов */ - $sText=$this->Text_Parser(getRequest('blog_description')); + $sText=$this->Text_Parser(getRequest('blog_description')); $oBlog->setDescription($sText); /** * Сбрасываем кеш, если поменяли тип блога @@ -294,10 +299,10 @@ class ActionBlog extends Action { } $oBlog->setType(getRequest('blog_type')); $oBlog->setLimitRatingTopic(getRequest('blog_limit_rating_topic')); - //$oBlog->setUrl(getRequest('blog_url')); // запрещаем смену URL блога + //$oBlog->setUrl(getRequest('blog_url')); // запрещаем смену URL блога /** * Загрузка аватара, делаем ресайзы - */ + */ if (isset($_FILES['avatar']) and is_uploaded_file($_FILES['avatar']['tmp_name'])) { if ($sPath=$this->Blog_UploadBlogAvatar($_FILES['avatar'],$oBlog)) { $oBlog->setAvatar($sPath); @@ -335,18 +340,18 @@ class ActionBlog extends Action { $_REQUEST['blog_limit_rating_topic']=$oBlog->getLimitRatingTopic(); $_REQUEST['blog_id']=$oBlog->getId(); } - - + + } /** * Управление пользователями блога * * @return unknown */ - protected function EventAdminBlog() { + protected function EventAdminBlog() { /** * Меню - */ + */ $this->sMenuItemSelect='admin'; $this->sMenuSubItemSelect=''; /** @@ -366,17 +371,17 @@ class ActionBlog extends Action { /** * Явлется ли авторизованный пользователь хозяином блога, либо его администратором */ - $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); + $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); $bIsAdministratorBlog=$oBlogUser ? $oBlogUser->getIsAdministrator() : false; if ($oBlog->getOwnerId()!=$this->oUserCurrent->getId() and !$this->oUserCurrent->isAdministrator() and !$bIsAdministratorBlog) { return parent::EventNotFound(); - } + } /** * Обрабатываем сохранение формы */ if (isPost('submit_blog_admin')) { $this->Security_ValidateSendForm(); - + $aUserRank=getRequest('user_rank',array()); if (!is_array($aUserRank)) { $aUserRank=array(); @@ -389,10 +394,10 @@ class ActionBlog extends Action { /** * Увеличиваем число читателей блога */ - if (in_array($sRank,array('administrator','moderator','reader')) and $oBlogUser->getUserRole()==ModuleBlog::BLOG_USER_ROLE_BAN) { - $oBlog->setCountUser($oBlog->getCountUser()+1); + if (in_array($sRank,array('administrator','moderator','reader')) and $oBlogUser->getUserRole()==ModuleBlog::BLOG_USER_ROLE_BAN) { + $oBlog->setCountUser($oBlog->getCountUser()+1); } - + switch ($sRank) { case 'administrator': $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR); @@ -405,12 +410,12 @@ class ActionBlog extends Action { break; case 'ban': if ($oBlogUser->getUserRole()!=ModuleBlog::BLOG_USER_ROLE_BAN) { - $oBlog->setCountUser($oBlog->getCountUser()-1); + $oBlog->setCountUser($oBlog->getCountUser()-1); } $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_BAN); break; default: - $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_GUEST); + $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_GUEST); } $this->Blog_UpdateRelationBlogUser($oBlogUser); $this->Message_AddNoticeSingle($this->Lang_Get('blog_admin_users_submit_ok')); @@ -434,26 +439,26 @@ class ActionBlog extends Action { ),$iPage,Config::Get('module.blog.users_per_page') ); $aBlogUsers=$aResult['collection']; - + /** * Формируем постраничность - */ + */ $aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.blog.users_per_page'),4,Router::GetPath('blog')."admin/{$oBlog->getId()}"); $this->Viewer_Assign('aPaging',$aPaging); - + $this->Viewer_AddHtmlTitle($oBlog->getTitle()); $this->Viewer_AddHtmlTitle($this->Lang_Get('blog_admin')); - + $this->Viewer_Assign('oBlogEdit',$oBlog); $this->Viewer_Assign('aBlogUsers',$aBlogUsers); /** * Устанавливаем шалон для вывода - */ + */ $this->SetTemplateAction('admin'); - + /** - * Если блог закрытый, получаем приглашенных - * и добавляем блок-форму для приглашения + * Если блог закрытый, получаем приглашенных + * и добавляем блок-форму для приглашения */ if($oBlog->getType()=='close') { $aBlogUsersInvited=$this->Blog_GetBlogUsersByBlogId($oBlog->getId(),ModuleBlog::BLOG_USER_ROLE_INVITE,null); @@ -461,7 +466,7 @@ class ActionBlog extends Action { $this->Viewer_AddBlock('right','actions/ActionBlog/invited.tpl'); } } - + /** * Проверка полей блога * @@ -476,7 +481,7 @@ class ActionBlog extends Action { return false; } $this->Security_ValidateSendForm(); - + $bOk=true; /** * Проверяем есть ли название блога @@ -494,12 +499,12 @@ class ActionBlog extends Action { $bOk=false; } } - + if (!$oBlog) { /** * Проверяем есть ли URL блога, с заменой всех пробельных символов на "_" * Проверка только в том случаи если создаём новый блог, т.к при редактировании URL нельзя менять - */ + */ $blogUrl=preg_replace("/\s+/",'_',getRequest('blog_url')); $_REQUEST['blog_url']=$blogUrl; if (!func_check(getRequest('blog_url'),'login',2,50)) { @@ -538,21 +543,21 @@ class ActionBlog extends Action { $bOk=false; } /** - * Преобразуем ограничение по рейтингу в число - */ + * Преобразуем ограничение по рейтингу в число + */ if (!func_check(getRequest('blog_limit_rating_topic'),'float')) { $this->Message_AddError($this->Lang_Get('blog_create_rating_error'),$this->Lang_Get('error')); $bOk=false; } - + /** * Выполнение хуков */ $this->Hook_Run('check_blog_fields', array('bOk'=>&$bOk)); - + return $bOk; } - + /** * Показ всех топиков * @@ -566,12 +571,12 @@ class ActionBlog 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_GetTopicsCollective($iPage,Config::Get('module.topic.per_page'),$sShowType); - $aTopics=$aResult['collection']; + $aTopics=$aResult['collection']; /** * Формируем постраничность */ @@ -584,12 +589,12 @@ class ActionBlog extends Action { * Загружаем переменные в шаблон */ $this->Viewer_Assign('aTopics',$aTopics); - $this->Viewer_Assign('aPaging',$aPaging); + $this->Viewer_Assign('aPaging',$aPaging); /** * Устанавливаем шаблон вывода */ $this->SetTemplateAction('index'); - } + } /** * Показ топика * @@ -598,18 +603,18 @@ class ActionBlog extends Action { * @return unknown */ protected function EventShowTopic() { - $sBlogUrl=''; + $sBlogUrl=''; if ($this->GetParamEventMatch(0,1)) { // из коллективного блога $sBlogUrl=$this->sCurrentEvent; $iTopicId=$this->GetParamEventMatch(0,1); - $this->sMenuItemSelect='blog'; + $this->sMenuItemSelect='blog'; } else { // из персонального блога $iTopicId=$this->GetEventMatch(1); - $this->sMenuItemSelect='log'; + $this->sMenuItemSelect='log'; } - $this->sMenuSubItemSelect=''; + $this->sMenuSubItemSelect=''; /** * Проверяем есть ли такой топик */ @@ -626,8 +631,8 @@ class ActionBlog extends Action { /** * Определяем права на отображение записи из закрытого блога */ - if($oTopic->getBlog()->getType()=='close' - and (!$this->oUserCurrent + if($oTopic->getBlog()->getType()=='close' + and (!$this->oUserCurrent || !in_array( $oTopic->getBlog()->getId(), $this->Blog_GetAccessibleBlogsByUser($this->oUserCurrent) @@ -637,7 +642,7 @@ class ActionBlog extends Action { $this->Message_AddErrorSingle($this->Lang_Get('blog_close_show'),$this->Lang_Get('not_access')); return Router::Action('error'); } - + /** * Если запросили топик из персонального блога то перенаправляем на страницу вывода коллективного топика */ @@ -671,8 +676,8 @@ class ActionBlog extends Action { $iPageDef=1; } $iPage=getRequest('cmtpage',0) ? (int)getRequest('cmtpage',0) : $iPageDef; - $aReturn=$this->Comment_GetCommentsByTargetId($oTopic->getId(),'topic',$iPage,Config::Get('module.comment.nested_per_page')); - $iMaxIdComment=$aReturn['iMaxIdComment']; + $aReturn=$this->Comment_GetCommentsByTargetId($oTopic->getId(),'topic',$iPage,Config::Get('module.comment.nested_per_page')); + $iMaxIdComment=$aReturn['iMaxIdComment']; $aComments=$aReturn['comments']; if (Config::Get('module.comment.use_nested') and Config::Get('module.comment.nested_per_page')) { $aPaging=$this->Viewer_MakePaging($aReturn['count'],$iPage,Config::Get('module.comment.nested_per_page'),4,''); @@ -698,7 +703,7 @@ class ActionBlog extends Action { /** * Вызов хуков */ - $this->Hook_Run('topic_show',array("oTopic"=>$oTopic)); + $this->Hook_Run('topic_show',array("oTopic"=>$oTopic)); /** * Выставляем SEO данные */ @@ -707,19 +712,19 @@ class ActionBlog extends Action { $this->Viewer_SetHtmlKeywords($oTopic->getTags()); /** * Загружаем переменные в шаблон - */ + */ $this->Viewer_Assign('oTopic',$oTopic); - $this->Viewer_Assign('aComments',$aComments); + $this->Viewer_Assign('aComments',$aComments); $this->Viewer_Assign('iMaxIdComment',$iMaxIdComment); $this->Viewer_AddHtmlTitle($oTopic->getBlog()->getTitle()); $this->Viewer_AddHtmlTitle($oTopic->getTitle()); $this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss').'comments/'.$oTopic->getId().'/',$oTopic->getTitle()); /** * Устанавливаем шаблон вывода - */ + */ $this->SetTemplateAction('topic'); } - + /** * Страница со списком читателей блога * @@ -729,7 +734,7 @@ class ActionBlog extends Action { $sBlogUrl=$this->sCurrentEvent; /** * Проверяем есть ли блог с таким УРЛ - */ + */ if (!($oBlog=$this->Blog_GetBlogByUrl($sBlogUrl))) { return parent::EventNotFound(); } @@ -746,7 +751,7 @@ class ActionBlog extends Action { $aBlogUsers=$aBlogUsersResult['collection']; /** * Формируем постраничность - */ + */ $aPaging=$this->Viewer_MakePaging($aBlogUsersResult['count'],$iPage,Config::Get('module.blog.users_per_page'),4,$oBlog->getUrlFull().'users'); $this->Viewer_Assign('aPaging',$aPaging); /** @@ -755,7 +760,7 @@ class ActionBlog extends Action { $this->Hook_Run('blog_collective_show_users',array('oBlog'=>$oBlog)); /** * Загружаем переменные в шаблон - */ + */ $this->Viewer_Assign('aBlogUsers',$aBlogUsers); $this->Viewer_Assign('iCountBlogUsers',$aBlogUsersResult['count']); $this->Viewer_Assign('oBlog',$oBlog); @@ -765,21 +770,21 @@ class ActionBlog extends Action { */ $this->SetTemplateAction('users'); } - + protected function EventShowBlog() { - $sBlogUrl=$this->sCurrentEvent; - $sShowType=in_array($this->GetParamEventMatch(0,0),array('bad','new')) ? $this->GetParamEventMatch(0,0) : 'good'; + $sBlogUrl=$this->sCurrentEvent; + $sShowType=in_array($this->GetParamEventMatch(0,0),array('bad','new')) ? $this->GetParamEventMatch(0,0) : 'good'; /** * Проверяем есть ли блог с таким УРЛ - */ + */ if (!($oBlog=$this->Blog_GetBlogByUrl($sBlogUrl))) { return parent::EventNotFound(); } /** * Определяем права на отображение закрытого блога - */ - if($oBlog->getType()=='close' - and (!$this->oUserCurrent + */ + if($oBlog->getType()=='close' + and (!$this->oUserCurrent or !in_array( $oBlog->getId(), $this->Blog_GetAccessibleBlogsByUser($this->oUserCurrent) @@ -790,21 +795,21 @@ class ActionBlog extends Action { } else { $bCloseBlog=false; } - + /** * Меню */ $this->sMenuSubItemSelect=$sShowType; - $this->sMenuSubBlogUrl=$oBlog->getUrlFull(); + $this->sMenuSubBlogUrl=$oBlog->getUrlFull(); /** * Передан ли номер страницы */ - $iPage= $this->GetParamEventMatch(($sShowType=='good')?0:1,2) ? $this->GetParamEventMatch(($sShowType=='good')?0:1,2) : 1; - + $iPage= $this->GetParamEventMatch(($sShowType=='good')?0:1,2) ? $this->GetParamEventMatch(($sShowType=='good')?0:1,2) : 1; + if (!$bCloseBlog) { /** * Получаем список топиков - */ + */ $aResult=$this->Topic_GetTopicsByBlog($oBlog,$iPage,Config::Get('module.topic.per_page'),$sShowType); $aTopics=$aResult['collection']; /** @@ -825,7 +830,7 @@ class ActionBlog extends Action { * Выставляем SEO данные */ $sTextSeo=preg_replace("/<.*>/Ui",' ',$oBlog->getDescription()); - $this->Viewer_SetHtmlDescription(func_text_words($sTextSeo,20)); + $this->Viewer_SetHtmlDescription(func_text_words($sTextSeo,20)); /** * Получаем список юзеров блога */ @@ -835,32 +840,32 @@ class ActionBlog extends Action { $aBlogModerators=$aBlogModeratorsResult['collection']; $aBlogAdministratorsResult=$this->Blog_GetBlogUsersByBlogId($oBlog->getId(),ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR); $aBlogAdministrators=$aBlogAdministratorsResult['collection']; - + /** * Для админов проекта получаем список блогов и передаем их во вьювер */ if($this->oUserCurrent and $this->oUserCurrent->isAdministrator()) { $aBlogs = $this->Blog_GetBlogs(); unset($aBlogs[$oBlog->getId()]); - + $this->Viewer_Assign('aBlogs',$aBlogs); } - + /** * Вызов хуков */ $this->Hook_Run('blog_collective_show',array('oBlog'=>$oBlog,'sShowType'=>$sShowType)); /** * Загружаем переменные в шаблон - */ - $this->Viewer_Assign('aBlogUsers',$aBlogUsers); + */ + $this->Viewer_Assign('aBlogUsers',$aBlogUsers); $this->Viewer_Assign('aBlogModerators',$aBlogModerators); $this->Viewer_Assign('aBlogAdministrators',$aBlogAdministrators); $this->Viewer_Assign('iCountBlogUsers',$aBlogUsersResult['count']); $this->Viewer_Assign('iCountBlogModerators',$aBlogModeratorsResult['count']); - $this->Viewer_Assign('iCountBlogAdministrators',$aBlogAdministratorsResult['count']+1); + $this->Viewer_Assign('iCountBlogAdministrators',$aBlogAdministratorsResult['count']+1); $this->Viewer_Assign('oBlog',$oBlog); - $this->Viewer_Assign('bCloseBlog',$bCloseBlog); + $this->Viewer_Assign('bCloseBlog',$bCloseBlog); $this->Viewer_AddHtmlTitle($oBlog->getTitle()); $this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss').'blog/'.$oBlog->getUrl().'/',$oBlog->getTitle()); /** @@ -875,10 +880,10 @@ class ActionBlog extends Action { protected function AjaxAddComment() { $this->Viewer_SetResponseAjax('json'); $this->SubmitComment(); - } + } /** * Обработка добавление комментария к топику - * + * * @return bool */ protected function SubmitComment() { @@ -903,18 +908,18 @@ class ActionBlog extends Action { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); return; } - + /** * Проверяем разрешено ли постить комменты */ - if (!$this->ACL_CanPostComment($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) { + if (!$this->ACL_CanPostComment($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) { $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_acl'),$this->Lang_Get('error')); return; } /** * Проверяем разрешено ли постить комменты по времени */ - if (!$this->ACL_CanPostCommentTime($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) { + if (!$this->ACL_CanPostCommentTime($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) { $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_limit'),$this->Lang_Get('error')); return; } @@ -924,12 +929,12 @@ class ActionBlog extends Action { if ($oTopic->getForbidComment()) { $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_notallow'),$this->Lang_Get('error')); return; - } + } /** * Проверяем текст комментария */ $sText=$this->Text_Parser(getRequest('comment_text')); - if (!func_check($sText,'text',2,10000)) { + if (!func_check($sText,'text',2,10000)) { $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_add_text_error'),$this->Lang_Get('error')); return; } @@ -937,7 +942,7 @@ class ActionBlog extends Action { * Проверям на какой коммент отвечаем */ $sParentId=(int)getRequest('reply'); - if (!func_check($sParentId,'id')) { + if (!func_check($sParentId,'id')) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); return; } @@ -946,7 +951,7 @@ class ActionBlog extends Action { /** * Проверяем существует ли комментарий на который отвечаем */ - if (!($oCommentParent=$this->Comment_GetCommentById($sParentId))) { + if (!($oCommentParent=$this->Comment_GetCommentById($sParentId))) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); return; } @@ -966,7 +971,7 @@ class ActionBlog extends Action { /** * Проверка на дублирующий коммент */ - if ($this->Comment_GetCommentUnique($oTopic->getId(),'topic',$this->oUserCurrent->getId(),$sParentId,md5($sText))) { + if ($this->Comment_GetCommentUnique($oTopic->getId(),'topic',$this->oUserCurrent->getId(),$sParentId,md5($sText))) { $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_spam'),$this->Lang_Get('error')); return; } @@ -977,31 +982,31 @@ class ActionBlog extends Action { $oCommentNew->setTargetId($oTopic->getId()); $oCommentNew->setTargetType('topic'); $oCommentNew->setTargetParentId($oTopic->getBlog()->getId()); - $oCommentNew->setUserId($this->oUserCurrent->getId()); + $oCommentNew->setUserId($this->oUserCurrent->getId()); $oCommentNew->setText($sText); $oCommentNew->setDate(date("Y-m-d H:i:s")); $oCommentNew->setUserIp(func_getIp()); $oCommentNew->setPid($sParentId); $oCommentNew->setTextHash(md5($sText)); - + /** * Добавляем коммент */ $this->Hook_Run('comment_add_before', array('oCommentNew'=>$oCommentNew,'oCommentParent'=>$oCommentParent,'oTopic'=>$oTopic)); if ($this->Comment_AddComment($oCommentNew)) { $this->Hook_Run('comment_add_after', array('oCommentNew'=>$oCommentNew,'oCommentParent'=>$oCommentParent,'oTopic'=>$oTopic)); - + $this->Viewer_AssignAjax('sCommentId',$oCommentNew->getId()); if ($oTopic->getPublish()) { /** * Добавляем коммент в прямой эфир если топик не в черновиках - */ + */ $oCommentOnline=Engine::GetEntity('Comment_CommentOnline'); $oCommentOnline->setTargetId($oCommentNew->getTargetId()); $oCommentOnline->setTargetType($oCommentNew->getTargetType()); $oCommentOnline->setTargetParentId($oCommentNew->getTargetParentId()); $oCommentOnline->setCommentId($oCommentNew->getId()); - + $this->Comment_AddCommentOnline($oCommentOnline); } /** @@ -1023,34 +1028,38 @@ class ActionBlog extends Action { $oUserAuthorComment=$oCommentParent->getUser(); $this->Notify_SendCommentReplyToAuthorParentComment($oUserAuthorComment,$oTopic,$oCommentNew,$this->oUserCurrent); } + /** + * Добавляем событие в ленту + */ + $this->Stream_write($oCommentNew->getUserId(), ModuleStream::EVENT_ADD_COMMENT, $oCommentNew->getId()); } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); } - } - + } + /** * Получение новых комментариев * */ protected function AjaxResponseComment() { $this->Viewer_SetResponseAjax('json'); - + if (!$this->oUserCurrent) { $this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error')); return; } - + $idTopic=getRequest('idTarget',null,'post'); if (!($oTopic=$this->Topic_GetTopicById($idTopic))) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); return; } - + $idCommentLast=getRequest('idCommentLast',null,'post'); $selfIdComment=getRequest('selfIdComment',null,'post'); $aComments=array(); - - if (getRequest('bUsePaging',null,'post') and $selfIdComment) { + + if (getRequest('bUsePaging',null,'post') and $selfIdComment) { if ($oComment=$this->Comment_GetCommentById($selfIdComment) and $oComment->getTargetId()==$oTopic->getId() and $oComment->getTargetType()=='topic') { $oViewerLocal=$this->Viewer_GetLocalViewer(); $oViewerLocal->Assign('oUserCurrent',$this->oUserCurrent); @@ -1069,10 +1078,10 @@ class ActionBlog extends Action { $aReturn['comments']=$aCmt; $aReturn['iMaxIdComment']=$selfIdComment; } else { - $aReturn=$this->Comment_GetCommentsNewByTargetId($oTopic->getId(),'topic',$idCommentLast); + $aReturn=$this->Comment_GetCommentsNewByTargetId($oTopic->getId(),'topic',$idCommentLast); } $iMaxIdComment=$aReturn['iMaxIdComment']; - + $oTopicRead=Engine::GetEntity('Topic_TopicRead'); $oTopicRead->setTopicId($oTopic->getId()); $oTopicRead->setUserId($this->oUserCurrent->getId()); @@ -1080,7 +1089,7 @@ class ActionBlog extends Action { $oTopicRead->setCommentIdLast($iMaxIdComment); $oTopicRead->setDateRead(date("Y-m-d H:i:s")); $this->Topic_SetTopicRead($oTopicRead); - + $aCmts=$aReturn['comments']; if ($aCmts and is_array($aCmts)) { foreach ($aCmts as $aCmt) { @@ -1091,24 +1100,24 @@ class ActionBlog extends Action { ); } } - + $this->Viewer_AssignAjax('iMaxIdComment',$iMaxIdComment); $this->Viewer_AssignAjax('aComments',$aComments); } - + /** - * Обработка ajax запроса на отправку + * Обработка ajax запроса на отправку * пользователям приглашения вступить в закрытый блог */ protected function AjaxAddBlogInvite() { $this->Viewer_SetResponseAjax('json'); $sUsers=getRequest('users',null,'post'); $sBlogId=getRequest('idBlog',null,'post'); - + /** * Если пользователь не авторизирован, возвращаем ошибку */ - if (!$this->User_IsAuthorization()) { + if (!$this->User_IsAuthorization()) { $this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error')); return; } @@ -1118,21 +1127,21 @@ class ActionBlog extends Action { */ if(!$oBlog=$this->Blog_GetBlogById($sBlogId)) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); - return; + return; } /** * Проверяем, имеет ли право текущий пользователь добавлять invite в blog */ - $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); + $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); $bIsAdministratorBlog=$oBlogUser ? $oBlogUser->getIsAdministrator() : false; if ($oBlog->getOwnerId()!=$this->oUserCurrent->getId() and !$this->oUserCurrent->isAdministrator() and !$bIsAdministratorBlog) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); - return; - } - + return; + } + /** - * Получаем список пользователей блога (любого статуса) - * Это полный АХТУНГ - исправить! + * Получаем список пользователей блога (любого статуса) + * Это полный АХТУНГ - исправить! */ $aBlogUsersResult = $this->Blog_GetBlogUsersByBlogId( $oBlog->getId(), @@ -1158,7 +1167,7 @@ class ActionBlog extends Action { continue; } /** - * Если пользователь пытается добавить инвайт + * Если пользователь пытается добавить инвайт * самому себе, возвращаем ошибку */ if(strtolower($sUser)==strtolower($this->oUserCurrent->getLogin())) { @@ -1166,10 +1175,10 @@ class ActionBlog extends Action { 'bStateError'=>true, 'sMsgTitle'=>$this->Lang_Get('error'), 'sMsg'=>$this->Lang_Get('blog_user_invite_add_self') - ); + ); continue; } - + /** * Если пользователь не найден или неактивен, * возвращаем ошибку @@ -1192,7 +1201,7 @@ class ActionBlog extends Action { $oBlogUserNew->setBlogId($oBlog->getId()); $oBlogUserNew->setUserId($oUser->getId()); $oBlogUserNew->setUserRole(ModuleBlog::BLOG_USER_ROLE_INVITE); - + if($this->Blog_AddRelationBlogUser($oBlogUserNew)) { $aResult[]=array( 'bStateError'=>false, @@ -1208,7 +1217,7 @@ class ActionBlog extends Action { 'sMsgTitle'=>$this->Lang_Get('error'), 'sMsg'=>$this->Lang_Get('system_error'), 'sUserLogin'=>$sUser - ); + ); } } else { /** @@ -1220,10 +1229,10 @@ class ActionBlog extends Action { $sErrorMessage=$this->Lang_Get('blog_user_already_invited',array('login'=>$sUser)); break; case ($aBlogUsers[$oUser->getId()]->getUserRole()>ModuleBlog::BLOG_USER_ROLE_GUEST): - $sErrorMessage=$this->Lang_Get('blog_user_already_exists',array('login'=>$sUser)); + $sErrorMessage=$this->Lang_Get('blog_user_already_exists',array('login'=>$sUser)); break; case ($aBlogUsers[$oUser->getId()]->getUserRole()==ModuleBlog::BLOG_USER_ROLE_REJECT): - $sErrorMessage=$this->Lang_Get('blog_user_already_reject',array('login'=>$sUser)); + $sErrorMessage=$this->Lang_Get('blog_user_already_reject',array('login'=>$sUser)); break; default: $sErrorMessage=$this->Lang_Get('system_error'); @@ -1235,9 +1244,9 @@ class ActionBlog extends Action { 'sUserLogin'=>$sUser ); continue; - } + } } - + /** * Передаем во вьевер массив с результатами обработки по каждому пользователю */ @@ -1245,18 +1254,18 @@ class ActionBlog extends Action { } /** - * Обработка ajax запроса на отправку + * Обработка ajax запроса на отправку * повторного приглашения вступить в закрытый блог */ protected function AjaxReBlogInvite() { $this->Viewer_SetResponseAjax('json'); $sUserId=getRequest('idUser',null,'post'); $sBlogId=getRequest('idBlog',null,'post'); - + /** * Если пользователь не авторизирован, возвращаем ошибку */ - if (!$this->User_IsAuthorization()) { + if (!$this->User_IsAuthorization()) { $this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error')); return; } @@ -1266,7 +1275,7 @@ class ActionBlog extends Action { */ if(!$oBlog=$this->Blog_GetBlogById($sBlogId)) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); - return; + return; } if (!$oUser=$this->User_GetUserById($sUserId) or $oUser->getActivate()!=1) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); @@ -1275,23 +1284,23 @@ class ActionBlog extends Action { /** * Проверяем, имеет ли право текущий пользователь добавлять invite в blog */ - $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); + $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); $bIsAdministratorBlog=$oBlogUser ? $oBlogUser->getIsAdministrator() : false; if ($oBlog->getOwnerId()!=$this->oUserCurrent->getId() and !$this->oUserCurrent->isAdministrator() and !$bIsAdministratorBlog) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); - return; + return; } - + $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$oUser->getId()); if ($oBlogUser->getUserRole()==ModuleBlog::BLOG_USER_ROLE_INVITE) { $this->SendBlogInvite($oBlog,$oUser); $this->Message_AddNoticeSingle($this->Lang_Get('blog_user_invite_add_ok',array('login'=>$oUser->getLogin())),$this->Lang_Get('attention')); } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); - } + } } /** - * Выполняет отправку приглашения в блог + * Выполняет отправку приглашения в блог * (по внутренней почте и на email) * * @param ModuleBlog_EntityBlog $oBlog @@ -1333,25 +1342,25 @@ class ActionBlog extends Action { ); /** * Удаляем отправляющего юзера из переписки - */ + */ $this->Talk_DeleteTalkUserByArray($oTalk->getId(),$this->oUserCurrent->getId()); } - + /** * Обработка отправленого пользователю приглашения вступить в блог */ - protected function EventInviteBlog() { + protected function EventInviteBlog() { require_once Config::Get('path.root.engine').'/lib/external/XXTEA/encrypt.php'; $sCode=xxtea_decrypt(base64_decode(rawurldecode(getRequest('code'))), Config::Get('module.blog.encrypt')); if (!$sCode) { return $this->EventNotFound(); } - + list($sBlogId,$sUserId)=explode('_',$sCode,2); - + $sAction=$this->GetParam(0); - + /** * Получаем текущего пользователя */ @@ -1371,7 +1380,7 @@ class ActionBlog extends Action { if((!$oBlog=$this->Blog_GetBlogById($sBlogId)) || $oBlog->getType()!='close') { return $this->EventNotFound(); } - + /** * Получаем связь "блог-пользователь" и проверяем, * чтобы ее тип был INVITE или REJECT @@ -1383,14 +1392,14 @@ class ActionBlog extends Action { $sMessage=$this->Lang_Get('blog_user_invite_already_done'); $this->Message_AddError($sMessage,$this->Lang_Get('error'),true); Router::Location(Router::GetPath('talk')); - return ; + return ; } if(!in_array($oBlogUser->getUserRole(),array(ModuleBlog::BLOG_USER_ROLE_INVITE,ModuleBlog::BLOG_USER_ROLE_REJECT))) { $this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'),true); Router::Location(Router::GetPath('talk')); return ; } - + /** * Обновляем роль пользователя до читателя */ @@ -1398,7 +1407,7 @@ class ActionBlog extends Action { if(!$this->Blog_UpdateRelationBlogUser($oBlogUser)) { $this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'),true); Router::Location(Router::GetPath('talk')); - return ; + return ; } if ($sAction=='accept') { /** @@ -1409,10 +1418,14 @@ class ActionBlog extends Action { $sMessage=$this->Lang_Get('blog_user_invite_accept'); } else { $sMessage=$this->Lang_Get('blog_user_invite_reject'); - } + } + /** + * Добавляем событие в ленту + */ + $this->Stream_write($oBlogUser->getId(), ModuleStream::EVENT_JOIN_BLOG, $oBlog->getId()); $this->Message_AddNotice($sMessage,$this->Lang_Get('attention'),true); - - Router::Location(Router::GetPath('talk')); + + Router::Location(Router::GetPath('talk')); } /** @@ -1454,7 +1467,7 @@ class ActionBlog extends Action { /** * Если указан идентификатор блога для перемещения, * то делаем попытку переместить топики. - * + * * (-1) - выбран пункт меню "удалить топики". */ if($sBlogIdNew=getRequest('topic_move_to') and ($sBlogIdNew!=-1) and is_array($aTopics) and count($aTopics)) { @@ -1476,21 +1489,21 @@ class ActionBlog extends Action { } break; default: - return parent::EventNotFound(); + return parent::EventNotFound(); } /** * Удаляяем блог и перенаправляем пользователя к списку блогов */ - $this->Hook_Run('blog_delete_before', array('sBlogId'=>$sBlogId)); + $this->Hook_Run('blog_delete_before', array('sBlogId'=>$sBlogId)); if($this->Blog_DeleteBlog($sBlogId)) { - $this->Hook_Run('blog_delete_after', array('sBlogId'=>$sBlogId)); + $this->Hook_Run('blog_delete_after', array('sBlogId'=>$sBlogId)); $this->Message_AddNoticeSingle($this->Lang_Get('blog_admin_delete_success'),$this->Lang_Get('attention'),true); Router::Location(Router::GetPath('blogs')); } else { Router::Location($oBlog->getUrlFull()); } } - + /** * Получение описания блога * @@ -1498,21 +1511,21 @@ class ActionBlog extends Action { protected function AjaxBlogInfo() { $this->Viewer_SetResponseAjax('json'); $sBlogId=getRequest('idBlog',null,'post'); - + if ($sBlogId==0) { - if ($this->oUserCurrent) { + if ($this->oUserCurrent) { $oBlog=$this->Blog_GetPersonalBlogByUserId($this->oUserCurrent->getId()); } } else { $oBlog=$this->Blog_GetBlogById($sBlogId); } - if ($oBlog) { + if ($oBlog) { $sText=$oBlog->getDescription(); $this->Viewer_AssignAjax('sText',$sText); } } - + /** * Подключение/отключение к блогу * @@ -1523,18 +1536,18 @@ class ActionBlog extends Action { $this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error')); return; } - + $idBlog=getRequest('idBlog',null,'post'); if (!($oBlog=$this->Blog_GetBlogById($idBlog))) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); return; } - + if (!in_array($oBlog->getType(),array('open','close'))) { $this->Message_AddErrorSingle($this->Lang_Get('blog_join_error_invite'),$this->Lang_Get('error')); return; } - + $oBlogUser=$this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(),$this->oUserCurrent->getId()); if (!$oBlogUser || ($oBlogUser->getUserRole()getType()=='close')) { if ($oBlog->getOwnerId()!=$this->oUserCurrent->getId()) { @@ -1559,45 +1572,45 @@ class ActionBlog extends Action { * Увеличиваем число читателей блога */ $oBlog->setCountUser($oBlog->getCountUser()+1); - $this->Blog_UpdateBlog($oBlog); + $this->Blog_UpdateBlog($oBlog); $this->Viewer_AssignAjax('iCountUser',$oBlog->getCountUser()); - } else { + } else { $sMsg=($oBlog->getType()=='close') ? $this->Lang_Get('blog_join_error_invite') : $this->Lang_Get('system_error'); $this->Message_AddErrorSingle($sMsg,$this->Lang_Get('error')); return; } - } else { + } else { $this->Message_AddErrorSingle($this->Lang_Get('blog_join_error_self'),$this->Lang_Get('attention')); return; } - } + } if ($oBlogUser && $oBlogUser->getUserRole()>ModuleBlog::BLOG_USER_ROLE_GUEST) { /** * Покидаем блог - */ + */ if ($this->Blog_DeleteRelationBlogUser($oBlogUser)) { $this->Message_AddNoticeSingle($this->Lang_Get('blog_leave_ok'),$this->Lang_Get('attention')); - $this->Viewer_AssignAjax('bState',false); + $this->Viewer_AssignAjax('bState',false); /** * Уменьшаем число читателей блога */ $oBlog->setCountUser($oBlog->getCountUser()-1); $this->Blog_UpdateBlog($oBlog); $this->Viewer_AssignAjax('iCountUser',$oBlog->getCountUser()); - } else { + } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error')); return; } - } + } } - + /** * Выполняется при завершении работы экшена * */ - public function EventShutdown() { + public function EventShutdown() { /** * Загружаем в шаблон необходимые переменные */ @@ -1609,7 +1622,7 @@ class ActionBlog extends Action { $this->Viewer_Assign('iCountTopicsPersonalNew',$this->iCountTopicsPersonalNew); $this->Viewer_Assign('iCountTopicsBlogNew',$this->iCountTopicsBlogNew); $this->Viewer_Assign('iCountTopicsNew',$this->iCountTopicsNew); - + $this->Viewer_Assign('BLOG_USER_ROLE_GUEST', ModuleBlog::BLOG_USER_ROLE_GUEST); $this->Viewer_Assign('BLOG_USER_ROLE_USER', ModuleBlog::BLOG_USER_ROLE_USER); $this->Viewer_Assign('BLOG_USER_ROLE_MODERATOR', ModuleBlog::BLOG_USER_ROLE_MODERATOR); diff --git a/classes/actions/ActionProfile.class.php b/classes/actions/ActionProfile.class.php index 910991b3..8e54a098 100644 --- a/classes/actions/ActionProfile.class.php +++ b/classes/actions/ActionProfile.class.php @@ -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()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); diff --git a/classes/actions/ActionStream.class.php b/classes/actions/ActionStream.class.php new file mode 100644 index 00000000..18ab2bb5 --- /dev/null +++ b/classes/actions/ActionStream.class.php @@ -0,0 +1,162 @@ +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')); + } +} \ No newline at end of file diff --git a/classes/actions/ActionTopic.class.php b/classes/actions/ActionTopic.class.php index dd239ddd..4897dfd6 100644 --- a/classes/actions/ActionTopic.class.php +++ b/classes/actions/ActionTopic.class.php @@ -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 { * Получаемый и устанавливаем разрезанный текст по тегу */ 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; } /** diff --git a/classes/blocks/BlockStreamConfig.class.php b/classes/blocks/BlockStreamConfig.class.php new file mode 100644 index 00000000..029ea0fa --- /dev/null +++ b/classes/blocks/BlockStreamConfig.class.php @@ -0,0 +1,13 @@ +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); + } +} \ No newline at end of file diff --git a/classes/modules/stream/Stream.class.php b/classes/modules/stream/Stream.class.php new file mode 100644 index 00000000..b369cbdd --- /dev/null +++ b/classes/modules/stream/Stream.class.php @@ -0,0 +1,189 @@ +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; + } + +} \ No newline at end of file diff --git a/classes/modules/stream/mapper/Stream.mapper.class.php b/classes/modules/stream/mapper/Stream.mapper.class.php new file mode 100644 index 00000000..da10c9a7 --- /dev/null +++ b/classes/modules/stream/mapper/Stream.mapper.class.php @@ -0,0 +1,128 @@ +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); + } + } +} \ No newline at end of file diff --git a/config/config.php b/config/config.php index 9bbc53d7..ca9a8487 100644 --- a/config/config.php +++ b/config/config.php @@ -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'), ); /** diff --git a/templates/language/russian.php b/templates/language/russian.php index 7271ade8..0cd501fa 100644 --- a/templates/language/russian.php +++ b/templates/language/russian.php @@ -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 */ diff --git a/templates/skin/new/actions/ActionStream/list.tpl b/templates/skin/new/actions/ActionStream/list.tpl new file mode 100644 index 00000000..73955497 --- /dev/null +++ b/templates/skin/new/actions/ActionStream/list.tpl @@ -0,0 +1,10 @@ +{include file='header.tpl'} + +{include file='stream_list.tpl'} + +{if count($aStreamEvents)} +
+ + {$aLang.stream_get_more}... +{/if} +{include file='footer.tpl'} \ No newline at end of file diff --git a/templates/skin/new/block.streamConfig.tpl b/templates/skin/new/block.streamConfig.tpl new file mode 100644 index 00000000..6bcafbcb --- /dev/null +++ b/templates/skin/new/block.streamConfig.tpl @@ -0,0 +1,72 @@ +{literal} + +{/literal} +
+
+
+

{$aLang.stream_block_config_title}

+ +
    + {foreach from=$STREAM_EVENT_TYPE item=aEventType} +
  • + {$aEventType.name} +
  • + {/foreach} +
+
+ {$aLang.stream_block_users_title}
+ + {$aLang.stream_block_config_append} +
    + {if count($aStreamSubscribedUsers)} + {foreach from=$aStreamSubscribedUsers item=oUser} + {assign var=iUserId value=$oUser->getId()} + {if !isset($aStreamFriends.$iUserId)} +
  • + {$oUser->getLogin()} +
  • + {/if} + {/foreach} + {/if} +
+ {if count($aStreamFriends)} + {$aLang.stream_block_users_friends} +
    + {foreach from=$aStreamFriends item=oUser} + {assign var=iUserId value=$oUser->getId()} +
  • + {$oUser->getLogin()} +
  • + {/foreach} +
+ {/if} +
+
+
\ No newline at end of file diff --git a/templates/skin/new/css/style.css b/templates/skin/new/css/style.css index eef9fc4f..7a1caa6b 100644 --- a/templates/skin/new/css/style.css +++ b/templates/skin/new/css/style.css @@ -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;} diff --git a/templates/skin/new/js/stream.js b/templates/skin/new/js/stream.js new file mode 100644 index 00000000..21638e2f --- /dev/null +++ b/templates/skin/new/js/stream.js @@ -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; \ No newline at end of file diff --git a/templates/skin/new/stream_list.tpl b/templates/skin/new/stream_list.tpl new file mode 100644 index 00000000..96ef0700 --- /dev/null +++ b/templates/skin/new/stream_list.tpl @@ -0,0 +1,50 @@ +{if count($aStreamEvents)} +
    + {foreach from=$aStreamEvents item=aEvent} + {assign var=initiatorId value=$aEvent.initiator} + {assign var=initiator value=$aStreamUsers.$initiatorId} +
  • {date_format date=$aEvent.date_added}: {$aLang.stream_list_user} {$initiator->getLogin()} + {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} {$topic->getTitle()} + {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} {$topic->getTitle()} + {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} {$blog->getTitle()} + {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} {$blog->getTitle()} + {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} {$topic->getTitle()} + {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} {$topic->getTitle()} + {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} {$user->getLogin()} + {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} {$blog->getTitle()} + {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} {$user->getLogin()} + {/if} +
  • + {/foreach} +
+{/if} \ No newline at end of file