1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-07-03 06:55:03 +03:00
ifhub.club/classes/modules/comment/Comment.class.php

890 lines
33 KiB
PHP
Raw Normal View History

<?php
2008-09-21 09:36:57 +03:00
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Модуль для работы с комментариями
*
*/
class ModuleComment extends Module {
2009-06-23 20:06:19 +03:00
protected $oMapper;
2009-06-28 17:04:44 +03:00
protected $oUserCurrent=null;
2008-09-21 09:36:57 +03:00
/**
* Инициализация
*
*/
public function Init() {
$this->oMapper=Engine::GetMapper(__CLASS__);
2009-06-28 17:04:44 +03:00
$this->oUserCurrent=$this->User_GetUserCurrent();
2008-09-21 09:36:57 +03:00
}
/**
* Получить коммент по айдишнику
*
* @param unknown_type $sId
* @return unknown
*/
public function GetCommentById($sId) {
2009-06-23 20:06:19 +03:00
$aComments=$this->GetCommentsAdditionalData($sId);
if (isset($aComments[$sId])) {
return $aComments[$sId];
}
return null;
}
/**
* Получает уникальный коммент, это помогает спастись от дублей комментов
*
2009-06-23 20:06:19 +03:00
* @param unknown_type $sTargetId
* @param unknown_type $sTargetType
* @param unknown_type $sUserId
* @param unknown_type $sCommentPid
* @param unknown_type $sHash
*/
2009-06-23 20:06:19 +03:00
public function GetCommentUnique($sTargetId,$sTargetType,$sUserId,$sCommentPid,$sHash) {
$sId=$this->oMapper->GetCommentUnique($sTargetId,$sTargetType,$sUserId,$sCommentPid,$sHash);
return $this->GetCommentById($sId);
}
2008-09-21 09:36:57 +03:00
/**
* Получить все комменты
*
2009-06-23 20:06:19 +03:00
* @param unknown_type $sTargetType
2008-09-21 09:36:57 +03:00
* @param unknown_type $iPage
* @param unknown_type $iPerPage
* @return unknown
*/
public function GetCommentsAll($sTargetType,$iPage,$iPerPage,$aExcludeTarget=array(),$aExcludeParentTarget=array()) {
$s=serialize($aExcludeTarget).serialize($aExcludeParentTarget);
if (false === ($data = $this->Cache_Get("comment_all_{$sTargetType}_{$iPage}_{$iPerPage}_{$s}"))) {
$data = array('collection'=>$this->oMapper->GetCommentsAll($sTargetType,$iCount,$iPage,$iPerPage,$aExcludeTarget,$aExcludeParentTarget),'count'=>$iCount);
$this->Cache_Set($data, "comment_all_{$sTargetType}_{$iPage}_{$iPerPage}_{$s}", array("comment_new_{$sTargetType}","comment_update_status_{$sTargetType}"), 60*60*24*1);
2008-09-21 09:36:57 +03:00
}
$data['collection']=$this->GetCommentsAdditionalData($data['collection'],array('target','favourite','user'=>array()));
2008-09-21 09:36:57 +03:00
return $data;
}
/**
2009-06-23 20:06:19 +03:00
* Получает дополнительные данные(объекты) для комментов по их ID
*
*/
public function GetCommentsAdditionalData($aCommentId,$aAllowData=array('vote','target','favourite','user'=>array())) {
2009-06-23 20:06:19 +03:00
func_array_simpleflip($aAllowData);
if (!is_array($aCommentId)) {
$aCommentId=array($aCommentId);
}
/**
* Получаем комменты
*/
$aComments=$this->GetCommentsByArrayId($aCommentId);
/**
* Формируем ID дополнительных данных, которые нужно получить
*/
$aUserId=array();
$aTargetId=array('topic'=>array(),'talk'=>array());
foreach ($aComments as $oComment) {
if (isset($aAllowData['user'])) {
$aUserId[]=$oComment->getUserId();
}
if (isset($aAllowData['target'])) {
$aTargetId[$oComment->getTargetType()][]=$oComment->getTargetId();
2010-01-05 19:27:21 +02:00
}
2009-06-23 20:06:19 +03:00
}
/**
* Получаем дополнительные данные
*/
$aUsers=isset($aAllowData['user']) && is_array($aAllowData['user']) ? $this->User_GetUsersAdditionalData($aUserId,$aAllowData['user']) : $this->User_GetUsersAdditionalData($aUserId);
/**
* В зависимости от типа target_type достаем данные
*/
$aTargets=array();
2009-07-26 16:43:16 +03:00
//$aTargets['topic']=isset($aAllowData['target']) && is_array($aAllowData['target']) ? $this->Topic_GetTopicsAdditionalData($aTargetId['topic'],$aAllowData['target']) : $this->Topic_GetTopicsAdditionalData($aTargetId['topic']);
$aTargets['topic']=$this->Topic_GetTopicsAdditionalData($aTargetId['topic'],array('blog'=>array('owner'=>array())));
2009-06-28 17:04:44 +03:00
$aVote=array();
if (isset($aAllowData['vote']) and $this->oUserCurrent) {
$aVote=$this->Vote_GetVoteByArray($aCommentId,'comment',$this->oUserCurrent->getId());
}
2010-01-05 19:27:21 +02:00
if (isset($aAllowData['favourite']) and $this->oUserCurrent) {
$aFavouriteComments=$this->Favourite_GetFavouritesByArray($aCommentId,'comment',$this->oUserCurrent->getId());
}
2009-06-23 20:06:19 +03:00
/**
* Добавляем данные к результату
*/
foreach ($aComments as $oComment) {
if (isset($aUsers[$oComment->getUserId()])) {
$oComment->setUser($aUsers[$oComment->getUserId()]);
} else {
$oComment->setUser(null); // или $oComment->setUser(new ModuleUser_EntityUser());
2009-06-23 20:06:19 +03:00
}
if (isset($aTargets[$oComment->getTargetType()][$oComment->getTargetId()])) {
$oComment->setTarget($aTargets[$oComment->getTargetType()][$oComment->getTargetId()]);
} else {
$oComment->setTarget(null);
}
2009-06-28 17:04:44 +03:00
if (isset($aVote[$oComment->getId()])) {
$oComment->setVote($aVote[$oComment->getId()]);
} else {
$oComment->setVote(null);
}
if (isset($aFavouriteComments[$oComment->getId()])) {
$oComment->setIsFavourite(true);
} else {
$oComment->setIsFavourite(false);
}
}
2009-06-23 20:06:19 +03:00
return $aComments;
}
2009-06-23 20:06:19 +03:00
/**
* Список комментов по ID
*
* @param array $aUserId
*/
public function GetCommentsByArrayId($aCommentId) {
2009-08-08 12:33:32 +03:00
if (!$aCommentId) {
return array();
}
2009-10-10 22:13:14 +03:00
if (Config::Get('sys.cache.solid')) {
2009-08-08 12:33:32 +03:00
return $this->GetCommentsByArrayIdSolid($aCommentId);
}
2009-06-23 20:06:19 +03:00
if (!is_array($aCommentId)) {
$aCommentId=array($aCommentId);
}
$aCommentId=array_unique($aCommentId);
$aComments=array();
$aCommentIdNotNeedQuery=array();
/**
* Делаем мульти-запрос к кешу
*/
$aCacheKeys=func_build_cache_keys($aCommentId,'comment_');
2009-08-08 12:33:32 +03:00
if (false !== ($data = $this->Cache_Get($aCacheKeys))) {
2009-06-23 20:06:19 +03:00
/**
* проверяем что досталось из кеша
*/
foreach ($aCacheKeys as $sValue => $sKey ) {
if (array_key_exists($sKey,$data)) {
if ($data[$sKey]) {
$aComments[$data[$sKey]->getId()]=$data[$sKey];
} else {
$aCommentIdNotNeedQuery[]=$sValue;
}
}
}
}
/**
* Смотрим каких комментов не было в кеше и делаем запрос в БД
*/
$aCommentIdNeedQuery=array_diff($aCommentId,array_keys($aComments));
$aCommentIdNeedQuery=array_diff($aCommentIdNeedQuery,$aCommentIdNotNeedQuery);
$aCommentIdNeedStore=$aCommentIdNeedQuery;
if ($data = $this->oMapper->GetCommentsByArrayId($aCommentIdNeedQuery)) {
foreach ($data as $oComment) {
/**
* Добавляем к результату и сохраняем в кеш
*/
$aComments[$oComment->getId()]=$oComment;
2009-08-08 12:33:32 +03:00
$this->Cache_Set($oComment, "comment_{$oComment->getId()}", array(), 60*60*24*4);
2009-06-23 20:06:19 +03:00
$aCommentIdNeedStore=array_diff($aCommentIdNeedStore,array($oComment->getId()));
}
}
/**
* Сохраняем в кеш запросы не вернувшие результата
*/
foreach ($aCommentIdNeedStore as $sId) {
2009-07-26 16:43:16 +03:00
$this->Cache_Set(null, "comment_{$sId}", array(), 60*60*24*4);
2009-06-23 20:06:19 +03:00
}
/**
* Сортируем результат согласно входящему массиву
*/
$aComments=func_array_sort_by_keys($aComments,$aCommentId);
return $aComments;
}
2009-08-08 12:33:32 +03:00
public function GetCommentsByArrayIdSolid($aCommentId) {
if (!is_array($aCommentId)) {
$aCommentId=array($aCommentId);
}
$aCommentId=array_unique($aCommentId);
$aComments=array();
$s=join(',',$aCommentId);
if (false === ($data = $this->Cache_Get("comment_id_{$s}"))) {
$data = $this->oMapper->GetCommentsByArrayId($aCommentId);
foreach ($data as $oComment) {
$aComments[$oComment->getId()]=$oComment;
}
$this->Cache_Set($aComments, "comment_id_{$s}", array("comment_update"), 60*60*24*1);
return $aComments;
}
return $data;
}
/**
* Получть все комменты сгрупированные по топику(для вывода прямого эфира)
2008-09-21 09:36:57 +03:00
*
2009-06-23 20:06:19 +03:00
* @param unknown_type $sTargetType
2008-09-21 09:36:57 +03:00
* @param unknown_type $iLimit
* @return unknown
*/
2009-06-23 20:06:19 +03:00
public function GetCommentsOnline($sTargetType,$iLimit) {
/**
* Исключаем из выборки идентификаторы закрытых блогов (target_parent_id)
*/
$aCloseBlogs = ($this->oUserCurrent)
? $this->Blog_GetInaccessibleBlogsByUser($this->oUserCurrent)
: $this->Blog_GetInaccessibleBlogsByUser();
$s=serialize($aCloseBlogs);
if (false === ($data = $this->Cache_Get("comment_online_{$sTargetType}_{$s}_{$iLimit}"))) {
$data = $this->oMapper->GetCommentsOnline($sTargetType,$aCloseBlogs,$iLimit);
$this->Cache_Set($data, "comment_online_{$sTargetType}_{$s}_{$iLimit}", array("comment_online_update_{$sTargetType}"), 60*60*24*1);
2008-09-21 09:36:57 +03:00
}
2009-06-23 20:06:19 +03:00
$data=$this->GetCommentsAdditionalData($data);
2008-09-21 09:36:57 +03:00
return $data;
}
/**
* Получить комменты по юзеру
*
* @param string $sId
* @param string $sTargetType
* @param int $iPage
* @param int $iPerPage
* @return array
2008-09-21 09:36:57 +03:00
*/
2009-06-23 20:06:19 +03:00
public function GetCommentsByUserId($sId,$sTargetType,$iPage,$iPerPage) {
/**
* Исключаем из выборки идентификаторы закрытых блогов
*/
$aCloseBlogs = ($this->oUserCurrent && $sId==$this->oUserCurrent->getId())
? array()
: $this->Blog_GetInaccessibleBlogsByUser();
$s=serialize($aCloseBlogs);
2009-09-20 21:43:20 +03:00
if (false === ($data = $this->Cache_Get("comment_user_{$sId}_{$sTargetType}_{$iPage}_{$iPerPage}_{$s}"))) {
$data = array('collection'=>$this->oMapper->GetCommentsByUserId($sId,$sTargetType,$iCount,$iPage,$iPerPage,array(),$aCloseBlogs),'count'=>$iCount);
2009-09-20 21:43:20 +03:00
$this->Cache_Set($data, "comment_user_{$sId}_{$sTargetType}_{$iPage}_{$iPerPage}_{$s}", array("comment_new_user_{$sId}_{$sTargetType}","comment_update_status_{$sTargetType}"), 60*60*24*2);
2008-09-21 09:36:57 +03:00
}
2009-06-23 20:06:19 +03:00
$data['collection']=$this->GetCommentsAdditionalData($data['collection']);
return $data;
2008-09-21 09:36:57 +03:00
}
/**
* Получает количество комментариев одного пользователя
*
* @param string $sId
* @param string $sTargetType
* @return int
*/
2009-06-23 20:06:19 +03:00
public function GetCountCommentsByUserId($sId,$sTargetType) {
/**
* Исключаем из выборки идентификаторы закрытых блогов
*/
$aCloseBlogs = ($this->oUserCurrent && $sId==$this->oUserCurrent->getId())
? array()
: $this->Blog_GetInaccessibleBlogsByUser();
$s=serialize($aCloseBlogs);
2009-09-20 21:43:20 +03:00
if (false === ($data = $this->Cache_Get("comment_count_user_{$sId}_{$sTargetType}_{$s}"))) {
$data = $this->oMapper->GetCountCommentsByUserId($sId,$sTargetType,array(),$aCloseBlogs);
2009-09-20 16:26:09 +03:00
$this->Cache_Set($data, "comment_count_user_{$sId}_{$sTargetType}", array("comment_new_user_{$sId}_{$sTargetType}","comment_update_status_{$sTargetType}"), 60*60*24*2);
2008-09-21 09:36:57 +03:00
}
return $data;
2008-09-21 09:36:57 +03:00
}
/**
* Получить комменты по рейтингу и дате
*
* @param string $sDate
* @param string $sTargetType
* @param int $iLimit
* @return array
2008-09-21 09:36:57 +03:00
*/
2009-06-23 20:06:19 +03:00
public function GetCommentsRatingByDate($sDate,$sTargetType,$iLimit=20) {
/**
* Выбираем топики, комметарии к которым являются недоступными для пользователя
*/
$aCloseBlogs = ($this->oUserCurrent)
? $this->Blog_GetInaccessibleBlogsByUser($this->oUserCurrent)
: $this->Blog_GetInaccessibleBlogsByUser();
$s=serialize($aCloseBlogs);
2008-09-21 09:36:57 +03:00
//т.к. время передаётся с точностью 1 час то можно по нему замутить кеширование
if (false === ($data = $this->Cache_Get("comment_rating_{$sDate}_{$sTargetType}_{$iLimit}_{$s}"))) {
$data = $this->oMapper->GetCommentsRatingByDate($sDate,$sTargetType,$iLimit,array(),$aCloseBlogs);
$this->Cache_Set($data, "comment_rating_{$sDate}_{$sTargetType}_{$iLimit}_{$s}", array("comment_new_{$sTargetType}","comment_update_status_{$sTargetType}","comment_update_rating_{$sTargetType}"), 60*60*24*2);
2008-09-21 09:36:57 +03:00
}
2009-06-23 20:06:19 +03:00
$data=$this->GetCommentsAdditionalData($data);
return $data;
2008-09-21 09:36:57 +03:00
}
/**
* Получить комменты для топика
*
* @param string $sId
* @param string $sTargetType
* @return object
2008-09-21 09:36:57 +03:00
*/
public function GetCommentsByTargetId($sId,$sTargetType,$iPage=1,$iPerPage=0) {
if (Config::Get('module.comment.use_nested')) {
return $this->GetCommentsTreeByTargetId($sId,$sTargetType,$iPage,$iPerPage);
}
if (false === ($aCommentsRec = $this->Cache_Get("comment_target_{$sId}_{$sTargetType}"))) {
2009-06-23 20:06:19 +03:00
$aCommentsRow=$this->oMapper->GetCommentsByTargetId($sId,$sTargetType);
2008-09-21 09:36:57 +03:00
if (count($aCommentsRow)) {
$aCommentsRec=$this->BuildCommentsRecursive($aCommentsRow);
2008-09-21 09:36:57 +03:00
}
2009-06-23 20:06:19 +03:00
$this->Cache_Set($aCommentsRec, "comment_target_{$sId}_{$sTargetType}", array("comment_new_{$sTargetType}_{$sId}"), 60*60*24*2);
}
2009-06-23 20:06:19 +03:00
if (!isset($aCommentsRec['comments'])) {
return array('comments'=>array(),'iMaxIdComment'=>0);
2009-11-10 20:49:53 +02:00
}
2009-06-23 20:06:19 +03:00
$aComments=$aCommentsRec;
$aComments['comments']=$this->GetCommentsAdditionalData(array_keys($aCommentsRec['comments']));
2009-06-23 20:06:19 +03:00
foreach ($aComments['comments'] as $oComment) {
$oComment->setLevel($aCommentsRec['comments'][$oComment->getId()]);
}
return $aComments;
2008-09-21 09:36:57 +03:00
}
/**
* Получает комменты используя nested set
*
* @param unknown_type $sId
* @param unknown_type $sTargetType
* @return unknown
*/
public function GetCommentsTreeByTargetId($sId,$sTargetType,$iPage=1,$iPerPage=0) {
if (!Config::Get('module.comment.nested_page_reverse') and $iPerPage and $iCountPage=ceil($this->GetCountCommentsRootByTargetId($sId,$sTargetType)/$iPerPage)) {
$iPage=$iCountPage-$iPage+1;
}
$iPage=$iPage<1 ? 1 : $iPage;
if (false === ($aReturn = $this->Cache_Get("comment_tree_target_{$sId}_{$sTargetType}_{$iPage}_{$iPerPage}"))) {
/**
* Нужно или нет использовать постраничное разбиение комментариев
*/
if ($iPerPage) {
$aComments=$this->oMapper->GetCommentsTreePageByTargetId($sId,$sTargetType,$iCount,$iPage,$iPerPage);
} else {
$aComments=$this->oMapper->GetCommentsTreeByTargetId($sId,$sTargetType);
$iCount=count($aComments);
}
$iMaxIdComment=count($aComments) ? max($aComments) : 0;
$aReturn=array('comments'=>$aComments,'iMaxIdComment'=>$iMaxIdComment,'count'=>$iCount);
$this->Cache_Set($aReturn, "comment_tree_target_{$sId}_{$sTargetType}_{$iPage}_{$iPerPage}", array("comment_new_{$sTargetType}_{$sId}"), 60*60*24*2);
}
$aReturn['comments']=$this->GetCommentsAdditionalData($aReturn['comments']);
return $aReturn;
}
public function GetCountCommentsRootByTargetId($sId,$sTargetType) {
return $this->oMapper->GetCountCommentsRootByTargetId($sId,$sTargetType);
}
public function GetPageCommentByTargetId($sId,$sTargetType,$oComment) {
if (!Config::Get('module.comment.nested_per_page')) {
return 1;
}
if (is_numeric($oComment)) {
if (!($oComment=$this->GetCommentById($oComment))) {
return false;
}
if ($oComment->getTargetId()!=$sId or $oComment->getTargetType()!=$sTargetType) {
return false;
}
}
/**
* Получаем корневого родителя
*/
if ($oComment->getPid()) {
if (!($oCommentRoot=$this->oMapper->GetCommentRootByTargetIdAndChildren($sId,$sTargetType,$oComment->getLeft()))) {
return false;
}
} else {
$oCommentRoot=$oComment;
}
$iCount=ceil($this->oMapper->GetCountCommentsAfterByTargetId($sId,$sTargetType,$oCommentRoot->getLeft())/Config::Get('module.comment.nested_per_page'));
if (!Config::Get('module.comment.nested_page_reverse') and $iCountPage=ceil($this->GetCountCommentsRootByTargetId($sId,$sTargetType)/Config::Get('module.comment.nested_per_page'))) {
$iCount=$iCountPage-$iCount+1;
}
return $iCount ? $iCount : 1;
}
2008-09-21 09:36:57 +03:00
/**
2009-06-23 20:06:19 +03:00
* Добавляет коммент
2008-09-21 09:36:57 +03:00
*
* @param ModuleComment_EntityComment $oComment
* @return bool
2008-09-21 09:36:57 +03:00
*/
public function AddComment(ModuleComment_EntityComment $oComment) {
if (Config::Get('module.comment.use_nested')) {
$sId=$this->oMapper->AddCommentTree($oComment);
} else {
$sId=$this->oMapper->AddComment($oComment);
}
if ($sId) {
2009-06-23 20:06:19 +03:00
if ($oComment->getTargetType()=='topic') {
$this->Topic_increaseTopicCountComment($oComment->getTargetId());
}
//чистим зависимые кеши
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_new_{$oComment->getTargetType()}","comment_new_user_{$oComment->getUserId()}_{$oComment->getTargetType()}","comment_new_{$oComment->getTargetType()}_{$oComment->getTargetId()}"));
$oComment->setId($sId);
return $oComment;
}
return false;
}
2008-09-21 09:36:57 +03:00
/**
2009-06-23 20:06:19 +03:00
* Обновляет коммент
2008-09-21 09:36:57 +03:00
*
* @param ModuleComment_EntityComment $oComment
* @return bool
2008-09-21 09:36:57 +03:00
*/
public function UpdateComment(ModuleComment_EntityComment $oComment) {
2009-06-23 20:06:19 +03:00
if ($this->oMapper->UpdateComment($oComment)) {
2008-09-21 09:36:57 +03:00
//чистим зависимые кеши
2010-04-17 20:55:22 +03:00
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_update","comment_update_{$oComment->getTargetType()}_{$oComment->getTargetId()}"));
2009-07-26 16:43:16 +03:00
$this->Cache_Delete("comment_{$oComment->getId()}");
2009-06-23 20:06:19 +03:00
return true;
2008-09-21 09:36:57 +03:00
}
return false;
2009-06-23 20:06:19 +03:00
}
2008-09-21 09:36:57 +03:00
/**
2009-06-23 20:06:19 +03:00
* Обновляет рейтинг у коммента
2008-09-21 09:36:57 +03:00
*
* @param ModuleComment_EntityComment $oComment
* @return bool
2008-09-21 09:36:57 +03:00
*/
public function UpdateCommentRating(ModuleComment_EntityComment $oComment) {
2009-06-23 20:06:19 +03:00
if ($this->oMapper->UpdateComment($oComment)) {
//чистим зависимые кеши
2009-11-10 20:49:53 +02:00
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_update_rating_{$oComment->getTargetType()}"));
2009-07-26 16:43:16 +03:00
$this->Cache_Delete("comment_{$oComment->getId()}");
2008-09-21 09:36:57 +03:00
return true;
}
return false;
2009-06-23 20:06:19 +03:00
}
2008-09-21 09:36:57 +03:00
/**
2009-06-23 20:06:19 +03:00
* Обновляет статус у коммента - delete или publish
2008-09-21 09:36:57 +03:00
*
* @param ModuleComment_EntityComment $oComment
* @return bool
2008-09-21 09:36:57 +03:00
*/
public function UpdateCommentStatus(ModuleComment_EntityComment $oComment) {
if ($this->oMapper->UpdateComment($oComment)) {
/**
* Если комментарий удаляется, удаляем его из прямого эфира
*/
if($oComment->getDelete()) $this->DeleteCommentOnlineByArrayId($oComment->getId(),$oComment->getTargetType());
2010-06-05 01:05:15 +03:00
/**
* Обновляем избранное
*/
$this->Favourite_SetFavouriteTargetPublish($oComment->getId(),'comment',!$oComment->getDelete());
/**
* Чистим зависимые кеши
*/
2009-11-10 20:49:53 +02:00
if(Config::Get('sys.cache.solid')){
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_update"));
}
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_update_status_{$oComment->getTargetType()}"));
$this->Cache_Delete("comment_{$oComment->getId()}");
2008-09-21 09:36:57 +03:00
return true;
}
return false;
}
2009-06-23 20:06:19 +03:00
/**
* Устанавливает publish у коммента
*
* @param string $sTargetId
* @param string $sTargetType
* @param int $iPublish
* @return bool
2009-06-23 20:06:19 +03:00
*/
public function SetCommentsPublish($sTargetId,$sTargetType,$iPublish) {
2009-11-20 02:59:01 +02:00
if(!$aComments = $this->GetCommentsByTargetId($sTargetId,$sTargetType)) {
return false;
}
2009-11-20 02:59:01 +02:00
if(!isset($aComments['comments']) or count($aComments)==0) {
return;
}
2009-06-23 20:06:19 +03:00
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_update_status_{$sTargetType}"));
/**
* Если статус публикации успешно изменен, то меняем статус в отметке "избранное".
* Если комментарии снимаются с публикации, удаляем их из прямого эфира.
*/
if($this->oMapper->SetCommentsPublish($sTargetId,$sTargetType,$iPublish)){
2009-11-20 02:59:01 +02:00
$this->Favourite_SetFavouriteTargetPublish(array_keys($aComments['comments']),'comment',$iPublish);
if($iPublish!=1) $this->DeleteCommentOnlineByTargetId($sTargetId,$sTargetType);
return true;
}
return false;
2009-06-23 20:06:19 +03:00
}
/**
* Удаляет коммент из прямого эфира
*
2009-06-23 20:06:19 +03:00
* @param unknown_type $sTargetId
* @param unknown_type $sTargetType
* @return unknown
*/
2009-06-23 20:06:19 +03:00
public function DeleteCommentOnlineByTargetId($sTargetId,$sTargetType) {
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_online_update_{$sTargetType}"));
return $this->oMapper->DeleteCommentOnlineByTargetId($sTargetId,$sTargetType);
}
/**
* Добавляет новый коммент в прямой эфир
*
* @param ModuleComment_EntityCommentOnline $oCommentOnline
*/
public function AddCommentOnline(ModuleComment_EntityCommentOnline $oCommentOnline) {
2009-06-23 20:06:19 +03:00
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_online_update_{$oCommentOnline->getTargetType()}"));
return $this->oMapper->AddCommentOnline($oCommentOnline);
}
/**
2009-06-23 20:06:19 +03:00
* Получить новые комменты для топика
*
* @param unknown_type $sId
2009-06-23 20:06:19 +03:00
* @param unknown_type $sTargetType
* @param unknown_type $sIdCommentLast - last read comment
* @return unknown
*/
2009-06-23 20:06:19 +03:00
public function GetCommentsNewByTargetId($sId,$sTargetType,$sIdCommentLast) {
if (false === ($aComments = $this->Cache_Get("comment_target_{$sId}_{$sTargetType}_{$sIdCommentLast}"))) {
$aComments=$this->oMapper->GetCommentsNewByTargetId($sId,$sTargetType,$sIdCommentLast);
$this->Cache_Set($aComments, "comment_target_{$sId}_{$sTargetType}_{$sIdCommentLast}", array("comment_new_{$sTargetType}_{$sId}"), 60*60*24*1);
}
2009-06-23 20:06:19 +03:00
if (count($aComments)==0) {
return array('comments'=>array(),'iMaxIdComment'=>0);
}
2009-06-23 20:06:19 +03:00
$iMaxIdComment=max($aComments);
$aCmts=$this->GetCommentsAdditionalData($aComments);
if (!class_exists('ModuleViewer')) {
require_once(Config::Get('path.root.engine')."/modules/viewer/Viewer.class.php");
}
$oViewerLocal=$this->Viewer_GetLocalViewer();
2009-06-27 12:10:11 +03:00
$oViewerLocal->Assign('oUserCurrent',$this->User_GetUserCurrent());
$oViewerLocal->Assign('bOneComment',true);
2009-08-28 10:22:54 +03:00
if($sTargetType!='topic') {
$oViewerLocal->Assign('bNoCommentFavourites',true);
}
$aCmt=array();
foreach ($aCmts as $oComment) {
2009-06-27 12:10:11 +03:00
$oViewerLocal->Assign('oComment',$oComment);
$sText=$oViewerLocal->Fetch("comment.tpl");
$aCmt[]=array(
'html' => $sText,
'obj' => $oComment,
2009-06-23 20:06:19 +03:00
);
}
2009-06-23 20:06:19 +03:00
return array('comments'=>$aCmt,'iMaxIdComment'=>$iMaxIdComment);
}
2008-09-21 09:36:57 +03:00
/**
* Строит дерево комментариев
*
* @param unknown_type $aComments
* @param unknown_type $bBegin
* @return unknown
*/
protected function BuildCommentsRecursive($aComments,$bBegin=true) {
static $aResultCommnets;
static $iLevel;
static $iMaxIdComment;
2008-09-21 09:36:57 +03:00
if ($bBegin) {
$aResultCommnets=array();
$iLevel=0;
$iMaxIdComment=0;
2008-09-21 09:36:57 +03:00
}
foreach ($aComments as $aComment) {
$aTemp=$aComment;
if ($aComment['comment_id']>$iMaxIdComment) {
$iMaxIdComment=$aComment['comment_id'];
}
2008-09-21 09:36:57 +03:00
$aTemp['level']=$iLevel;
unset($aTemp['childNodes']);
2009-06-23 20:06:19 +03:00
$aResultCommnets[$aTemp['comment_id']]=$aTemp['level'];
2008-09-21 09:36:57 +03:00
if (isset($aComment['childNodes']) and count($aComment['childNodes'])>0) {
$iLevel++;
$this->BuildCommentsRecursive($aComment['childNodes'],false);
}
}
$iLevel--;
return array('comments'=>$aResultCommnets,'iMaxIdComment'=>$iMaxIdComment);
2008-09-21 09:36:57 +03:00
}
/**
* Получает привязку комментария к ибранному(добавлен ли коммент в избранное у юзера)
*
* @param string $sCommentId
* @param string $sUserId
* @return ModuleFavourite_EntityFavourite|null
*/
public function GetFavouriteComment($sCommentId,$sUserId) {
return $this->Favourite_GetFavourite($sCommentId,'comment',$sUserId);
}
/**
* Получить список избранного по списку айдишников
*
* @param array $aCommentId
*/
public function GetFavouriteCommentsByArray($aCommentId,$sUserId) {
return $this->Favourite_GetFavouritesByArray($aCommentId,'comment',$sUserId);
}
2008-09-21 09:36:57 +03:00
/**
* Получить список избранного по списку айдишников, но используя единый кеш
*
* @param array $aCommentId
* @param int $sUserId
* @return array
*/
public function GetFavouriteCommentsByArraySolid($aCommentId,$sUserId) {
return $this->Favourite_GetFavouritesByArraySolid($aCommentId,'comment',$sUserId);
}
/**
* Получает список комментариев из избранного пользователя
*
* @param string $sUserId
* @param int $iCount
* @param int $iCurrPage
* @param int $iPerPage
* @return array
*/
public function GetCommentsFavouriteByUserId($sUserId,$iCurrPage,$iPerPage) {
$aCloseTopics = array();
/**
* Получаем список идентификаторов избранных комментов
*/
$data = ($this->oUserCurrent && $sUserId==$this->oUserCurrent->getId())
? $this->Favourite_GetFavouritesByUserId($sUserId,'comment',$iCurrPage,$iPerPage,$aCloseTopics)
: $this->Favourite_GetFavouriteOpenCommentsByUserId($sUserId,$iCurrPage,$iPerPage);
/**
* Получаем комменты по переданому массиву айдишников
*/
$data['collection']=$this->GetCommentsAdditionalData($data['collection']);
return $data;
}
/**
* Возвращает число комментариев в избранном
*
* @param string $sUserId
* @return int
*/
public function GetCountCommentsFavouriteByUserId($sUserId) {
return ($this->oUserCurrent && $sUserId==$this->oUserCurrent->getId())
? $this->Favourite_GetCountFavouritesByUserId($sUserId,'comment')
: $this->Favourite_GetCountFavouriteOpenCommentsByUserId($sUserId);
}
/**
* Добавляет комментарий в избранное
*
* @param ModuleFavourite_EntityFavourite $oFavourite
* @return bool
*/
public function AddFavouriteComment(ModuleFavourite_EntityFavourite $oFavourite) {
2009-08-28 10:22:54 +03:00
if( ($oFavourite->getTargetType()=='comment')
&& ($oComment=$this->Comment_GetCommentById($oFavourite->getTargetId()))
&& $oComment->getTargetType()=='topic') {
return $this->Favourite_AddFavourite($oFavourite);
}
return false;
}
/**
* Удаляет комментарий из избранного
*
* @param ModuleFavourite_EntityFavourite $oFavourite
* @return bool
*/
public function DeleteFavouriteComment(ModuleFavourite_EntityFavourite $oFavourite) {
2009-08-28 10:22:54 +03:00
if( ($oFavourite->getTargetType()=='comment')
&& ($oComment=$this->Comment_GetCommentById($oFavourite->getTargetId()))
&& $oComment->getTargetType()=='topic') {
return $this->Favourite_DeleteFavourite($oFavourite);
}
return false;
}
/**
* Удаляет комментарии из избранного по списку
*
* @param array $aCommentId
* @return bool
*/
public function DeleteFavouriteCommentsByArrayId($aCommentId) {
return $this->Favourite_DeleteFavouriteByTargetId($aCommentId, 'comment');
}
/**
* Удаляет комментарии из базы данных
*
* @param array|int $aTargetId
* @param string $sTargetType
* @return bool
*/
public function DeleteCommentByTargetId($aTargetId,$sTargetType) {
if(!is_array($aTargetId)) $aTargetId = array($aTargetId);
/**
* Получаем список идентификаторов удаляемых комментариев
*/
$aCommentsId = array();
foreach ($aTargetId as $sTargetId) {
$aComments=$this->GetCommentsByTargetId($sTargetId,$sTargetType);
$aCommentsId = array_merge($aCommentsId, array_keys($aComments['comments']));
}
/**
* Если ни одного комментария не найдено, выходим
*/
if(!count($aCommentsId)) return true;
/**
* Чистим зависимые кеши
*/
2009-11-10 20:49:53 +02:00
if(Config::Get('sys.cache.solid')) {
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("comment_update","comment_target_{$sTargetId}_{$sTargetType}"));
} else {
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("comment_target_{$sTargetId}_{$sTargetType}"));
/**
* Удаляем кеш для каждого комментария
*/
foreach($aCommentsId as $iCommentId) $this->Cache_Delete("comment_{$iCommentId}");
}
if($this->oMapper->DeleteCommentByTargetId($aTargetId,$sTargetType)){
/**
* Удаляем комментарии из избранного
*/
$this->DeleteFavouriteCommentsByArrayId($aCommentsId);
/**
* Удаляем комментарии к топику из прямого эфира
*/
$this->DeleteCommentOnlineByArrayId($aCommentsId,$sTargetType);
/**
* Удаляем голосование за комментарии
*/
$this->Vote_DeleteVoteByTarget($aCommentsId,'comment');
return true;
}
return false;
}
/**
* Удаляет коммент из прямого эфира по массиву переданных идентификаторов
*
* @param (array|int) $aCommentId
* @param string $sTargetType
* @return bool
*/
public function DeleteCommentOnlineByArrayId($aCommentId,$sTargetType) {
if(!is_array($aCommentId)) $aCommentId = array($aCommentId);
/**
* Чистим кеш
*/
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_online_update_{$sTargetType}"));
return $this->oMapper->DeleteCommentOnlineByArrayId($aCommentId,$sTargetType);
}
/**
* Меняем target parent по массиву идентификаторов
*
* @param string $sParentId
* @param string $sTargetType
* @param array|string $aTargetId
* @return bool
*/
public function UpdateTargetParentByTargetId($sParentId, $sTargetType, $aTargetId) {
if(!is_array($aTargetId)) $aTargetId = array($aTargetId);
// чистим зависимые кеши
2010-04-17 20:55:22 +03:00
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_new_{$sTargetType}"));
return $this->oMapper->UpdateTargetParentByTargetId($sParentId, $sTargetType, $aTargetId);
}
/**
* Меняем target parent по массиву идентификаторов в таблице комментариев online
*
* @param string $sParentId
* @param string $sTargetType
* @param array|string $aTargetId
* @return bool
*/
public function UpdateTargetParentByTargetIdOnline($sParentId, $sTargetType, $aTargetId) {
if(!is_array($aTargetId)) $aTargetId = array($aTargetId);
// чистим зависимые кеши
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_online_update_{$sTargetType}"));
return $this->oMapper->UpdateTargetParentByTargetIdOnline($sParentId, $sTargetType, $aTargetId);
}
2010-04-17 20:55:22 +03:00
/**
* Меняет target parent на новый
*
* @param string $sParentId
* @param string $sTargetType
* @param string $sParentIdNew
* @return bool
*/
public function MoveTargetParent($sParentId, $sTargetType, $sParentIdNew) {
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_new_{$sTargetType}"));
return $this->oMapper->MoveTargetParent($sParentId, $sTargetType, $sParentIdNew);
}
/**
* Меняет target parent на новый в прямом эфире
*
* @param string $sParentId
* @param string $sTargetType
* @param string $sParentIdNew
* @return bool
*/
public function MoveTargetParentOnline($sParentId, $sTargetType, $sParentIdNew) {
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("comment_online_update_{$sTargetType}"));
return $this->oMapper->MoveTargetParentOnline($sParentId, $sTargetType, $sParentIdNew);
}
/**
* Перестраивает дерево комментариев
* Восстанавливает значения left, right и level
*
* @param unknown_type $aTargetId
* @param unknown_type $sTargetType
*/
public function RestoreTree($aTargetId=null,$sTargetType=null) {
// обработать конкретную сущность
if (!is_null($aTargetId) and !is_null($sTargetType)) {
$this->oMapper->RestoreTree(null,0,-1,$aTargetId,$sTargetType);
return ;
}
$aType=array();
// обработать все сущности конкретного типа
if (!is_null($sTargetType)) {
$aType[]=$sTargetType;
} else {
// обработать все сущности всех типов
$aType=$this->oMapper->GetCommentTypes();
}
foreach ($aType as $sTargetType) {
// для каждого типа получаем порциями ID сущностей
$iPage=1;
$iPerPage=50;
while ($aResult=$this->oMapper->GetTargetIdByType($sTargetType,$iPage,$iPerPage)) {
foreach ($aResult as $Row) {
$this->oMapper->RestoreTree(null,0,-1,$Row['target_id'],$sTargetType);
}
$iPage++;
}
}
}
2008-09-21 09:36:57 +03:00
}
?>