mirror of
https://github.com/Oreolek/ifhub.club.git
synced 2024-06-16 23:00:51 +03:00
Перенос категорий блогов на механизм универсальных категорий
This commit is contained in:
parent
7019ed553d
commit
42d48aeb55
|
@ -62,11 +62,6 @@ class ActionAdmin extends Action {
|
|||
$this->AddEvent('recalcfavourite','EventRecalculateFavourite');
|
||||
$this->AddEvent('recalcvote','EventRecalculateVote');
|
||||
$this->AddEvent('recalctopic','EventRecalculateTopic');
|
||||
$this->AddEventPreg('/^blogcategory$/i','/^modal-add$/i','EventBlogCategoryModalAdd');
|
||||
$this->AddEventPreg('/^blogcategory$/i','/^modal-edit$/i','EventBlogCategoryModalEdit');
|
||||
$this->AddEventPreg('/^blogcategory$/i','/^add$/i','EventBlogCategoryAdd');
|
||||
$this->AddEventPreg('/^blogcategory$/i','/^edit$/i','EventBlogCategoryEdit');
|
||||
$this->AddEvent('blogcategory','EventBlogCategory');
|
||||
}
|
||||
|
||||
|
||||
|
@ -82,146 +77,6 @@ class ActionAdmin extends Action {
|
|||
protected function EventIndex() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Список категорий блогов
|
||||
*/
|
||||
protected function EventBlogCategory() {
|
||||
/**
|
||||
* Обработка удаления
|
||||
*/
|
||||
if ($this->GetParam(0)=='delete' and $oCategory=$this->Blog_GetCategoryById($this->GetParam(1))) {
|
||||
$this->Security_ValidateSendForm();
|
||||
/**
|
||||
* Получаем все дочернии категории
|
||||
*/
|
||||
$aCategoriesId=$this->Blog_GetChildrenCategoriesById($oCategory->getId(),true);
|
||||
$aCategoriesId[]=$oCategory->getId();
|
||||
/**
|
||||
* У блогов проставляем category_id = null
|
||||
*/
|
||||
$this->Blog_ReplaceBlogsCategoryByCategoryId($aCategoriesId,null);
|
||||
/**
|
||||
* Удаляем категории
|
||||
*/
|
||||
$this->Blog_DeleteCategoryByArrayId($aCategoriesId);
|
||||
}
|
||||
/**
|
||||
* Обработка изменения сортировки
|
||||
*/
|
||||
if ($this->GetParam(0)=='sort' and $oCategory=$this->Blog_GetCategoryById($this->GetParam(1))) {
|
||||
$this->Security_ValidateSendForm();
|
||||
$sWay=$this->GetParam(2)=='down' ? 'down' : 'up';
|
||||
$iSortOld=$oCategory->getSort();
|
||||
if ($oCategoryPrev=$this->Blog_GetNextCategoryBySort($iSortOld,$oCategory->getPid(),$sWay)) {
|
||||
$iSortNew=$oCategoryPrev->getSort();
|
||||
$oCategoryPrev->setSort($iSortOld);
|
||||
$this->Blog_UpdateCategory($oCategoryPrev);
|
||||
} else {
|
||||
if ($sWay=='down') {
|
||||
$iSortNew=$iSortOld-1;
|
||||
} else {
|
||||
$iSortNew=$iSortOld+1;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Меняем значения сортировки местами
|
||||
*/
|
||||
$oCategory->setSort($iSortNew);
|
||||
$this->Blog_UpdateCategory($oCategory);
|
||||
}
|
||||
$aCategories=$this->Blog_GetCategoriesTree();
|
||||
$this->Viewer_Assign("aCategories",$aCategories);
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает модальное окно создания категории блога
|
||||
*/
|
||||
protected function EventBlogCategoryModalAdd() {
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
$aCategories=$this->Blog_GetCategoriesTree();
|
||||
$oViewer=$this->Viewer_GetLocalViewer();
|
||||
$oViewer->Assign('aCategories',$aCategories);
|
||||
/**
|
||||
* Устанавливаем переменные для ajax ответа
|
||||
*/
|
||||
$this->Viewer_AssignAjax('sText',$oViewer->Fetch("actions/ActionAdmin/blogcategory_form_add.tpl"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает модальное окно редактирования категории бога
|
||||
*/
|
||||
protected function EventBlogCategoryModalEdit() {
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
if (!($oCategory=$this->Blog_GetCategoryById(getRequestStr('id')))) {
|
||||
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
|
||||
return;
|
||||
}
|
||||
$aCategories=$this->Blog_GetCategoriesTree();
|
||||
$oViewer=$this->Viewer_GetLocalViewer();
|
||||
$oViewer->Assign('oCategory',$oCategory);
|
||||
$oViewer->Assign('aCategories',$aCategories);
|
||||
/**
|
||||
* Устанавливаем переменные для ajax ответа
|
||||
*/
|
||||
$this->Viewer_AssignAjax('sText',$oViewer->Fetch("actions/ActionAdmin/blogcategory_form_add.tpl"));
|
||||
}
|
||||
|
||||
protected function EventBlogCategoryAdd() {
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
|
||||
/**
|
||||
* Создаем категорию
|
||||
*/
|
||||
$oCategory=Engine::GetEntity('ModuleBlog_EntityBlogCategory');
|
||||
$oCategory->setTitle(getRequestStr('title'));
|
||||
$oCategory->setUrl(getRequestStr('url'));
|
||||
$oCategory->setSort(getRequestStr('sort'));
|
||||
$oCategory->setPid(getRequestStr('pid'));
|
||||
|
||||
if ($oCategory->_Validate()) {
|
||||
if ($this->Blog_AddCategory($oCategory)) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
$this->Message_AddError($oCategory->_getValidateError(),$this->Lang_Get('error'));
|
||||
}
|
||||
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
|
||||
}
|
||||
|
||||
protected function EventBlogCategoryEdit() {
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
|
||||
if (!($oCategory=$this->Blog_GetCategoryById(getRequestStr('id')))) {
|
||||
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Создаем категорию
|
||||
*/
|
||||
$oCategory->setTitle(getRequestStr('title'));
|
||||
$oCategory->setUrl(getRequestStr('url'));
|
||||
$oCategory->setSort(getRequestStr('sort'));
|
||||
$oCategory->setPid(getRequestStr('pid'));
|
||||
|
||||
if ($oCategory->_Validate()) {
|
||||
if ($this->Blog_UpdateCategory($oCategory)) {
|
||||
/**
|
||||
* Проверяем корректность вложений
|
||||
*/
|
||||
if (count($this->Blog_GetCategoriesTree())<$this->Blog_GetCountCategories()) {
|
||||
$oCategory->setPid(null);
|
||||
$oCategory->setUrlFull($oCategory->getUrl());
|
||||
$this->Blog_UpdateCategory($oCategory);
|
||||
}
|
||||
$this->Blog_RebuildCategoryUrlFull($oCategory);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
$this->Message_AddError($oCategory->_getValidateError(),$this->Lang_Get('error'));
|
||||
}
|
||||
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
|
||||
}
|
||||
/**
|
||||
* Перестроение дерева комментариев, актуально при $config['module']['comment']['use_nested'] = true;
|
||||
*
|
||||
|
|
|
@ -1682,20 +1682,19 @@ class ActionAjax extends Action {
|
|||
* Загружает список блогов конкретной категории
|
||||
*/
|
||||
protected function EventBlogsGetByCategory() {
|
||||
if (!($oCategory=$this->Blog_GetCategoryById(getRequestStr('id')))) {
|
||||
if (!($oCategory=$this->Category_GetCategoryById(getRequestStr('id')))) {
|
||||
return $this->EventErrorDebug();
|
||||
}
|
||||
/**
|
||||
* Получаем все дочерние категории
|
||||
* Список ID блогов по категории
|
||||
*/
|
||||
$aCategoriesId=$this->Blog_GetChildrenCategoriesById($oCategory->getId(),true);
|
||||
$aCategoriesId[]=$oCategory->getId();
|
||||
$aBlogIds=$this->Blog_GetTargetIdsByCategory($oCategory,1,1000,true);
|
||||
/**
|
||||
* Формируем фильтр для получения списка блогов
|
||||
*/
|
||||
$aFilter=array(
|
||||
'exclude_type' => 'personal',
|
||||
'category_id' => $aCategoriesId
|
||||
'id' => $aBlogIds ? $aBlogIds : array(0)
|
||||
);
|
||||
/**
|
||||
* Получаем список блогов(все по фильтру)
|
||||
|
@ -1711,7 +1710,6 @@ class ActionAjax extends Action {
|
|||
$aResult[]=array(
|
||||
'id' => $oBlog->getId(),
|
||||
'title' => htmlspecialchars($oBlog->getTitle()),
|
||||
'category_id' => $oBlog->getCategoryId(),
|
||||
'type' => $oBlog->getType(),
|
||||
'rating' => $oBlog->getRating(),
|
||||
'url' => $oBlog->getUrl(),
|
||||
|
|
|
@ -205,17 +205,20 @@ class ActionBlog extends Action {
|
|||
*/
|
||||
$aCategories=$this->Blog_GetCategoriesTree();
|
||||
$this->Viewer_Assign('aBlogCategories',$aCategories);
|
||||
/**
|
||||
* Создаем объект блога
|
||||
*/
|
||||
$oBlog=Engine::GetEntity('Blog');
|
||||
/**
|
||||
* Запускаем проверку корректности ввода полей при добалении блога.
|
||||
* Дополнительно проверяем, что был отправлен POST запрос.
|
||||
*/
|
||||
if (!$this->checkBlogFields()) {
|
||||
if (!$this->checkBlogFields($oBlog)) {
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Если всё ок то пытаемся создать блог
|
||||
*/
|
||||
$oBlog=Engine::GetEntity('Blog');
|
||||
$oBlog->setOwnerId($this->oUserCurrent->getId());
|
||||
$oBlog->setTitle(strip_tags(getRequestStr('blog_title')));
|
||||
/**
|
||||
|
@ -237,37 +240,26 @@ class ActionBlog extends Action {
|
|||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Устанавливаем категорию для блога
|
||||
*/
|
||||
if (Config::Get('module.blog.category_allow') and ($this->oUserCurrent->isAdministrator() or !Config::Get('module.blog.category_only_admin'))) {
|
||||
if (getRequestStr('blog_category')) {
|
||||
$oBlog->setCategoryId(getRequestStr('blog_category'));
|
||||
} elseif (Config::Get('module.blog.category_allow_empty')) {
|
||||
$oBlog->setCategoryId(null);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Создаём блог
|
||||
*/
|
||||
$this->Hook_Run('blog_add_before', array('oBlog'=>$oBlog));
|
||||
if ($this->Blog_AddBlog($oBlog)) {
|
||||
$this->Hook_Run('blog_add_after', array('oBlog'=>$oBlog));
|
||||
/**
|
||||
* Сохраняем категории
|
||||
*/
|
||||
if (Config::Get('module.blog.category_allow') and ($this->oUserCurrent->isAdministrator() or !Config::Get('module.blog.category_only_admin'))) {
|
||||
$oBlog->category->CallbackAfterSave();
|
||||
}
|
||||
/**
|
||||
* Получаем блог, это для получение полного пути блога, если он в будущем будет зависит от других сущностей(компании, юзер и т.п.)
|
||||
*/
|
||||
$oBlog->Blog_GetBlogById($oBlog->getId());
|
||||
$oBlog=$this->Blog_GetBlogById($oBlog->getId());
|
||||
/**
|
||||
* Фиксируем ID у media файлов
|
||||
*/
|
||||
$this->Media_ReplaceTargetTmpById('blog',$oBlog->getId());
|
||||
/**
|
||||
* Меняем количество блогов в категории
|
||||
*/
|
||||
if ($oBlog->getCategoryId()) {
|
||||
$this->Blog_IncreaseCategoryCountBlogs($oBlog->getCategoryId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляем событие в ленту
|
||||
*/
|
||||
|
@ -359,17 +351,6 @@ class ActionBlog extends Action {
|
|||
if ($this->oUserCurrent->isAdministrator()) {
|
||||
$oBlog->setUrl(getRequestStr('blog_url')); // разрешаем смену URL блога только админу
|
||||
}
|
||||
/**
|
||||
* Устанавливаем категорию для блога
|
||||
*/
|
||||
$iCategoryIdOld=$oBlog->getCategoryId();
|
||||
if (Config::Get('module.blog.category_allow') and ($this->oUserCurrent->isAdministrator() or !Config::Get('module.blog.category_only_admin'))) {
|
||||
if (getRequestStr('blog_category')) {
|
||||
$oBlog->setCategoryId(getRequestStr('blog_category'));
|
||||
} elseif (Config::Get('module.blog.category_allow_empty')) {
|
||||
$oBlog->setCategoryId(null);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Загрузка аватара, делаем ресайзы
|
||||
*/
|
||||
|
@ -392,15 +373,11 @@ class ActionBlog extends Action {
|
|||
$this->Hook_Run('blog_edit_before', array('oBlog'=>$oBlog));
|
||||
if ($this->Blog_UpdateBlog($oBlog)) {
|
||||
$this->Hook_Run('blog_edit_after', array('oBlog'=>$oBlog));
|
||||
|
||||
/**
|
||||
* Меняем количество блогов в категории
|
||||
* Сохраняем категории
|
||||
*/
|
||||
if ($iCategoryIdOld and $iCategoryIdOld!=$oBlog->getCategoryId()) {
|
||||
$this->Blog_DecreaseCategoryCountBlogs($iCategoryIdOld);
|
||||
}
|
||||
if ($oBlog->getCategoryId()) {
|
||||
$this->Blog_IncreaseCategoryCountBlogs($oBlog->getCategoryId());
|
||||
if (Config::Get('module.blog.category_allow') and ($this->oUserCurrent->isAdministrator() or !Config::Get('module.blog.category_only_admin'))) {
|
||||
$oBlog->category->CallbackAfterSave();
|
||||
}
|
||||
|
||||
Router::Location($oBlog->getUrlFull());
|
||||
|
@ -415,7 +392,6 @@ class ActionBlog extends Action {
|
|||
$_REQUEST['blog_title']=$oBlog->getTitle();
|
||||
$_REQUEST['blog_url']=$oBlog->getUrl();
|
||||
$_REQUEST['blog_type']=$oBlog->getType();
|
||||
$_REQUEST['blog_category']=$oBlog->getCategoryId();
|
||||
$_REQUEST['blog_description']=$oBlog->getDescription();
|
||||
$_REQUEST['blog_limit_rating_topic']=$oBlog->getLimitRatingTopic();
|
||||
$_REQUEST['blog_id']=$oBlog->getId();
|
||||
|
@ -580,7 +556,7 @@ class ActionBlog extends Action {
|
|||
/**
|
||||
* Проверяем есть ли URL блога, с заменой всех пробельных символов на "_"
|
||||
*/
|
||||
if (!$oBlog or $this->oUserCurrent->isAdministrator()) {
|
||||
if (!$oBlog or !$oBlog->getId() or $this->oUserCurrent->isAdministrator()) {
|
||||
$blogUrl=preg_replace("/\s+/",'_',getRequestStr('blog_url'));
|
||||
$_REQUEST['blog_url']=$blogUrl;
|
||||
if (!func_check(getRequestStr('blog_url'),'login',2,50)) {
|
||||
|
@ -629,22 +605,12 @@ class ActionBlog extends Action {
|
|||
* Проверяем категорию блога
|
||||
*/
|
||||
if (Config::Get('module.blog.category_allow')) {
|
||||
if ($oCategory=$this->Blog_GetCategoryById(getRequestStr('blog_category'))) {
|
||||
/**
|
||||
* Проверяем есть ли у этой категории дочернии
|
||||
*/
|
||||
if (Config::Get('module.blog.category_only_children') and $this->Blog_GetCategoriesByPid($oCategory->getId())) {
|
||||
$this->Message_AddError($this->Lang_Get('blog.add.fields.category.error_only_children'),$this->Lang_Get('error'));
|
||||
$bOk=false;
|
||||
}
|
||||
} else {
|
||||
$_REQUEST['blog_category']=null;
|
||||
if (!Config::Get('module.blog.category_allow_empty')) {
|
||||
$this->Message_AddError($this->Lang_Get('blog.add.fields.category.error'),$this->Lang_Get('error'));
|
||||
$bOk=false;
|
||||
}
|
||||
if (true!==($mRes=$oBlog->category->ValidateCategoriesCheck(getRequest('category')))) {
|
||||
$this->Message_AddError($mRes,$this->Lang_Get('error'));
|
||||
$bOk=false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выполнение хуков
|
||||
*/
|
||||
|
|
|
@ -86,13 +86,13 @@ class ActionBlogs extends Action {
|
|||
/**
|
||||
* Категории
|
||||
*/
|
||||
if (getRequestStr('category') and $oCategory=$this->Blog_GetCategoryById(getRequestStr('category'))) {
|
||||
if (getRequestStr('category') and $oCategory=$this->Category_GetCategoryById(getRequestStr('category'))) {
|
||||
/**
|
||||
* Получаем все дочерние категории
|
||||
* Получаем ID всех блогов
|
||||
* По сути это костыль, но т.к. блогов обычно не много, то норм
|
||||
*/
|
||||
$aCategoriesId=$this->Blog_GetChildrenCategoriesById($oCategory->getId(),true);
|
||||
$aCategoriesId[]=$oCategory->getId();
|
||||
$aFilter['category_id']=$aCategoriesId;
|
||||
$aBlogIds=$this->Blog_GetTargetIdsByCategory($oCategory,1,1000,true);
|
||||
$aFilter['id']=$aBlogIds ? $aBlogIds : array(0);
|
||||
}
|
||||
/**
|
||||
* Тип
|
||||
|
|
|
@ -31,27 +31,5 @@ class BlockBlogNav extends Block {
|
|||
}
|
||||
$aCategories=$this->Blog_GetCategoriesTree();
|
||||
$this->Viewer_Assign("aNavigatorBlogCategories",$aCategories);
|
||||
/**
|
||||
* Получаем список блогов для первой категории для прогрузки в шаблон
|
||||
*/
|
||||
if ($oCategory=array_shift($aCategories)) {
|
||||
/**
|
||||
* Получаем все дочерние категории
|
||||
*/
|
||||
$aCategoriesId=$this->Blog_GetChildrenCategoriesById($oCategory->getId(),true);
|
||||
$aCategoriesId[]=$oCategory->getId();
|
||||
/**
|
||||
* Формируем фильтр для получения списка блогов
|
||||
*/
|
||||
$aFilter=array(
|
||||
'exclude_type' => 'personal',
|
||||
'category_id' => $aCategoriesId
|
||||
);
|
||||
/**
|
||||
* Получаем список блогов(все по фильтру)
|
||||
*/
|
||||
$aResult=$this->Blog_GetBlogsByFilter($aFilter,array('blog_title'=>'asc'),1,PHP_INT_MAX);
|
||||
$this->Viewer_Assign("aNavigatorBlogs",$aResult['collection']);
|
||||
}
|
||||
}
|
||||
}
|
59
application/classes/blocks/BlockCategoryUpdate.class.php
Normal file
59
application/classes/blocks/BlockCategoryUpdate.class.php
Normal file
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
/*-------------------------------------------------------
|
||||
*
|
||||
* 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
|
||||
*
|
||||
---------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Обработка блока с редактированием категорий объекта
|
||||
*
|
||||
* @package blocks
|
||||
* @since 1.0
|
||||
*/
|
||||
class BlockCategoryUpdate extends Block {
|
||||
/**
|
||||
* Запуск обработки
|
||||
*/
|
||||
public function Exec() {
|
||||
$sEntity = $this->GetParam('entity');
|
||||
$oTarget = $this->GetParam('target');
|
||||
|
||||
if (!$oTarget) {
|
||||
$oTarget=Engine::GetEntity($sEntity);
|
||||
}
|
||||
|
||||
if ($oTarget) {
|
||||
$aBehaviors=$oTarget->GetBehaviors();
|
||||
foreach($aBehaviors as $oBehavior) {
|
||||
$sClassRoot=$this->Plugin_GetRootDelegater('entity',get_class($oBehavior));
|
||||
if ($sClassRoot=='ModuleCategory_BehaviorEntity') {
|
||||
/**
|
||||
* Нужное нам поведение - получаем список текущих категорий
|
||||
*/
|
||||
$this->Viewer_Assign('aCategoriesCurrent',$oBehavior->getCategories());
|
||||
/**
|
||||
* Загружаем параметры
|
||||
*/
|
||||
$aParams=$oBehavior->getParams();
|
||||
$this->Viewer_Assign('aCategoryParams',$aParams);
|
||||
/**
|
||||
* Загружаем список доступных категорий
|
||||
*/
|
||||
$this->Viewer_Assign('aCategories',$this->Category_GetCategoriesTreeByTargetType($aParams['target_type']));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -62,6 +62,18 @@ class ModuleBlog extends Module {
|
|||
* @var ModuleUser_EntityUser|null
|
||||
*/
|
||||
protected $oUserCurrent=null;
|
||||
/**
|
||||
* Список поведений
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $aBehaviors=array(
|
||||
// Категории
|
||||
'category'=> array(
|
||||
'class'=>'ModuleCategory_BehaviorModule',
|
||||
'target_type'=>'blog',
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Инициализация
|
||||
|
@ -841,9 +853,7 @@ class ModuleBlog extends Module {
|
|||
/**
|
||||
* Обновляем категорию блога
|
||||
*/
|
||||
if ($oBlog->getCategoryId()) {
|
||||
$this->DecreaseCategoryCountBlogs($oBlog->getCategoryId());
|
||||
}
|
||||
$oBlog->category->CallbackAfterDelete();
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
|
@ -939,231 +949,4 @@ class ModuleBlog extends Module {
|
|||
public function GetBlogItemsByArrayId($aBlogId) {
|
||||
return $this->GetBlogsByArrayId($aBlogId);
|
||||
}
|
||||
/**
|
||||
* Получает список категорий блогов
|
||||
*
|
||||
* @param int|null|bool $iPid ID родительской категории, если false, то не учитывается в выборке
|
||||
* @return array
|
||||
*/
|
||||
public function GetCategoriesByPid($iPid) {
|
||||
return $this->oMapperBlog->GetCategoriesByPid($iPid);
|
||||
}
|
||||
/**
|
||||
* Получает категорию по полному урлу
|
||||
*
|
||||
* @param string $sUrl УРЛ
|
||||
* @return ModuleBlog_EntityBlogCategory|null
|
||||
*/
|
||||
public function GetCategoryByUrlFull($sUrl) {
|
||||
return $this->oMapperBlog->GetCategoryByUrlFull($sUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает дерево категорий блогов
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function GetCategoriesTree() {
|
||||
$aResult=array();
|
||||
$aCategoriesRow=$this->oMapperBlog->GetCategoriesTree();
|
||||
if (count($aCategoriesRow)) {
|
||||
$aResult=$this->BuildCategoriesRecursive($aCategoriesRow);
|
||||
}
|
||||
return $aResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает дочерние категории
|
||||
*
|
||||
* @param int $iId ID Основной категории
|
||||
* @param bool $bOnlyIds Возвращать сами объекты или только ID
|
||||
* @param array $aCategories Служебный параметр - дочерний список категорий
|
||||
* @param bool $bBegin Служебный параметр - старт рекурсии
|
||||
* @param null $iIdParent Служебный параметр - ID родительской категории
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function GetChildrenCategoriesById($iId,$bOnlyIds=false,$aCategories=array(),$bBegin=true,$iIdParent=null) {
|
||||
static $aResult;
|
||||
if ($bBegin) {
|
||||
$aResult=array();
|
||||
$aCategories=$this->oMapperBlog->GetCategoriesTree();
|
||||
}
|
||||
|
||||
foreach ($aCategories as $aCategory) {
|
||||
$aCategory['children']=array();
|
||||
$aTmp=$aCategory;
|
||||
unset($aTmp['childNodes']);
|
||||
$aResult[$aCategory['id']]=$aTmp;
|
||||
|
||||
if ($iIdParent) {
|
||||
$aResult[$iIdParent]['children'][]=$bOnlyIds ? $aCategory['id'] : Engine::GetEntity('ModuleBlog_EntityBlogCategory',$aTmp);
|
||||
}
|
||||
if (isset($aCategory['childNodes']) and count($aCategory['childNodes'])>0) {
|
||||
$this->GetChildrenCategoriesById($iId,$bOnlyIds,$aCategory['childNodes'],false,$aCategory['id']);
|
||||
if ($iIdParent) {
|
||||
$aResult[$iIdParent]['children']=array_merge($aResult[$iIdParent]['children'],$aResult[$aCategory['id']]['children']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($aResult[$iId])) {
|
||||
return $aResult[$iId]['children'];
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
/**
|
||||
* Строит дерево категорий блогов
|
||||
*
|
||||
* @param array $aCategories
|
||||
* @param bool $bBegin
|
||||
* @param ModuleBlog_EntityBlogCategory|null $oCategoryParent
|
||||
* @return array
|
||||
*/
|
||||
protected function BuildCategoriesRecursive($aCategories,$bBegin=true,$oCategoryParent=null) {
|
||||
static $aResult;
|
||||
static $iLevel;
|
||||
if ($bBegin) {
|
||||
$aResult=array();
|
||||
$iLevel=0;
|
||||
}
|
||||
foreach ($aCategories as $aCategory) {
|
||||
$aTemp=$aCategory;
|
||||
$aTemp['level']=$iLevel;
|
||||
unset($aTemp['childNodes']);
|
||||
$oCategory=Engine::GetEntity('ModuleBlog_EntityBlogCategory',$aTemp);
|
||||
|
||||
$aResult[]=$oCategory;
|
||||
if (isset($aCategory['childNodes']) and count($aCategory['childNodes'])>0) {
|
||||
$iLevel++;
|
||||
$this->BuildCategoriesRecursive($aCategory['childNodes'],false,$oCategory);
|
||||
}
|
||||
if ($oCategoryParent) {
|
||||
$oCategoryParent->setCountBlogs($oCategory->getCountBlogs()+$oCategoryParent->getCountBlogs());
|
||||
}
|
||||
}
|
||||
$iLevel--;
|
||||
|
||||
return $aResult;
|
||||
}
|
||||
/**
|
||||
* Получает категорию по ID
|
||||
*
|
||||
* @param int $iId УРЛ
|
||||
* @return ModuleBlog_EntityBlogCategory|null
|
||||
*/
|
||||
public function GetCategoryById($iId) {
|
||||
return $this->oMapperBlog->GetCategoryById($iId);
|
||||
}
|
||||
/**
|
||||
* Получает следующую категорию по сортировке
|
||||
*
|
||||
* @param $iSort
|
||||
* @param $sPid
|
||||
* @param $sWay
|
||||
*
|
||||
* @return ModuleBlog_EntityBlogCategory|null
|
||||
*/
|
||||
public function GetNextCategoryBySort($iSort,$sPid,$sWay='up') {
|
||||
return $this->oMapperBlog->GetNextCategoryBySort($iSort,$sPid,$sWay);
|
||||
}
|
||||
/**
|
||||
* Обновление категории
|
||||
*
|
||||
* @param ModuleBlog_EntityBlogCategory $oObject Объект категории
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function UpdateCategory($oObject) {
|
||||
return $this->oMapperBlog->UpdateCategory($oObject);
|
||||
}
|
||||
/**
|
||||
* Добавление категории
|
||||
*
|
||||
* @param ModuleBlog_EntityBlogCategory $oObject
|
||||
*
|
||||
* @return int|bool
|
||||
*/
|
||||
public function AddCategory($oObject) {
|
||||
return $this->oMapperBlog->AddCategory($oObject);
|
||||
}
|
||||
/**
|
||||
* Возвращает максимальное значение сортировки для родительской категории
|
||||
*
|
||||
* @param int|null $sPid
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function GetCategoryMaxSortByPid($sPid) {
|
||||
return $this->oMapperBlog->GetCategoryMaxSortByPid($sPid);
|
||||
}
|
||||
public function RebuildCategoryUrlFull($oCategoryStart,$bStart=true) {
|
||||
static $aRebuildIds;
|
||||
if ($bStart) {
|
||||
$aRebuildIds=array();
|
||||
}
|
||||
$aCategories=$this->GetCategoriesByPid($oCategoryStart->getId());
|
||||
foreach ($aCategories as $oCategory) {
|
||||
if ($oCategory->getId()==$oCategoryStart->getId()) {
|
||||
continue;
|
||||
}
|
||||
if (in_array($oCategory->getId(),$aRebuildIds)) {
|
||||
continue;
|
||||
}
|
||||
$aRebuildIds[]=$oCategory->getId();
|
||||
$oCategory->setUrlFull($oCategoryStart->getUrlFull().'/'.$oCategory->getUrl());
|
||||
$this->UpdateCategory($oCategory);
|
||||
$this->RebuildCategoryUrlFull($oCategory,false);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Возвращает количество категорий
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountCategories() {
|
||||
return $this->oMapperBlog->GetCountCategories();
|
||||
}
|
||||
/**
|
||||
* Увеличивает количество блогов у категории
|
||||
*
|
||||
* @param int $sId ID категории
|
||||
* @return bool
|
||||
*/
|
||||
public function IncreaseCategoryCountBlogs($sId) {
|
||||
return $this->oMapperBlog->IncreaseCategoryCountBlogs($sId);
|
||||
}
|
||||
/**
|
||||
* Уменьшает количество блогов у категории
|
||||
*
|
||||
* @param int $sId ID категории
|
||||
* @return bool
|
||||
*/
|
||||
public function DecreaseCategoryCountBlogs($sId) {
|
||||
return $this->oMapperBlog->DecreaseCategoryCountBlogs($sId);
|
||||
}
|
||||
/**
|
||||
* Удаляет категории по списку их ID
|
||||
*
|
||||
* @param array $aArrayId Список ID категорий
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function DeleteCategoryByArrayId($aArrayId) {
|
||||
return $this->oMapperBlog->DeleteCategoryByArrayId($aArrayId);
|
||||
}
|
||||
/**
|
||||
* Заменяет категорию на новую у блогов
|
||||
*
|
||||
* @param int| null $iIdOld Старая категори
|
||||
* @param int| null $iIdNew Новая категория
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function ReplaceBlogsCategoryByCategoryId($iIdOld,$iIdNew) {
|
||||
$res=$this->oMapperBlog->ReplaceBlogsCategoryByCategoryId($iIdOld,$iIdNew);
|
||||
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array('blog_update'));
|
||||
return $res;
|
||||
}
|
||||
}
|
|
@ -22,6 +22,33 @@
|
|||
* @since 1.0
|
||||
*/
|
||||
class ModuleBlog_EntityBlog extends Entity {
|
||||
|
||||
protected $sPrimaryKey = 'blog_id';
|
||||
/**
|
||||
* Список поведений
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $aBehaviors=array(
|
||||
// Категории
|
||||
'category'=>array(
|
||||
'class'=>'ModuleCategory_BehaviorEntity',
|
||||
'target_type'=>'blog',
|
||||
'form_field'=>'category',
|
||||
'multiple'=>false,
|
||||
'validate_require'=>false,
|
||||
'validate_only_without_children'=>true,
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Инициализация
|
||||
*/
|
||||
public function Init() {
|
||||
parent::Init();
|
||||
$this->aBehaviors['category']['validate_require']=!Config::Get('module.blog.category_allow_empty');
|
||||
$this->aBehaviors['category']['validate_only_without_children']=Config::Get('module.blog.category_only_without_children');
|
||||
}
|
||||
/**
|
||||
* Возвращает ID блога
|
||||
*
|
||||
|
@ -38,14 +65,6 @@ class ModuleBlog_EntityBlog extends Entity {
|
|||
public function getOwnerId() {
|
||||
return $this->_getDataOne('user_owner_id');
|
||||
}
|
||||
/**
|
||||
* Возвращает ID категории
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getCategoryId() {
|
||||
return $this->_getDataOne('category_id');
|
||||
}
|
||||
/**
|
||||
* Возвращает название блога
|
||||
*
|
||||
|
@ -237,14 +256,6 @@ class ModuleBlog_EntityBlog extends Entity {
|
|||
public function setOwnerId($data) {
|
||||
$this->_aData['user_owner_id']=$data;
|
||||
}
|
||||
/**
|
||||
* Устанавливает ID категории блога
|
||||
*
|
||||
* @param int $data
|
||||
*/
|
||||
public function setCategoryId($data) {
|
||||
$this->_aData['category_id']=$data;
|
||||
}
|
||||
/**
|
||||
* Устанавливает заголовок блога
|
||||
*
|
||||
|
|
|
@ -1,81 +0,0 @@
|
|||
<?php
|
||||
/*-------------------------------------------------------
|
||||
*
|
||||
* 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
|
||||
*
|
||||
---------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Сущность категории блога
|
||||
*
|
||||
* @package modules.blog
|
||||
* @since 1.1
|
||||
*/
|
||||
class ModuleBlog_EntityBlogCategory extends Entity {
|
||||
/**
|
||||
* Определяем правила валидации
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $aValidateRules=array(
|
||||
array('url','regexp','pattern'=>'/^[\w\-_]+$/i','allowEmpty'=>false),
|
||||
array('title','string','max'=>100,'min'=>1,'allowEmpty'=>false),
|
||||
array('sort','number','integerOnly'=>true),
|
||||
array('pid','parent_category'),
|
||||
array('sort','sort_check'),
|
||||
);
|
||||
/**
|
||||
* Проверка родительской категории
|
||||
*
|
||||
* @param string $sValue Валидируемое значение
|
||||
* @param array $aParams Параметры
|
||||
* @return bool
|
||||
*/
|
||||
public function ValidateParentCategory($sValue,$aParams) {
|
||||
if ($this->getPid()) {
|
||||
if ($oCategory=$this->Blog_GetCategoryById($this->getPid())) {
|
||||
if ($oCategory->getId()==$this->getId()) {
|
||||
return 'Попытка вложить категорию в саму себя';
|
||||
}
|
||||
$this->setUrlFull($oCategory->getUrlFull().'/'.$this->getUrl());
|
||||
} else {
|
||||
return 'Неверная категория';
|
||||
}
|
||||
} else {
|
||||
$this->setPid(null);
|
||||
$this->setUrlFull($this->getUrl());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Установка дефолтной сортировки
|
||||
*
|
||||
* @param string $sValue Валидируемое значение
|
||||
* @param array $aParams Параметры
|
||||
* @return bool
|
||||
*/
|
||||
public function ValidateSortCheck($sValue,$aParams) {
|
||||
if (!$this->getSort()) {
|
||||
$this->setSort($this->Blog_GetCategoryMaxSortByPid($this->getPid())+1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Возвращает полный URL категории
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getUrlWeb() {
|
||||
return Router::GetPath('blogs').$this->getUrlFull().'/';
|
||||
}
|
||||
}
|
|
@ -33,16 +33,15 @@ class ModuleBlog_MapperBlog extends Mapper {
|
|||
(user_owner_id,
|
||||
blog_title,
|
||||
blog_description,
|
||||
blog_type,
|
||||
category_id,
|
||||
blog_type,
|
||||
blog_date_add,
|
||||
blog_limit_rating_topic,
|
||||
blog_url,
|
||||
blog_avatar
|
||||
)
|
||||
VALUES(?d, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES(?d, ?, ?, ?, ?, ?, ?, ?)
|
||||
";
|
||||
if ($iId=$this->oDb->query($sql,$oBlog->getOwnerId(),$oBlog->getTitle(),$oBlog->getDescription(),$oBlog->getType(),$oBlog->getCategoryId(),$oBlog->getDateAdd(),$oBlog->getLimitRatingTopic(),$oBlog->getUrl(),$oBlog->getAvatar())) {
|
||||
if ($iId=$this->oDb->query($sql,$oBlog->getOwnerId(),$oBlog->getTitle(),$oBlog->getDescription(),$oBlog->getType(),$oBlog->getDateAdd(),$oBlog->getLimitRatingTopic(),$oBlog->getUrl(),$oBlog->getAvatar())) {
|
||||
return $iId;
|
||||
}
|
||||
return false;
|
||||
|
@ -59,7 +58,6 @@ class ModuleBlog_MapperBlog extends Mapper {
|
|||
blog_title= ?,
|
||||
blog_description= ?,
|
||||
blog_type= ?,
|
||||
category_id= ?,
|
||||
blog_date_edit= ?,
|
||||
blog_rating= ?f,
|
||||
blog_count_vote = ?d,
|
||||
|
@ -71,7 +69,7 @@ class ModuleBlog_MapperBlog extends Mapper {
|
|||
WHERE
|
||||
blog_id = ?d
|
||||
";
|
||||
$res=$this->oDb->query($sql,$oBlog->getTitle(),$oBlog->getDescription(),$oBlog->getType(),$oBlog->getCategoryId(),$oBlog->getDateEdit(),$oBlog->getRating(),$oBlog->getCountVote(),$oBlog->getCountUser(),$oBlog->getCountTopic(),$oBlog->getLimitRatingTopic(),$oBlog->getUrl(),$oBlog->getAvatar(),$oBlog->getId());
|
||||
$res=$this->oDb->query($sql,$oBlog->getTitle(),$oBlog->getDescription(),$oBlog->getType(),$oBlog->getDateEdit(),$oBlog->getRating(),$oBlog->getCountVote(),$oBlog->getCountUser(),$oBlog->getCountTopic(),$oBlog->getLimitRatingTopic(),$oBlog->getUrl(),$oBlog->getAvatar(),$oBlog->getId());
|
||||
return $this->IsSuccessful($res);
|
||||
}
|
||||
/**
|
||||
|
@ -116,234 +114,6 @@ class ModuleBlog_MapperBlog extends Mapper {
|
|||
}
|
||||
return $aBlogs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает список категорий блогов
|
||||
*
|
||||
* @param int|null|bool $iPid ID родительской категории, если false, то не учитывается в выборке
|
||||
* @return array
|
||||
*/
|
||||
public function GetCategoriesByPid($iPid) {
|
||||
$sql = "SELECT
|
||||
*
|
||||
FROM
|
||||
".Config::Get('db.table.blog_category')."
|
||||
WHERE
|
||||
1 = 1
|
||||
{ AND pid = ?d }
|
||||
{ AND pid IS NULL and 1=?d }
|
||||
ORDER by title asc
|
||||
";
|
||||
$aReturn=array();
|
||||
if ($aRows=$this->oDb->select($sql,$iPid ? $iPid : DBSIMPLE_SKIP,is_null($iPid) ? 1 : DBSIMPLE_SKIP)) {
|
||||
foreach ($aRows as $aRow) {
|
||||
$aReturn[]=Engine::GetEntity('ModuleBlog_EntityBlogCategory',$aRow);
|
||||
}
|
||||
}
|
||||
return $aReturn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает список категорий с учетом вложенности
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function GetCategoriesTree() {
|
||||
$sql = "SELECT
|
||||
*,
|
||||
id as ARRAY_KEY,
|
||||
pid as PARENT_KEY
|
||||
FROM
|
||||
".Config::Get('db.table.blog_category')."
|
||||
ORDER by sort desc;
|
||||
";
|
||||
if ($aRows=$this->oDb->select($sql)) {
|
||||
return $aRows;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Получает категорию по полному урлу
|
||||
*
|
||||
* @param string $sUrl УРЛ
|
||||
* @return ModuleBlog_EntityBlogCategory|null
|
||||
*/
|
||||
public function GetCategoryByUrlFull($sUrl) {
|
||||
$sql = "SELECT * FROM ".Config::Get('db.table.blog_category')." WHERE url_full = ? ";
|
||||
if ($aRow=$this->oDb->selectRow($sql,$sUrl)) {
|
||||
return Engine::GetEntity('ModuleBlog_EntityBlogCategory',$aRow);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Получает категорию по ID
|
||||
*
|
||||
* @param int $iId УРЛ
|
||||
* @return ModuleBlog_EntityBlogCategory|null
|
||||
*/
|
||||
public function GetCategoryById($iId) {
|
||||
$sql = "SELECT * FROM ".Config::Get('db.table.blog_category')." WHERE id = ?d ";
|
||||
if ($aRow=$this->oDb->selectRow($sql,$iId)) {
|
||||
return Engine::GetEntity('ModuleBlog_EntityBlogCategory',$aRow);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает следующую категорию по сортировке
|
||||
*
|
||||
* @param $iSort
|
||||
* @param $sPid
|
||||
* @param $sWay
|
||||
*
|
||||
* @return ModuleBlog_EntityBlogCategory|null
|
||||
*/
|
||||
public function GetNextCategoryBySort($iSort,$sPid,$sWay) {
|
||||
if ($sWay=='up') {
|
||||
$sWay='>';
|
||||
$sOrder='asc';
|
||||
} else {
|
||||
$sWay='<';
|
||||
$sOrder='desc';
|
||||
}
|
||||
$sPidNULL='';
|
||||
if (is_null($sPid)) {
|
||||
$sPidNULL='pid IS NULL and';
|
||||
}
|
||||
$sql = "SELECT * FROM ".Config::Get('db.table.blog_category')." WHERE { pid = ? and } {$sPidNULL} sort {$sWay} ? order by sort {$sOrder} limit 0,1";
|
||||
if ($aRow=$this->oDb->selectRow($sql,is_null($sPid) ? DBSIMPLE_SKIP : $sPid, $iSort)) {
|
||||
return Engine::GetEntity('ModuleBlog_EntityBlogCategory',$aRow);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает максимальное значение сортировки для родительской категории
|
||||
*
|
||||
* @param int|null $sPid
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function GetCategoryMaxSortByPid($sPid) {
|
||||
$sql = "SELECT max(sort) as max_sort FROM ".Config::Get('db.table.blog_category')." WHERE 1=1 { and pid = ? } { and pid IS NULL and 1=?d } ";
|
||||
if ($aRow=$this->oDb->selectRow($sql,is_null($sPid) ? DBSIMPLE_SKIP : $sPid,!is_null($sPid) ? DBSIMPLE_SKIP : 1)) {
|
||||
return $aRow['max_sort'];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
/**
|
||||
* Обновление категории
|
||||
*
|
||||
* @param ModuleBlog_EntityBlogCategory $oObject Объект категории
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function UpdateCategory($oObject) {
|
||||
$sql = "UPDATE ".Config::Get('db.table.blog_category')." SET ?a WHERE id = ?d ";
|
||||
$res=$this->oDb->query($sql,$oObject->_getData(array('pid','title','url','url_full','sort','count_blogs')),$oObject->getId());
|
||||
return $this->IsSuccessful($res);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавление категории
|
||||
*
|
||||
* @param ModuleBlog_EntityBlogCategory $oObject
|
||||
*
|
||||
* @return int|bool
|
||||
*/
|
||||
public function AddCategory($oObject) {
|
||||
$sql = "INSERT INTO ".Config::Get('db.table.blog_category')." SET ?a ";
|
||||
if ($iId=$this->oDb->query($sql,$oObject->_getData())) {
|
||||
return $iId;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает количество категорий
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountCategories() {
|
||||
$sql = "SELECT count(*) as count FROM ".Config::Get('db.table.blog_category')." ";
|
||||
if ($aRow=$this->oDb->selectRow($sql)) {
|
||||
return $aRow['count'];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
/**
|
||||
* Увеличивает количество блогов у категории
|
||||
*
|
||||
* @param int $sId ID категории
|
||||
* @return bool
|
||||
*/
|
||||
public function IncreaseCategoryCountBlogs($sId) {
|
||||
$sql = "UPDATE ".Config::Get('db.table.blog_category')."
|
||||
SET
|
||||
count_blogs=count_blogs+1
|
||||
WHERE
|
||||
id = ?
|
||||
";
|
||||
$res=$this->oDb->query($sql,$sId);
|
||||
return $this->IsSuccessful($res);
|
||||
}
|
||||
/**
|
||||
* Уменьшает количество блогов у категории
|
||||
*
|
||||
* @param int $sId ID категории
|
||||
* @return bool
|
||||
*/
|
||||
public function DecreaseCategoryCountBlogs($sId) {
|
||||
$sql = "UPDATE ".Config::Get('db.table.blog_category')."
|
||||
SET
|
||||
count_blogs=count_blogs-1
|
||||
WHERE
|
||||
id = ?
|
||||
";
|
||||
$res=$this->oDb->query($sql,$sId);
|
||||
return $this->IsSuccessful($res);
|
||||
}
|
||||
/**
|
||||
* Удаляет категории по списку их ID
|
||||
*
|
||||
* @param array $aArrayId Список ID категорий
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function DeleteCategoryByArrayId($aArrayId) {
|
||||
if (!is_array($aArrayId)) {
|
||||
$aArrayId=array($aArrayId);
|
||||
}
|
||||
$sql = "DELETE FROM ".Config::Get('db.table.blog_category')."
|
||||
WHERE
|
||||
id IN (?a)
|
||||
";
|
||||
$res=$this->oDb->query($sql,$aArrayId);
|
||||
return $this->IsSuccessful($res);
|
||||
}
|
||||
/**
|
||||
* Заменяет категорию на новую у блогов
|
||||
*
|
||||
* @param int|array|null $iIdOld Старая категори
|
||||
* @param int|null $iIdNew Новая категория
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function ReplaceBlogsCategoryByCategoryId($iIdOld,$iIdNew) {
|
||||
if (!is_null($iIdOld) and !is_array($iIdOld)) {
|
||||
$iIdOld=array($iIdOld);
|
||||
}
|
||||
$sql = "UPDATE ".Config::Get('db.table.blog')."
|
||||
SET
|
||||
category_id = ?
|
||||
WHERE
|
||||
1 = 1
|
||||
{ and category_id IN ( ?a ) }
|
||||
{ and category_id IS NULL and 1 = ?d }
|
||||
";
|
||||
$res=$this->oDb->query($sql,$iIdNew,is_null($iIdOld) ? DBSIMPLE_SKIP : $iIdOld,!is_null($iIdOld) ? DBSIMPLE_SKIP : 1);
|
||||
return $this->IsSuccessful($res);
|
||||
}
|
||||
/**
|
||||
* Добавляет свзяь пользователя с блогом в БД
|
||||
*
|
||||
|
@ -746,8 +516,8 @@ class ModuleBlog_MapperBlog extends Mapper {
|
|||
if (isset($aFilter['type']) and !is_array($aFilter['type'])) {
|
||||
$aFilter['type']=array($aFilter['type']);
|
||||
}
|
||||
if (isset($aFilter['category_id']) and !is_array($aFilter['category_id'])) {
|
||||
$aFilter['category_id']=array($aFilter['category_id']);
|
||||
if (isset($aFilter['id']) and !is_array($aFilter['id'])) {
|
||||
$aFilter['id']=array($aFilter['id']);
|
||||
}
|
||||
|
||||
$sql = "SELECT
|
||||
|
@ -756,27 +526,23 @@ class ModuleBlog_MapperBlog extends Mapper {
|
|||
".Config::Get('db.table.blog')."
|
||||
WHERE
|
||||
1 = 1
|
||||
{ AND blog_id = ?d }
|
||||
{ AND blog_id IN (?a) }
|
||||
{ AND user_owner_id = ?d }
|
||||
{ AND blog_type IN (?a) }
|
||||
{ AND blog_type not IN (?a) }
|
||||
{ AND blog_url = ? }
|
||||
{ AND blog_title LIKE ? }
|
||||
{ AND category_id IN (?a) }
|
||||
{ AND category_id IS NULL and 1=?d}
|
||||
ORDER by {$sOrder}
|
||||
LIMIT ?d, ?d ;
|
||||
";
|
||||
$aResult=array();
|
||||
if ($aRows=$this->oDb->selectPage($iCount,$sql,
|
||||
isset($aFilter['id']) ? $aFilter['id'] : DBSIMPLE_SKIP,
|
||||
(isset($aFilter['id']) and count($aFilter['id'])) ? $aFilter['id'] : DBSIMPLE_SKIP,
|
||||
isset($aFilter['user_owner_id']) ? $aFilter['user_owner_id'] : DBSIMPLE_SKIP,
|
||||
(isset($aFilter['type']) and count($aFilter['type']) ) ? $aFilter['type'] : DBSIMPLE_SKIP,
|
||||
(isset($aFilter['exclude_type']) and count($aFilter['exclude_type']) ) ? $aFilter['exclude_type'] : DBSIMPLE_SKIP,
|
||||
isset($aFilter['url']) ? $aFilter['url'] : DBSIMPLE_SKIP,
|
||||
isset($aFilter['title']) ? $aFilter['title'] : DBSIMPLE_SKIP,
|
||||
(isset($aFilter['category_id']) and count($aFilter['category_id'])) ? $aFilter['category_id'] : DBSIMPLE_SKIP,
|
||||
(array_key_exists('category_id',$aFilter) and is_null($aFilter['category_id'])) ? 1 : DBSIMPLE_SKIP,
|
||||
($iCurrPage-1)*$iPerPage, $iPerPage
|
||||
)) {
|
||||
foreach ($aRows as $aRow) {
|
||||
|
|
|
@ -418,5 +418,41 @@ class ModuleCategory extends ModuleORM {
|
|||
$this->RebuildCategoryUrlFull($oCategory,false);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Возвращает список ID таргетов по списку категорий
|
||||
*
|
||||
* @param $aCategoryId
|
||||
* @param $sTargetType
|
||||
* @param $iPage
|
||||
* @param $iPerPage
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function GetTargetIdsByCategoriesId($aCategoryId,$sTargetType,$iPage,$iPerPage) {
|
||||
if (!is_array($aCategoryId)) {
|
||||
$aCategoryId=array($aCategoryId);
|
||||
}
|
||||
if (!count($aCategoryId)) {
|
||||
return array();
|
||||
}
|
||||
$aTargetItems=$this->GetTargetItemsByFilter(array('category_id in'=>$aCategoryId,'target_type'=>$sTargetType,'#page'=>array($iPage,$iPerPage),'#index-from'=>'target_id'));
|
||||
return array_keys($aTargetItems['collection']);
|
||||
}
|
||||
/**
|
||||
* Возвращает список ID таргетов по категории
|
||||
*
|
||||
* @param $oCategory
|
||||
* @param $sTargetType
|
||||
* @param $iPage
|
||||
* @param $iPerPage
|
||||
* @param bool $bIncludeChild
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function GetTargetIdsByCategory($oCategory,$sTargetType,$iPage,$iPerPage,$bIncludeChild=false) {
|
||||
$aCategoryId=$this->GetCategoriesIdByCategory($oCategory,$bIncludeChild);
|
||||
|
||||
return $this->GetTargetIdsByCategoriesId($aCategoryId,$sTargetType,$iPage,$iPerPage);
|
||||
}
|
||||
|
||||
}
|
|
@ -31,12 +31,13 @@ class ModuleCategory_BehaviorEntity extends Behavior {
|
|||
protected $aParams=array(
|
||||
'target_type'=>'',
|
||||
'form_field'=>'categories',
|
||||
'form_fill_current_from_request'=>true,
|
||||
'multiple'=>false,
|
||||
|
||||
'validate_enable'=>true,
|
||||
'validate_field'=>null,
|
||||
'validate_require'=>false,
|
||||
'validate_from_request'=>true,
|
||||
'validate_from_request'=>false,
|
||||
'validate_min'=>1,
|
||||
'validate_max'=>5,
|
||||
'validate_only_without_children'=>false,
|
||||
|
|
|
@ -67,4 +67,25 @@ class ModuleCategory_BehaviorModule extends Behavior {
|
|||
$aFilter=$this->Category_RewriteFilter($aParams['aFilter'],$aParams['sEntityFull'],$this->getParam('target_type'));
|
||||
$aParams['aFilter']=$aFilter;
|
||||
}
|
||||
/**
|
||||
* Возвращает дерево категорий
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function GetCategoriesTree() {
|
||||
return $this->Category_GetCategoriesTreeByTargetType($this->getParam('target_type'));
|
||||
}
|
||||
/**
|
||||
* Возвращает список ID объектов (элементов), которые принадлежат категории
|
||||
*
|
||||
* @param $oCategory
|
||||
* @param $iPage
|
||||
* @param $iPerPage
|
||||
* @param bool $bIncludeChild
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function GetTargetIdsByCategory($oCategory,$iPage,$iPerPage,$bIncludeChild=false) {
|
||||
return $this->Category_GetTargetIdsByCategory($oCategory,$this->getParam('target_type'),$iPage,$iPerPage,$bIncludeChild);
|
||||
}
|
||||
}
|
|
@ -116,7 +116,7 @@ $config['module']['blog']['encrypt'] = 'livestreet'; // Ключ XXTEA
|
|||
$config['module']['blog']['avatar_size'] = array('500crop','100crop','64crop','48crop','24crop'); // Список размеров аватаров у блога
|
||||
$config['module']['blog']['category_allow'] = true; // Разрешить использование категорий бля блогов
|
||||
$config['module']['blog']['category_only_admin'] = true; // Задавать и менять категории для блога может только админ
|
||||
$config['module']['blog']['category_only_children'] = true; // Для блога можно выбрать только конечную категорию, у которой нет других вложенных
|
||||
$config['module']['blog']['category_only_without_children'] = true; // Для блога можно выбрать только конечную категорию, у которой нет других вложенных
|
||||
$config['module']['blog']['category_allow_empty'] = true; // Разрешить блоги без категории
|
||||
// Модуль Topic
|
||||
$config['module']['topic']['new_time'] = 60*60*24*1; // Время в секундах в течении которого топик считается новым
|
||||
|
|
|
@ -37,7 +37,7 @@ ls.blog = (function ($) {
|
|||
nav: {
|
||||
categories: '.js-blog-nav-categories',
|
||||
blogs: '.js-blog-nav-blogs',
|
||||
submit: '.js-blog-nav-submit',
|
||||
submit: '.js-blog-nav-submit'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -56,7 +56,7 @@ ls.blog = (function ($) {
|
|||
nav: {
|
||||
categories: $(this.options.selectors.nav.categories),
|
||||
blogs: $(this.options.selectors.nav.blogs),
|
||||
submit: $(this.options.selectors.nav.submit),
|
||||
submit: $(this.options.selectors.nav.submit)
|
||||
},
|
||||
info: $(this.options.selectors.info),
|
||||
toggle_join: $(this.options.selectors.toggle_join),
|
||||
|
|
|
@ -1,44 +0,0 @@
|
|||
{extends file='layouts/layout.base.tpl'}
|
||||
|
||||
{block name='layout_options'}
|
||||
{$bNoSidebar = true}
|
||||
{/block}
|
||||
|
||||
{block name='layout_page_title'}<a href="{router page='admin'}">{$aLang.admin_header}</a> <span>»</span> {$aLang.admin_list_blogcategory}{/block}
|
||||
|
||||
{block name='layout_content'}
|
||||
<button class="button button-primary" data-type="modal-toggle" data-modal-url="{router page='admin'}blogcategory/modal-add/">{$aLang.admin_blogcategory_add}</button>
|
||||
<br />
|
||||
<br />
|
||||
|
||||
<table cellspacing="0" class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th width="180px">{$aLang.admin_blogcategory_items_title}</th>
|
||||
<th align="center" >{$aLang.admin_blogcategory_items_url}</th>
|
||||
<th align="center" width="80px">{$aLang.admin_blogcategory_items_action}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{foreach $aCategories as $oCategory}
|
||||
<tr>
|
||||
<td>
|
||||
<i class="icon-file" style="margin-left: {$oCategory->getLevel()*20}px;"></i>
|
||||
<a href="{$oCategory->getUrlWeb()}" border="0">{$oCategory->getTitle()|escape:'html'}</a>
|
||||
</td>
|
||||
<td>
|
||||
/{$oCategory->getUrlFull()}/
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="#" data-type="modal-toggle" data-modal-url="{router page='admin'}blogcategory/modal-edit/" data-param-id="{$oCategory->getId()}" class="icon-edit"></a>
|
||||
<a href="{router page='admin'}blogcategory/delete/{$oCategory->getId()}/?security_ls_key={$LIVESTREET_SECURITY_KEY}" onclick="return confirm('«{$oCategory->getTitle()|escape:'html'}»: {$aLang.admin_blogcategory_items_delete_confirm}');" class="icon-remove"></a>
|
||||
|
||||
<a href="{router page='admin'}blogcategory/sort/{$oCategory->getId()}/?security_ls_key={$LIVESTREET_SECURITY_KEY}" class="icon-arrow-up"></a>
|
||||
<a href="{router page='admin'}blogcategory/sort/{$oCategory->getId()}/down/?security_ls_key={$LIVESTREET_SECURITY_KEY}" class="icon-arrow-down"></a>
|
||||
</td>
|
||||
</tr>
|
||||
{/foreach}
|
||||
</tbody>
|
||||
</table>
|
||||
{/block}
|
|
@ -1,44 +0,0 @@
|
|||
{extends 'components/modal/modal.tpl'}
|
||||
|
||||
|
||||
{block name='modal_id'}modal-category-add{/block}
|
||||
{block name='modal_class'}js-modal-default{/block}
|
||||
{block name='modal_title'}
|
||||
{if $oCategory}
|
||||
{$aLang.admin_blogcategory_form_edit}
|
||||
{else}
|
||||
{$aLang.admin_blogcategory_form_add}
|
||||
{/if}
|
||||
{/block}
|
||||
|
||||
{block name='modal_content'}
|
||||
<form action="" method="post" id="form-category-blog-add" onsubmit="ls.admin.blogCategories.{if $oCategory}showFormEdit{else}showFormAdd{/if}( $(this) ); return false;">
|
||||
<p><label for="pid">{$aLang.admin_blogcategory_form_field_parent}</label>
|
||||
<select name="pid" id="pid" class="width-full">
|
||||
<option value="0"></option>
|
||||
{foreach $aCategories as $oCategoryItem}
|
||||
<option {if $oCategory and $oCategory->getPid()==$oCategoryItem->getId()}selected="selected"{/if} style="margin-left: {$oCategoryItem->getLevel()*20}px;" value="{$oCategoryItem->getId()}">{$oCategoryItem->getTitle()|escape:'html'}</option>
|
||||
{/foreach}
|
||||
</select></p>
|
||||
|
||||
<p><label for="title">{$aLang.admin_blogcategory_form_field_title}</label>
|
||||
<input type="text" name="title" id="title" class="width-full" value="{if $oCategory}{$oCategory->getTitle()}{/if}"></p>
|
||||
|
||||
<p><label for="url">{$aLang.admin_blogcategory_form_field_url}</label>
|
||||
<input type="text" name="url" id="url" class="width-full" value="{if $oCategory}{$oCategory->getUrl()}{/if}"></p>
|
||||
|
||||
<label for="sort">{$aLang.admin_blogcategory_form_field_sort}</label>
|
||||
<input type="text" name="sort" id="sort" class="width-full" value="{if $oCategory}{$oCategory->getSort()}{/if}">
|
||||
|
||||
|
||||
{if $oCategory}
|
||||
<input type="hidden" name="id" value="{$oCategory->getId()}">
|
||||
{/if}
|
||||
</form>
|
||||
{/block}
|
||||
|
||||
{block name='modal_footer_begin'}
|
||||
<button type="submit" name="submit" class="button button-primary" onclick="jQuery('#form-category-blog-add').submit()">
|
||||
{if $oCategory}{$aLang.admin_blogcategory_form_edit_submit}{else}{$aLang.admin_blogcategory_form_add_submit}{/if}
|
||||
</button>
|
||||
{/block}
|
|
@ -10,7 +10,6 @@
|
|||
<ul>
|
||||
<li><a href="{router page="admin"}plugins/">{$aLang.admin_list_plugins}</a></li>
|
||||
<li><a href="{router page="admin"}userfields/">{$aLang.admin_list_userfields}</a></li>
|
||||
<li><a href="{router page="admin"}blogcategory/">{$aLang.admin_list_blogcategory}</a></li>
|
||||
<li><a href="{router page="admin"}restorecomment/?security_ls_key={$LIVESTREET_SECURITY_KEY}">{$aLang.admin_list_restorecomment}</a></li>
|
||||
<li><a href="{router page="admin"}recalcfavourite/?security_ls_key={$LIVESTREET_SECURITY_KEY}">{$aLang.admin_list_recalcfavourite}</a></li>
|
||||
<li><a href="{router page="admin"}recalcvote/?security_ls_key={$LIVESTREET_SECURITY_KEY}">{$aLang.admin_list_recalcvote}</a></li>
|
||||
|
|
|
@ -14,8 +14,9 @@
|
|||
<p><select class="width-full js-blog-nav-categories">
|
||||
<option value="0">{$aLang.blog.categories.category}</option>
|
||||
|
||||
{foreach $aNavigatorBlogCategories as $oCategoryItem}
|
||||
<option style="margin-left: {$oCategoryItem->getLevel()*20}px;" value="{$oCategoryItem->getId()}">{$oCategoryItem->getTitle()|escape}</option>
|
||||
{foreach $aNavigatorBlogCategories as $aCategoryItem}
|
||||
{$oCategoryItem=$aCategoryItem.entity}
|
||||
<option style="margin-left: {$aCategoryItem.level*20}px;" value="{$oCategoryItem->getId()}">{$oCategoryItem->getTitle()}</option>
|
||||
{/foreach}
|
||||
</select></p>
|
||||
|
||||
|
|
|
@ -21,13 +21,14 @@
|
|||
'count' => $iCountBlogsAll
|
||||
] ]}
|
||||
|
||||
{foreach $aBlogCategories as $oCategory}
|
||||
{foreach $aBlogCategories as $aCategory}
|
||||
{$oCategory=$aCategory.entity}
|
||||
{$aItems[] = [
|
||||
'text' => ($oCategory->getTitle()|escape),
|
||||
'url' => $oCategory->getUrlWeb(),
|
||||
'attributes' => "data-search-type=\"blogs\" data-name=\"category\" data-value=\"{$oCategory->getId()}\" style=\"margin-left: {$oCategory->getLevel() * 20}px;\"",
|
||||
'text' => ($oCategory->getTitle()),
|
||||
'url' => '#',
|
||||
'attributes' => "data-search-type=\"blogs\" data-name=\"category\" data-value=\"{$oCategory->getId()}\" style=\"margin-left: {$aCategory.level * 20}px;\"",
|
||||
'classes' => 'js-search-ajax-option',
|
||||
'count' => $oCategory->getCountBlogs()
|
||||
'count' => $oCategory->getCountTargetOfDescendants()
|
||||
]}
|
||||
{/foreach}
|
||||
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
|
||||
{*
|
||||
Вывод категорий на странице создания нового объекта
|
||||
*}
|
||||
|
||||
{$aCategoriesCurrentId=[]}
|
||||
{if $aCategoryParams.form_fill_current_from_request && $_aRequest[$aCategoryParams.form_field]}
|
||||
{$aCategoriesCurrentId=$_aRequest[$aCategoryParams.form_field]}
|
||||
{else}
|
||||
{if $aCategoriesCurrent}
|
||||
{foreach $aCategoriesCurrent as $oCategoryCurrent}
|
||||
{$aCategoriesCurrentId[]=$oCategoryCurrent->getId()}
|
||||
{/foreach}
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
Категория:
|
||||
<select name="{$aCategoryParams.form_field}[]" {if $aCategoryParams.multiple}multiple="multiple" style="height: 200px;"{/if}>
|
||||
{if !$aCategoryParams.validate_require}
|
||||
<option value="">—</option>
|
||||
{/if}
|
||||
{foreach $aCategories as $aCategory}
|
||||
{$oCategory=$aCategory.entity}
|
||||
<option value="{$oCategory->getId()}" {if in_array($oCategory->getId(),$aCategoriesCurrentId)}selected="selected"{/if} style="margin-left: {$oCategory->getLevel()*10}px;">{''|str_pad:(2*$aCategory.level):'-'|cat:$oCategory->getTitle()}</option>
|
||||
{/foreach}
|
||||
</select>
|
|
@ -24,24 +24,10 @@
|
|||
|
||||
{* Категория блога *}
|
||||
{if Config::Get('module.blog.category_allow') and ($oUserCurrent->isAdministrator() or ! Config::Get('module.blog.category_only_admin'))}
|
||||
{$aBlogCategoriesCustom = [
|
||||
[ 'value' => 0, 'text' => '—' ]
|
||||
]}
|
||||
|
||||
{foreach $aBlogCategories as $oBlogCategory}
|
||||
{$aBlogCategoriesCustom[] = [
|
||||
'value' => $oBlogCategory->getId(),
|
||||
'text' => $oBlogCategory->getTitle()|escape
|
||||
]}
|
||||
{/foreach}
|
||||
{* Подключаем блок для управления категориями *}
|
||||
{insert name="block" block="categoryUpdate" params=[ 'target' => $oBlogEdit, 'entity' => 'ModuleBlog_EntityBlog' ]}
|
||||
|
||||
{include 'components/field/field.select.tpl'
|
||||
sName = 'blog_category'
|
||||
sLabel = $aLang.blog.add.fields.category.label
|
||||
sNote = $aLang.blog.add.fields.category.note
|
||||
sInputClasses = 'width-200'
|
||||
aItems = $aBlogCategoriesCustom
|
||||
sSelectedValue = $_aRequest.blog_category}
|
||||
{/if}
|
||||
|
||||
|
||||
|
|
|
@ -580,3 +580,27 @@ CREATE TABLE IF NOT EXISTS `prefix_category_type` (
|
|||
KEY `state` (`state`),
|
||||
KEY `target_type` (`target_type`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
|
||||
|
||||
-- 10.07.2014
|
||||
ALTER TABLE `prefix_category` ADD `data` VARCHAR( 500 ) NOT NULL ;
|
||||
ALTER TABLE `prefix_category` ADD `count_target` INT NOT NULL DEFAULT '0' AFTER `state` ,
|
||||
ADD INDEX ( `count_target` ) ;
|
||||
ALTER TABLE `prefix_blog_category` DROP FOREIGN KEY `prefix_blog_category_ibfk_1` ;
|
||||
ALTER TABLE `prefix_blog` DROP FOREIGN KEY `prefix_blog_ibfk_1` ;
|
||||
ALTER TABLE `prefix_blog` DROP `category_id` ;
|
||||
DROP TABLE `prefix_blog_category`;
|
||||
|
||||
INSERT INTO `social`.`prefix_category_type` (
|
||||
`id` ,
|
||||
`target_type` ,
|
||||
`title` ,
|
||||
`state` ,
|
||||
`date_create` ,
|
||||
`date_update` ,
|
||||
`params`
|
||||
)
|
||||
VALUES (
|
||||
NULL , 'blog', 'Блоги', '1', '2014-07-14 00:00:00', NULL , ''
|
||||
);
|
||||
|
||||
|
|
Loading…
Reference in a new issue