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

Форматирование кода под PSR-2

This commit is contained in:
Mzhelskiy Maxim 2014-10-08 15:49:34 +07:00
parent 3dc0465e1e
commit 039de4359d
180 changed files with 43592 additions and 39279 deletions

View file

@ -25,132 +25,147 @@
* @package application.actions
* @since 1.0
*/
class ActionAdmin extends Action {
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent=null;
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect='admin';
class ActionAdmin extends Action
{
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent = null;
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect = 'admin';
/**
* Инициализация
*
* @return string
*/
public function Init() {
/**
* Если нет прав доступа - перекидываем на 404 страницу
*/
if(!$this->User_IsAuthorization() or !$oUserCurrent=$this->User_GetUserCurrent() or !$oUserCurrent->isAdministrator()) {
return parent::EventNotFound();
}
$this->SetDefaultEvent('index');
/**
* Инициализация
*
* @return string
*/
public function Init()
{
/**
* Если нет прав доступа - перекидываем на 404 страницу
*/
if (!$this->User_IsAuthorization() or !$oUserCurrent = $this->User_GetUserCurrent() or !$oUserCurrent->isAdministrator()) {
return parent::EventNotFound();
}
$this->SetDefaultEvent('index');
$this->oUserCurrent=$oUserCurrent;
}
/**
* Регистрация евентов
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventIndex');
$this->AddEvent('plugins','EventPlugins');
}
$this->oUserCurrent = $oUserCurrent;
}
/**
* Регистрация евентов
*/
protected function RegisterEvent()
{
$this->AddEvent('index', 'EventIndex');
$this->AddEvent('plugins', 'EventPlugins');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Отображение главной страницы админки
*/
protected function EventIndex() {
/**
* Определяем доступность установки расширенной админ-панели
*/
$aPluginsAll=func_list_plugins(true);
if (in_array('admin',$aPluginsAll)) {
$this->Viewer_Assign('bAvailableAdminPlugin',true);
}
}
/**
* Страница со списком плагинов
*
*/
protected function EventPlugins() {
$this->sMenuHeadItemSelect='plugins';
/**
* Получаем название плагина и действие
*/
if($sPlugin=getRequestStr('plugin',null,'get') and $sAction=getRequestStr('action',null,'get')) {
return $this->SubmitManagePlugin($sPlugin,$sAction);
}
/**
* Получаем список блогов
*/
$aPlugins=$this->PluginManager_GetPluginsItems(array('order'=>'name'));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign("aPlugins",$aPlugins);
$this->Viewer_AddHtmlTitle($this->Lang_Get('admin.plugins.title'));
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('plugins');
}
/**
* Активация\деактивация плагина
*
* @param string $sPlugin Имя плагина
* @param string $sAction Действие
*/
protected function SubmitManagePlugin($sPlugin,$sAction) {
$this->Security_ValidateSendForm();
if(!in_array($sAction,array('activate','deactivate','remove','apply_update'))) {
$this->Message_AddError($this->Lang_Get('admin.plugins.notices.unknown_action'),$this->Lang_Get('error'),true);
Router::Location(Router::GetPath('admin/plugins'));
}
$bResult=false;
/**
* Активируем\деактивируем плагин
*/
if ($sAction=='activate') {
$bResult=$this->PluginManager_ActivatePlugin($sPlugin);
} elseif ($sAction=='deactivate') {
$bResult=$this->PluginManager_DeactivatePlugin($sPlugin);
} elseif ($sAction=='remove') {
$bResult=$this->PluginManager_RemovePlugin($sPlugin);
} elseif ($sAction=='apply_update') {
$this->PluginManager_ApplyPluginUpdate($sPlugin);
$bResult=true;
}
if($bResult) {
$this->Message_AddNotice($this->Lang_Get('admin.plugins.notices.action_ok'),$this->Lang_Get('attention'),true);
} else {
if(!($aMessages=$this->Message_GetErrorSession()) or !count($aMessages)) $this->Message_AddErrorSingle($this->Lang_Get('system_error'),$this->Lang_Get('error'),true);
}
/**
* Возвращаем на страницу управления плагинами
*/
Router::Location(Router::GetPath('admin').'plugins/');
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown() {
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
}
/**
* Отображение главной страницы админки
*/
protected function EventIndex()
{
/**
* Определяем доступность установки расширенной админ-панели
*/
$aPluginsAll = func_list_plugins(true);
if (in_array('admin', $aPluginsAll)) {
$this->Viewer_Assign('bAvailableAdminPlugin', true);
}
}
/**
* Страница со списком плагинов
*
*/
protected function EventPlugins()
{
$this->sMenuHeadItemSelect = 'plugins';
/**
* Получаем название плагина и действие
*/
if ($sPlugin = getRequestStr('plugin', null, 'get') and $sAction = getRequestStr('action', null, 'get')) {
return $this->SubmitManagePlugin($sPlugin, $sAction);
}
/**
* Получаем список блогов
*/
$aPlugins = $this->PluginManager_GetPluginsItems(array('order' => 'name'));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign("aPlugins", $aPlugins);
$this->Viewer_AddHtmlTitle($this->Lang_Get('admin.plugins.title'));
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('plugins');
}
/**
* Активация\деактивация плагина
*
* @param string $sPlugin Имя плагина
* @param string $sAction Действие
*/
protected function SubmitManagePlugin($sPlugin, $sAction)
{
$this->Security_ValidateSendForm();
if (!in_array($sAction, array('activate', 'deactivate', 'remove', 'apply_update'))) {
$this->Message_AddError($this->Lang_Get('admin.plugins.notices.unknown_action'), $this->Lang_Get('error'),
true);
Router::Location(Router::GetPath('admin/plugins'));
}
$bResult = false;
/**
* Активируем\деактивируем плагин
*/
if ($sAction == 'activate') {
$bResult = $this->PluginManager_ActivatePlugin($sPlugin);
} elseif ($sAction == 'deactivate') {
$bResult = $this->PluginManager_DeactivatePlugin($sPlugin);
} elseif ($sAction == 'remove') {
$bResult = $this->PluginManager_RemovePlugin($sPlugin);
} elseif ($sAction == 'apply_update') {
$this->PluginManager_ApplyPluginUpdate($sPlugin);
$bResult = true;
}
if ($bResult) {
$this->Message_AddNotice($this->Lang_Get('admin.plugins.notices.action_ok'), $this->Lang_Get('attention'),
true);
} else {
if (!($aMessages = $this->Message_GetErrorSession()) or !count($aMessages)) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'), true);
}
}
/**
* Возвращаем на страницу управления плагинами
*/
Router::Location(Router::GetPath('admin') . 'plugins/');
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown()
{
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect', $this->sMenuHeadItemSelect);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -25,131 +25,147 @@
* @package application.actions
* @since 1.0
*/
class ActionBlogs extends Action {
/**
* Инициализация
*/
public function Init() {
/**
* Загружаем в шаблон JS текстовки
*/
$this->Lang_AddLangJs(array(
'blog.join.join','blog.join.leave'
));
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_list'));
}
/**
* Регистрируем евенты
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^(page([1-9]\d{0,5}))?$/i','EventShowBlogs');
$this->AddEventPreg('/^ajax-search$/i','EventAjaxSearch');
}
class ActionBlogs extends Action
{
/**
* Инициализация
*/
public function Init()
{
/**
* Загружаем в шаблон JS текстовки
*/
$this->Lang_AddLangJs(array(
'blog.join.join',
'blog.join.leave'
));
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_list'));
}
/**
* Регистрируем евенты
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^(page([1-9]\d{0,5}))?$/i', 'EventShowBlogs');
$this->AddEventPreg('/^ajax-search$/i', 'EventAjaxSearch');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Поиск блогов по названию
*/
protected function EventAjaxSearch() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Фильтр
*/
$aFilter=array(
'exclude_type' => 'personal',
);
$sOrderWay=in_array(getRequestStr('order'),array('desc','asc')) ? getRequestStr('order') : 'desc';
$sOrderField=in_array(getRequestStr('sort_by'),array('blog_id','blog_title','blog_rating','blog_count_user','blog_count_topic')) ? getRequestStr('sort_by') : 'blog_rating';
if (is_numeric(getRequestStr('pageNext')) and getRequestStr('pageNext')>0) {
$iPage=getRequestStr('pageNext');
} else {
$iPage=1;
}
/**
* Получаем из реквеста первые буквы блога
*/
if ($sTitle=getRequestStr('sText')) {
$sTitle=str_replace('%','',$sTitle);
} else {
$sTitle='';
}
if ($sTitle) {
$aFilter['title']="%{$sTitle}%";
}
/**
* Категории
*/
if (getRequestStr('category') and $oCategory=$this->Category_GetCategoryById(getRequestStr('category'))) {
/**
* Получаем ID всех блогов
* По сути это костыль, но т.к. блогов обычно не много, то норм
*/
$aBlogIds=$this->Blog_GetTargetIdsByCategory($oCategory,1,1000,true);
$aFilter['id']=$aBlogIds ? $aBlogIds : array(0);
}
/**
* Тип
*/
if (in_array(getRequestStr('type'),array('open','close'))) {
$aFilter['type']=getRequestStr('type');
}
/**
* Ищем блоги
*/
$aResult=$this->Blog_GetBlogsByFilter($aFilter,array($sOrderField=>$sOrderWay),$iPage,Config::Get('module.blog.per_page'));
$bHideMore=$iPage*Config::Get('module.blog.per_page')>=$aResult['count'];
/**
* Формируем и возвращает ответ
*/
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aBlogs',$aResult['collection']);
$oViewer->Assign('oUserCurrent',$this->User_GetUserCurrent());
$oViewer->Assign('sBlogsEmptyList',$this->Lang_Get('search.alerts.empty'));
$oViewer->Assign('bUseMore', true);
$oViewer->Assign('bHideMore', $bHideMore);
$oViewer->Assign('iSearchCount', $aResult['count']);
$this->Viewer_AssignAjax('sText',$oViewer->Fetch("components/blog/blog-list.tpl"));
/**
* Для подгрузки
*/
$this->Viewer_AssignAjax('count_loaded',count($aResult['collection']));
$this->Viewer_AssignAjax('pageNext',count($aResult['collection'])>0 ? $iPage+1 : $iPage);
$this->Viewer_AssignAjax('bHideMore',$bHideMore);
}
/**
* Отображение списка блогов
*/
protected function EventShowBlogs() {
/**
* Фильтр поиска блогов
*/
$aFilter=array(
'exclude_type' => 'personal'
);
/**
* Получаем список блогов
*/
$aResult=$this->Blog_GetBlogsByFilter($aFilter,array('blog_rating'=>'desc'),1,Config::Get('module.blog.per_page'));
$aBlogs=$aResult['collection'];
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign("aBlogs",$aBlogs);
$this->Viewer_Assign('iSearchCount', $aResult['count']);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Поиск блогов по названию
*/
protected function EventAjaxSearch()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Фильтр
*/
$aFilter = array(
'exclude_type' => 'personal',
);
$sOrderWay = in_array(getRequestStr('order'), array('desc', 'asc')) ? getRequestStr('order') : 'desc';
$sOrderField = in_array(getRequestStr('sort_by'), array(
'blog_id',
'blog_title',
'blog_rating',
'blog_count_user',
'blog_count_topic'
)) ? getRequestStr('sort_by') : 'blog_rating';
if (is_numeric(getRequestStr('pageNext')) and getRequestStr('pageNext') > 0) {
$iPage = getRequestStr('pageNext');
} else {
$iPage = 1;
}
/**
* Получаем из реквеста первые буквы блога
*/
if ($sTitle = getRequestStr('sText')) {
$sTitle = str_replace('%', '', $sTitle);
} else {
$sTitle = '';
}
if ($sTitle) {
$aFilter['title'] = "%{$sTitle}%";
}
/**
* Категории
*/
if (getRequestStr('category') and $oCategory = $this->Category_GetCategoryById(getRequestStr('category'))) {
/**
* Получаем ID всех блогов
* По сути это костыль, но т.к. блогов обычно не много, то норм
*/
$aBlogIds = $this->Blog_GetTargetIdsByCategory($oCategory, 1, 1000, true);
$aFilter['id'] = $aBlogIds ? $aBlogIds : array(0);
}
/**
* Тип
*/
if (in_array(getRequestStr('type'), array('open', 'close'))) {
$aFilter['type'] = getRequestStr('type');
}
/**
* Ищем блоги
*/
$aResult = $this->Blog_GetBlogsByFilter($aFilter, array($sOrderField => $sOrderWay), $iPage,
Config::Get('module.blog.per_page'));
$bHideMore = $iPage * Config::Get('module.blog.per_page') >= $aResult['count'];
/**
* Формируем и возвращает ответ
*/
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('aBlogs', $aResult['collection']);
$oViewer->Assign('oUserCurrent', $this->User_GetUserCurrent());
$oViewer->Assign('sBlogsEmptyList', $this->Lang_Get('search.alerts.empty'));
$oViewer->Assign('bUseMore', true);
$oViewer->Assign('bHideMore', $bHideMore);
$oViewer->Assign('iSearchCount', $aResult['count']);
$this->Viewer_AssignAjax('sText', $oViewer->Fetch("components/blog/blog-list.tpl"));
/**
* Для подгрузки
*/
$this->Viewer_AssignAjax('count_loaded', count($aResult['collection']));
$this->Viewer_AssignAjax('pageNext', count($aResult['collection']) > 0 ? $iPage + 1 : $iPage);
$this->Viewer_AssignAjax('bHideMore', $bHideMore);
}
/**
* Отображение списка блогов
*/
protected function EventShowBlogs()
{
/**
* Фильтр поиска блогов
*/
$aFilter = array(
'exclude_type' => 'personal'
);
/**
* Получаем список блогов
*/
$aResult = $this->Blog_GetBlogsByFilter($aFilter, array('blog_rating' => 'desc'), 1,
Config::Get('module.blog.per_page'));
$aBlogs = $aResult['collection'];
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign("aBlogs", $aBlogs);
$this->Viewer_Assign('iSearchCount', $aResult['count']);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
}

View file

@ -25,76 +25,84 @@
* @package application.actions
* @since 1.0
*/
class ActionComments extends Action {
/**
* Текущий юзер
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent=null;
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect='blog';
class ActionComments extends Action
{
/**
* Текущий юзер
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent = null;
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect = 'blog';
/**
* Инициализация
*/
public function Init() {
$this->oUserCurrent=$this->User_GetUserCurrent();
}
/**
* Регистрация евентов
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^\d+$/i','EventShowComment');
}
/**
* Инициализация
*/
public function Init()
{
$this->oUserCurrent = $this->User_GetUserCurrent();
}
/**
* Регистрация евентов
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^\d+$/i', 'EventShowComment');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Обрабатывает ссылку на конкретный комментарий, определят к какому топику он относится и перенаправляет на него
* Актуально при использовании постраничности комментариев
*/
protected function EventShowComment() {
$iCommentId=$this->sCurrentEvent;
/**
* Проверяем к чему относится комментарий
*/
if (!($oComment=$this->Comment_GetCommentById($iCommentId))) {
return parent::EventNotFound();
}
if ($oComment->getTargetType()!='topic' or !($oTopic=$oComment->getTarget())) {
return parent::EventNotFound();
}
/**
* Определяем необходимую страницу для отображения комментария
*/
if (!Config::Get('module.comment.use_nested') or !Config::Get('module.comment.nested_per_page')) {
Router::Location($oTopic->getUrl().'#comment'.$oComment->getId());
}
$iPage=$this->Comment_GetPageCommentByTargetId($oComment->getTargetId(),$oComment->getTargetType(),$oComment);
if ($iPage==1) {
Router::Location($oTopic->getUrl().'#comment'.$oComment->getId());
} else {
Router::Location($oTopic->getUrl()."?cmtpage={$iPage}#comment".$oComment->getId());
}
exit();
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown() {
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
}
/**
* Обрабатывает ссылку на конкретный комментарий, определят к какому топику он относится и перенаправляет на него
* Актуально при использовании постраничности комментариев
*/
protected function EventShowComment()
{
$iCommentId = $this->sCurrentEvent;
/**
* Проверяем к чему относится комментарий
*/
if (!($oComment = $this->Comment_GetCommentById($iCommentId))) {
return parent::EventNotFound();
}
if ($oComment->getTargetType() != 'topic' or !($oTopic = $oComment->getTarget())) {
return parent::EventNotFound();
}
/**
* Определяем необходимую страницу для отображения комментария
*/
if (!Config::Get('module.comment.use_nested') or !Config::Get('module.comment.nested_per_page')) {
Router::Location($oTopic->getUrl() . '#comment' . $oComment->getId());
}
$iPage = $this->Comment_GetPageCommentByTargetId($oComment->getTargetId(), $oComment->getTargetType(),
$oComment);
if ($iPage == 1) {
Router::Location($oTopic->getUrl() . '#comment' . $oComment->getId());
} else {
Router::Location($oTopic->getUrl() . "?cmtpage={$iPage}#comment" . $oComment->getId());
}
exit();
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown()
{
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect', $this->sMenuHeadItemSelect);
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,71 +25,79 @@
* @package application.actions
* @since 1.0
*/
class ActionError extends Action {
/**
* Список специфических HTTP ошибок для которых необходимо отдавать header
*
* @var array
*/
protected $aHttpErrors=array(
'404' => array(
'header' => '404 Not Found',
),
'403' => array(
'header' => '403 Forbidden',
),
'500' => array(
'header' => '500 Internal Server Error',
),
);
/**
* Инициализация экшена
*
*/
public function Init() {
/**
* Устанавливаем дефолтный евент
*/
$this->SetDefaultEvent('index');
/**
* Запрешаем отображать статистику выполнения
*/
Router::SetIsShowStats(false);
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventError');
$this->AddEventPreg('/^\d{3}$/i','EventError');
}
/**
* Вывод ошибки
*
*/
protected function EventError() {
/**
* Если евент равен одной из ошибок из $aHttpErrors, то шлем браузеру специфичный header
* Например, для 404 в хидере будет послан браузеру заголовок HTTP/1.1 404 Not Found
*/
if (array_key_exists($this->sCurrentEvent,$this->aHttpErrors)) {
/**
* Смотрим есть ли сообщения об ошибках
*/
if (!$this->Message_GetError()) {
$this->Message_AddErrorSingle($this->Lang_Get('common.error.system.code.'.$this->sCurrentEvent),$this->sCurrentEvent);
}
$aHttpError=$this->aHttpErrors[$this->sCurrentEvent];
if (isset($aHttpError['header'])) {
$sProtocol=isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
header("{$sProtocol} {$aHttpError['header']}");
}
}
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('error'));
$this->SetTemplateAction('index');
}
class ActionError extends Action
{
/**
* Список специфических HTTP ошибок для которых необходимо отдавать header
*
* @var array
*/
protected $aHttpErrors = array(
'404' => array(
'header' => '404 Not Found',
),
'403' => array(
'header' => '403 Forbidden',
),
'500' => array(
'header' => '500 Internal Server Error',
),
);
/**
* Инициализация экшена
*
*/
public function Init()
{
/**
* Устанавливаем дефолтный евент
*/
$this->SetDefaultEvent('index');
/**
* Запрешаем отображать статистику выполнения
*/
Router::SetIsShowStats(false);
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent()
{
$this->AddEvent('index', 'EventError');
$this->AddEventPreg('/^\d{3}$/i', 'EventError');
}
/**
* Вывод ошибки
*
*/
protected function EventError()
{
/**
* Если евент равен одной из ошибок из $aHttpErrors, то шлем браузеру специфичный header
* Например, для 404 в хидере будет послан браузеру заголовок HTTP/1.1 404 Not Found
*/
if (array_key_exists($this->sCurrentEvent, $this->aHttpErrors)) {
/**
* Смотрим есть ли сообщения об ошибках
*/
if (!$this->Message_GetError()) {
$this->Message_AddErrorSingle($this->Lang_Get('common.error.system.code.' . $this->sCurrentEvent),
$this->sCurrentEvent);
}
$aHttpError = $this->aHttpErrors[$this->sCurrentEvent];
if (isset($aHttpError['header'])) {
$sProtocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
header("{$sProtocol} {$aHttpError['header']}");
}
}
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('error'));
$this->SetTemplateAction('index');
}
}

View file

@ -25,318 +25,346 @@
* @package application.actions
* @since 1.0
*/
class ActionIndex extends Action {
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect='blog';
/**
* Меню
*
* @var string
*/
protected $sMenuItemSelect='index';
/**
* Субменю
*
* @var string
*/
protected $sMenuSubItemSelect='good';
/**
* Число новых топиков
*
* @var int
*/
protected $iCountTopicsNew=0;
/**
* Число новых топиков в коллективных блогах
*
* @var int
*/
protected $iCountTopicsCollectiveNew=0;
/**
* Число новых топиков в персональных блогах
*
* @var int
*/
protected $iCountTopicsPersonalNew=0;
/**
* URL-префикс для навигации по топикам
*
* @var string
*/
protected $sNavTopicsSubUrl = '';
class ActionIndex extends Action
{
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect = 'blog';
/**
* Меню
*
* @var string
*/
protected $sMenuItemSelect = 'index';
/**
* Субменю
*
* @var string
*/
protected $sMenuSubItemSelect = 'good';
/**
* Число новых топиков
*
* @var int
*/
protected $iCountTopicsNew = 0;
/**
* Число новых топиков в коллективных блогах
*
* @var int
*/
protected $iCountTopicsCollectiveNew = 0;
/**
* Число новых топиков в персональных блогах
*
* @var int
*/
protected $iCountTopicsPersonalNew = 0;
/**
* URL-префикс для навигации по топикам
*
* @var string
*/
protected $sNavTopicsSubUrl = '';
/**
* Инициализация
*
*/
public function Init() {
/**
* Подсчитываем новые топики
*/
$this->iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew();
$this->iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew();
$this->iCountTopicsNew=$this->iCountTopicsCollectiveNew+$this->iCountTopicsPersonalNew;
$this->sNavTopicsSubUrl = Router::GetPath('index');
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^(page([1-9]\d{0,5}))?$/i','EventIndex');
$this->AddEventPreg('/^new$/i','/^(page([1-9]\d{0,5}))?$/i','EventNew');
$this->AddEventPreg('/^newall$/i','/^(page([1-9]\d{0,5}))?$/i','EventNewAll');
$this->AddEventPreg('/^discussed$/i','/^(page([1-9]\d{0,5}))?$/i','EventDiscussed');
$this->AddEventPreg('/^top$/i','/^(page([1-9]\d{0,5}))?$/i','EventTop');
}
/**
* Инициализация
*
*/
public function Init()
{
/**
* Подсчитываем новые топики
*/
$this->iCountTopicsCollectiveNew = $this->Topic_GetCountTopicsCollectiveNew();
$this->iCountTopicsPersonalNew = $this->Topic_GetCountTopicsPersonalNew();
$this->iCountTopicsNew = $this->iCountTopicsCollectiveNew + $this->iCountTopicsPersonalNew;
$this->sNavTopicsSubUrl = Router::GetPath('index');
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^(page([1-9]\d{0,5}))?$/i', 'EventIndex');
$this->AddEventPreg('/^new$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventNew');
$this->AddEventPreg('/^newall$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventNewAll');
$this->AddEventPreg('/^discussed$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventDiscussed');
$this->AddEventPreg('/^top$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTop');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Вывод рейтинговых топиков
*/
protected function EventTop() {
$sPeriod=Config::Get('module.topic.default_period_top');
if (in_array(getRequestStr('period'),array(1,7,30,'all'))) {
$sPeriod=getRequestStr('period');
}
if (!$sPeriod) $sPeriod=1;
/**
* Меню
*/
$this->sMenuSubItemSelect='top';
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
if ($iPage==1 and !getRequest('period')) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('index').'top/');
}
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsTop($iPage,Config::Get('module.topic.per_page'),$sPeriod=='all' ? null : $sPeriod*60*60*24);
/**
* Если нет топиков за 1 день, то показываем за неделю (7)
*/
if (!$aResult['count'] and $iPage==1 and !getRequest('period')) {
$sPeriod=7;
$aResult=$this->Topic_GetTopicsTop($iPage,Config::Get('module.topic.per_page'),$sPeriod=='all' ? null : $sPeriod*60*60*24);
}
$aTopics=$aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>&$aTopics));
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('index').'top',array('period'=>$sPeriod));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('sPeriodSelectCurrent',$sPeriod);
$this->Viewer_Assign('sPeriodSelectRoot',Router::GetPath('index').'top/');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_top'));
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.top_period_'.$sPeriod));
}
/**
* Вывод обсуждаемых топиков
*/
protected function EventDiscussed() {
$sPeriod=Config::Get('module.topic.default_period_discussed');
if (in_array(getRequestStr('period'),array(1,7,30,'all'))) {
$sPeriod=getRequestStr('period');
}
if (!$sPeriod) $sPeriod=1;
/**
* Меню
*/
$this->sMenuSubItemSelect='discussed';
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
if ($iPage==1 and !getRequest('period')) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('index').'discussed/');
}
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsDiscussed($iPage,Config::Get('module.topic.per_page'),$sPeriod=='all' ? null : $sPeriod*60*60*24);
/**
* Если нет топиков за 1 день, то показываем за неделю (7)
*/
if (!$aResult['count'] and $iPage==1 and !getRequest('period')) {
$sPeriod=7;
$aResult=$this->Topic_GetTopicsDiscussed($iPage,Config::Get('module.topic.per_page'),$sPeriod=='all' ? null : $sPeriod*60*60*24);
}
$aTopics=$aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>&$aTopics));
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('index').'discussed',array('period'=>$sPeriod));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('sPeriodSelectCurrent',$sPeriod);
$this->Viewer_Assign('sPeriodSelectRoot',Router::GetPath('index').'discussed/');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_discussed'));
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.top_period_'.$sPeriod));
}
/**
* Вывод новых топиков
*/
protected function EventNew() {
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss').'new/',Config::Get('view.name'));
/**
* Меню
*/
$this->sMenuSubItemSelect='new';
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsNew($iPage,Config::Get('module.topic.per_page'));
$aTopics=$aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>&$aTopics));
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('index').'new');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_new'));
}
/**
* Вывод ВСЕХ новых топиков
*/
protected function EventNewAll() {
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all'));
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss').'new/',Config::Get('view.name'));
/**
* Меню
*/
$this->sMenuSubItemSelect='new';
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsNewAll($iPage,Config::Get('module.topic.per_page'));
$aTopics=$aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>&$aTopics));
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('index').'newall');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Вывод интересных на главную
*
*/
protected function EventIndex() {
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss').'index/',Config::Get('view.name'));
/**
* Меню
*/
$this->sMenuSubItemSelect='good';
/**
* Передан ли номер страницы
*/
$iPage=$this->GetEventMatch(2) ? $this->GetEventMatch(2) : 1;
/**
* Устанавливаем основной URL для поисковиков
*/
if ($iPage==1) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('/'));
}
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsGood($iPage,Config::Get('module.topic.per_page'));
$aTopics=$aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>&$aTopics));
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('index'));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* При завершении экшена загружаем переменные в шаблон
*
*/
public function EventShutdown() {
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsNew',$this->iCountTopicsNew);
$this->Viewer_Assign('iCountTopicsCollectiveNew',$this->iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew',$this->iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsSubNew',$this->iCountTopicsNew);
$this->Viewer_Assign('sNavTopicsSubUrl',$this->sNavTopicsSubUrl);
}
/**
* Вывод рейтинговых топиков
*/
protected function EventTop()
{
$sPeriod = Config::Get('module.topic.default_period_top');
if (in_array(getRequestStr('period'), array(1, 7, 30, 'all'))) {
$sPeriod = getRequestStr('period');
}
if (!$sPeriod) {
$sPeriod = 1;
}
/**
* Меню
*/
$this->sMenuSubItemSelect = 'top';
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
if ($iPage == 1 and !getRequest('period')) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('index') . 'top/');
}
/**
* Получаем список топиков
*/
$aResult = $this->Topic_GetTopicsTop($iPage, Config::Get('module.topic.per_page'),
$sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
/**
* Если нет топиков за 1 день, то показываем за неделю (7)
*/
if (!$aResult['count'] and $iPage == 1 and !getRequest('period')) {
$sPeriod = 7;
$aResult = $this->Topic_GetTopicsTop($iPage, Config::Get('module.topic.per_page'),
$sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
}
$aTopics = $aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => &$aTopics));
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('index') . 'top', array('period' => $sPeriod));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics', $aTopics);
$this->Viewer_Assign('aPaging', $aPaging);
$this->Viewer_Assign('sPeriodSelectCurrent', $sPeriod);
$this->Viewer_Assign('sPeriodSelectRoot', Router::GetPath('index') . 'top/');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_top'));
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.top_period_' . $sPeriod));
}
/**
* Вывод обсуждаемых топиков
*/
protected function EventDiscussed()
{
$sPeriod = Config::Get('module.topic.default_period_discussed');
if (in_array(getRequestStr('period'), array(1, 7, 30, 'all'))) {
$sPeriod = getRequestStr('period');
}
if (!$sPeriod) {
$sPeriod = 1;
}
/**
* Меню
*/
$this->sMenuSubItemSelect = 'discussed';
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
if ($iPage == 1 and !getRequest('period')) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('index') . 'discussed/');
}
/**
* Получаем список топиков
*/
$aResult = $this->Topic_GetTopicsDiscussed($iPage, Config::Get('module.topic.per_page'),
$sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
/**
* Если нет топиков за 1 день, то показываем за неделю (7)
*/
if (!$aResult['count'] and $iPage == 1 and !getRequest('period')) {
$sPeriod = 7;
$aResult = $this->Topic_GetTopicsDiscussed($iPage, Config::Get('module.topic.per_page'),
$sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
}
$aTopics = $aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => &$aTopics));
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('index') . 'discussed', array('period' => $sPeriod));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics', $aTopics);
$this->Viewer_Assign('aPaging', $aPaging);
$this->Viewer_Assign('sPeriodSelectCurrent', $sPeriod);
$this->Viewer_Assign('sPeriodSelectRoot', Router::GetPath('index') . 'discussed/');
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_discussed'));
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.top_period_' . $sPeriod));
}
/**
* Вывод новых топиков
*/
protected function EventNew()
{
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss') . 'new/', Config::Get('view.name'));
/**
* Меню
*/
$this->sMenuSubItemSelect = 'new';
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
/**
* Получаем список топиков
*/
$aResult = $this->Topic_GetTopicsNew($iPage, Config::Get('module.topic.per_page'));
$aTopics = $aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => &$aTopics));
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('index') . 'new');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics', $aTopics);
$this->Viewer_Assign('aPaging', $aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_new'));
}
/**
* Вывод ВСЕХ новых топиков
*/
protected function EventNewAll()
{
$this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all'));
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss') . 'new/', Config::Get('view.name'));
/**
* Меню
*/
$this->sMenuSubItemSelect = 'new';
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
/**
* Получаем список топиков
*/
$aResult = $this->Topic_GetTopicsNewAll($iPage, Config::Get('module.topic.per_page'));
$aTopics = $aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => &$aTopics));
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('index') . 'newall');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics', $aTopics);
$this->Viewer_Assign('aPaging', $aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Вывод интересных на главную
*
*/
protected function EventIndex()
{
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss') . 'index/', Config::Get('view.name'));
/**
* Меню
*/
$this->sMenuSubItemSelect = 'good';
/**
* Передан ли номер страницы
*/
$iPage = $this->GetEventMatch(2) ? $this->GetEventMatch(2) : 1;
/**
* Устанавливаем основной URL для поисковиков
*/
if ($iPage == 1) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('/'));
}
/**
* Получаем список топиков
*/
$aResult = $this->Topic_GetTopicsGood($iPage, Config::Get('module.topic.per_page'));
$aTopics = $aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => &$aTopics));
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('index'));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics', $aTopics);
$this->Viewer_Assign('aPaging', $aPaging);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* При завершении экшена загружаем переменные в шаблон
*
*/
public function EventShutdown()
{
$this->Viewer_Assign('sMenuHeadItemSelect', $this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect', $this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect', $this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsNew', $this->iCountTopicsNew);
$this->Viewer_Assign('iCountTopicsCollectiveNew', $this->iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew', $this->iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsSubNew', $this->iCountTopicsNew);
$this->Viewer_Assign('sNavTopicsSubUrl', $this->sNavTopicsSubUrl);
}
}

View file

@ -25,189 +25,206 @@
* @package application.actions
* @since 1.0
*/
class ActionLogin extends Action {
/**
* Инициализация
*
*/
public function Init() {
/**
* Устанавливаем дефолтный евент
*/
$this->SetDefaultEvent('index');
/**
* Отключаем отображение статистики выполнения
*/
Router::SetIsShowStats(false);
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventLogin');
$this->AddEvent('exit','EventExit');
$this->AddEvent('reset','EventReset');
class ActionLogin extends Action
{
/**
* Инициализация
*
*/
public function Init()
{
/**
* Устанавливаем дефолтный евент
*/
$this->SetDefaultEvent('index');
/**
* Отключаем отображение статистики выполнения
*/
Router::SetIsShowStats(false);
}
$this->AddEvent('ajax-login','EventAjaxLogin');
$this->AddEvent('ajax-reset','EventAjaxReset');
}
/**
* Ajax авторизация
*/
protected function EventAjaxLogin() {
/**
* Устанвливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Логин и пароль являются строками?
*/
if (!is_string(getRequest('login')) or !is_string(getRequest('password'))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return;
}
/**
* Проверяем есть ли такой юзер по логину
*/
if ((func_check(getRequest('login'),'mail') and $oUser=$this->User_GetUserByMail(getRequest('login'))) or $oUser=$this->User_GetUserByLogin(getRequest('login'))) {
/**
* Выбираем сценарий валидации
*/
$oUser->_setValidateScenario('signIn');
/**
* Заполняем поля (данные)
*/
$oUser->setCaptcha(getRequestStr('captcha'));
/**
* Запускаем валидацию
*/
if ($oUser->_Validate()) {
/**
* Сверяем хеши паролей и проверяем активен ли юзер
*/
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent()
{
$this->AddEvent('index', 'EventLogin');
$this->AddEvent('exit', 'EventExit');
$this->AddEvent('reset', 'EventReset');
if ($oUser->getPassword()==func_encrypt(getRequest('password'))) {
if (!$oUser->getActivate()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.notices.not_activated', array('reactivation_path' => Router::GetPath('registration') . 'reactivation')));
return;
}
$bRemember=getRequest('remember',false) ? true : false;
/**
* Убиваем каптчу
*/
unset($_SESSION['captcha_keystring_user_auth']);
/**
* Авторизуем
*/
$this->User_Authorization($oUser,$bRemember);
/**
* Определяем редирект
*/
$sUrl=Config::Get('module.user.redirect_after_login');
if (getRequestStr('return-path')) {
$sUrl=getRequestStr('return-path');
}
$this->Viewer_AssignAjax('sUrlRedirect',$sUrl ? $sUrl : Router::GetPath('/'));
return;
}
} else {
/**
* Получаем ошибки
*/
$this->Viewer_AssignAjax('aErrors',$oUser->_getValidateErrors());
}
$this->AddEvent('ajax-login', 'EventAjaxLogin');
$this->AddEvent('ajax-reset', 'EventAjaxReset');
}
/**
* Ajax авторизация
*/
protected function EventAjaxLogin()
{
/**
* Устанвливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Логин и пароль являются строками?
*/
if (!is_string(getRequest('login')) or !is_string(getRequest('password'))) {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return;
}
/**
* Проверяем есть ли такой юзер по логину
*/
if ((func_check(getRequest('login'),
'mail') and $oUser = $this->User_GetUserByMail(getRequest('login'))) or $oUser = $this->User_GetUserByLogin(getRequest('login'))
) {
/**
* Выбираем сценарий валидации
*/
$oUser->_setValidateScenario('signIn');
/**
* Заполняем поля (данные)
*/
$oUser->setCaptcha(getRequestStr('captcha'));
/**
* Запускаем валидацию
*/
if ($oUser->_Validate()) {
/**
* Сверяем хеши паролей и проверяем активен ли юзер
*/
if ($oUser->getPassword() == func_encrypt(getRequest('password'))) {
if (!$oUser->getActivate()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.notices.not_activated',
array('reactivation_path' => Router::GetPath('registration') . 'reactivation')));
return;
}
$bRemember = getRequest('remember', false) ? true : false;
/**
* Убиваем каптчу
*/
unset($_SESSION['captcha_keystring_user_auth']);
/**
* Авторизуем
*/
$this->User_Authorization($oUser, $bRemember);
/**
* Определяем редирект
*/
$sUrl = Config::Get('module.user.redirect_after_login');
if (getRequestStr('return-path')) {
$sUrl = getRequestStr('return-path');
}
$this->Viewer_AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Router::GetPath('/'));
return;
}
} else {
/**
* Получаем ошибки
*/
$this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
}
}
$this->Message_AddErrorSingle($this->Lang_Get('auth.login.notices.error_login'));
}
}
$this->Message_AddErrorSingle($this->Lang_Get('auth.login.notices.error_login'));
}
/**
* Обрабатываем процесс залогинивания
* По факту только отображение шаблона, дальше вступает в дело Ajax
*
*/
protected function EventLogin() {
/**
* Если уже авторизирован
*/
if($this->User_GetUserCurrent()) {
Router::Location(Router::GetPath('/'));
}
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.login.title'));
}
/**
* Обрабатываем процесс разлогинивания
*
*/
protected function EventExit() {
$this->Security_ValidateSendForm();
$this->User_Logout();
Router::Location(Router::GetPath('/'));
}
/**
* Ajax запрос на восстановление пароля
*/
protected function EventAjaxReset() {
/**
* Устанвливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Пользователь с таким емайлом существует?
*/
if ((func_check(getRequestStr('mail'),'mail') and $oUser=$this->User_GetUserByMail(getRequestStr('mail')))) {
/**
* Формируем и отправляем ссылку на смену пароля
*/
$oReminder=Engine::GetEntity('User_Reminder');
$oReminder->setCode(func_generator(32));
$oReminder->setDateAdd(date("Y-m-d H:i:s"));
$oReminder->setDateExpire(date("Y-m-d H:i:s",time()+60*60*24*7));
$oReminder->setDateUsed(null);
$oReminder->setIsUsed(0);
$oReminder->setUserId($oUser->getId());
if ($this->User_AddReminder($oReminder)) {
$this->Message_AddNotice($this->Lang_Get('auth.notices.success_send_password'));
$this->Notify_SendReminderCode($oUser,$oReminder);
return;
}
}
$this->Message_AddError($this->Lang_Get('auth.notices.error_bad_email'),$this->Lang_Get('error'));
}
/**
* Обработка напоминания пароля, подтверждение смены пароля
*
*/
protected function EventReset() {
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.reset.title'));
/**
* Проверка кода на восстановление пароля и генерация нового пароля
*/
if (func_check($this->GetParam(0),'md5')) {
/**
* Проверка кода подтверждения
*/
if ($oReminder=$this->User_GetReminderByCode($this->GetParam(0))) {
if (!$oReminder->getIsUsed() and strtotime($oReminder->getDateExpire())>time() and $oUser=$this->User_GetUserById($oReminder->getUserId())) {
$sNewPassword=func_generator(7);
$oUser->setPassword(func_encrypt($sNewPassword));
if ($this->User_Update($oUser)) {
$oReminder->setDateUsed(date("Y-m-d H:i:s"));
$oReminder->setIsUsed(1);
$this->User_UpdateReminder($oReminder);
$this->Notify_SendReminderPassword($oUser,$sNewPassword);
$this->SetTemplateAction('reset_confirm');
return ;
}
}
}
$this->Message_AddErrorSingle($this->Lang_Get('auth.reset.alerts.error_bad_code'), $this->Lang_Get('error'));
return Router::Action('error');
}
}
/**
* Обрабатываем процесс залогинивания
* По факту только отображение шаблона, дальше вступает в дело Ajax
*
*/
protected function EventLogin()
{
/**
* Если уже авторизирован
*/
if ($this->User_GetUserCurrent()) {
Router::Location(Router::GetPath('/'));
}
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.login.title'));
}
/**
* Обрабатываем процесс разлогинивания
*
*/
protected function EventExit()
{
$this->Security_ValidateSendForm();
$this->User_Logout();
Router::Location(Router::GetPath('/'));
}
/**
* Ajax запрос на восстановление пароля
*/
protected function EventAjaxReset()
{
/**
* Устанвливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Пользователь с таким емайлом существует?
*/
if ((func_check(getRequestStr('mail'), 'mail') and $oUser = $this->User_GetUserByMail(getRequestStr('mail')))) {
/**
* Формируем и отправляем ссылку на смену пароля
*/
$oReminder = Engine::GetEntity('User_Reminder');
$oReminder->setCode(func_generator(32));
$oReminder->setDateAdd(date("Y-m-d H:i:s"));
$oReminder->setDateExpire(date("Y-m-d H:i:s", time() + 60 * 60 * 24 * 7));
$oReminder->setDateUsed(null);
$oReminder->setIsUsed(0);
$oReminder->setUserId($oUser->getId());
if ($this->User_AddReminder($oReminder)) {
$this->Message_AddNotice($this->Lang_Get('auth.notices.success_send_password'));
$this->Notify_SendReminderCode($oUser, $oReminder);
return;
}
}
$this->Message_AddError($this->Lang_Get('auth.notices.error_bad_email'), $this->Lang_Get('error'));
}
/**
* Обработка напоминания пароля, подтверждение смены пароля
*
*/
protected function EventReset()
{
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.reset.title'));
/**
* Проверка кода на восстановление пароля и генерация нового пароля
*/
if (func_check($this->GetParam(0), 'md5')) {
/**
* Проверка кода подтверждения
*/
if ($oReminder = $this->User_GetReminderByCode($this->GetParam(0))) {
if (!$oReminder->getIsUsed() and strtotime($oReminder->getDateExpire()) > time() and $oUser = $this->User_GetUserById($oReminder->getUserId())) {
$sNewPassword = func_generator(7);
$oUser->setPassword(func_encrypt($sNewPassword));
if ($this->User_Update($oUser)) {
$oReminder->setDateUsed(date("Y-m-d H:i:s"));
$oReminder->setIsUsed(1);
$this->User_UpdateReminder($oReminder);
$this->Notify_SendReminderPassword($oUser, $sNewPassword);
$this->SetTemplateAction('reset_confirm');
return;
}
}
}
$this->Message_AddErrorSingle($this->Lang_Get('auth.reset.alerts.error_bad_code'),
$this->Lang_Get('error'));
return Router::Action('error');
}
}
}

View file

@ -26,89 +26,95 @@
* @package application.actions
* @since 1.0
*/
class ActionMy extends Action {
/**
* Объект юзера чей профиль мы смотрим
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserProfile=null;
class ActionMy extends Action
{
/**
* Объект юзера чей профиль мы смотрим
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserProfile = null;
/**
* Инициализация
*/
public function Init() {
}
/**
* Регистрируем евенты
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^.+$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEventPreg('/^.+$/i','/^blog$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEventPreg('/^.+$/i','/^comment$/i','/^(page([1-9]\d{0,5}))?$/i','EventComments');
}
/**
* Инициализация
*/
public function Init()
{
}
/**
* Регистрируем евенты
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^.+$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEventPreg('/^.+$/i', '/^blog$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEventPreg('/^.+$/i', '/^comment$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventComments');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Выводит список топиков которые написал юзер
* Перенаправляет на профиль пользователя
*
*/
protected function EventTopics() {
/**
* Получаем логин из УРЛа
*/
$sUserLogin=$this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
return parent::EventNotFound();
}
/**
* Передан ли номер страницы
*/
if ($this->GetParamEventMatch(0,0)=='blog') {
$iPage=$this->GetParamEventMatch(1,2) ? $this->GetParamEventMatch(1,2) : 1;
} else {
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
}
/**
* Выполняем редирект на новый URL, в новых версиях LS экшен "my" будет удален
*/
$sPage=$iPage==1 ? '' : "page{$iPage}/";
Router::Location($this->oUserProfile->getUserWebPath().'created/topics/'.$sPage);
}
/**
* Выводит список топиков которые написал юзер
* Перенаправляет на профиль пользователя
*
*/
protected function EventTopics()
{
/**
* Получаем логин из УРЛа
*/
$sUserLogin = $this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!($this->oUserProfile = $this->User_GetUserByLogin($sUserLogin))) {
return parent::EventNotFound();
}
/**
* Передан ли номер страницы
*/
if ($this->GetParamEventMatch(0, 0) == 'blog') {
$iPage = $this->GetParamEventMatch(1, 2) ? $this->GetParamEventMatch(1, 2) : 1;
} else {
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
}
/**
* Выполняем редирект на новый URL, в новых версиях LS экшен "my" будет удален
*/
$sPage = $iPage == 1 ? '' : "page{$iPage}/";
Router::Location($this->oUserProfile->getUserWebPath() . 'created/topics/' . $sPage);
}
/**
* Выводит список комментариев которые написал юзер
* Перенаправляет на профиль пользователя
*
*/
protected function EventComments() {
/**
* Получаем логин из УРЛа
*/
$sUserLogin=$this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!($this->oUserProfile=$this->User_GetUserByLogin($sUserLogin))) {
return parent::EventNotFound();
}
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(1,2) ? $this->GetParamEventMatch(1,2) : 1;
/**
* Выполняем редирект на новый URL, в новых версиях LS экшен "my" будет удален
*/
$sPage=$iPage==1 ? '' : "page{$iPage}/";
Router::Location($this->oUserProfile->getUserWebPath().'created/comments/'.$sPage);
}
/**
* Выводит список комментариев которые написал юзер
* Перенаправляет на профиль пользователя
*
*/
protected function EventComments()
{
/**
* Получаем логин из УРЛа
*/
$sUserLogin = $this->sCurrentEvent;
/**
* Проверяем есть ли такой юзер
*/
if (!($this->oUserProfile = $this->User_GetUserByLogin($sUserLogin))) {
return parent::EventNotFound();
}
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(1, 2) ? $this->GetParamEventMatch(1, 2) : 1;
/**
* Выполняем редирект на новый URL, в новых версиях LS экшен "my" будет удален
*/
$sPage = $iPage == 1 ? '' : "page{$iPage}/";
Router::Location($this->oUserProfile->getUserWebPath() . 'created/comments/' . $sPage);
}
}

View file

@ -25,268 +25,296 @@
* @package application.actions
* @since 1.0
*/
class ActionPeople extends Action {
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect='people';
/**
* Меню
*
* @var string
*/
protected $sMenuItemSelect='all';
class ActionPeople extends Action
{
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect = 'people';
/**
* Меню
*
* @var string
*/
protected $sMenuItemSelect = 'all';
/**
* Инициализация
*
*/
public function Init() {
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('user.users'));
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^(index)?$/i','/^(page([1-9]\d{0,5}))?$/i','/^$/i','EventIndex');
$this->AddEventPreg('/^ajax-search$/i','EventAjaxSearch');
/**
* Инициализация
*
*/
public function Init()
{
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('user.users'));
}
$this->AddEventPreg('/^country$/i','/^\d+$/i','/^(page([1-9]\d{0,5}))?$/i','EventCountry');
$this->AddEventPreg('/^city$/i','/^\d+$/i','/^(page([1-9]\d{0,5}))?$/i','EventCity');
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^(index)?$/i', '/^(page([1-9]\d{0,5}))?$/i', '/^$/i', 'EventIndex');
$this->AddEventPreg('/^ajax-search$/i', 'EventAjaxSearch');
$this->AddEventPreg('/^country$/i', '/^\d+$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventCountry');
$this->AddEventPreg('/^city$/i', '/^\d+$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventCity');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Поиск пользователей по логину
*/
protected function EventAjaxSearch() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Формируем фильтр
*/
$aFilter=array(
'activate' => 1
);
$sOrderWay=in_array(getRequestStr('order'),array('desc','asc')) ? getRequestStr('order') : 'desc';
$sOrderField=in_array(getRequestStr('sort_by'),array('user_rating','user_date_register','user_login','user_skill','user_profile_name')) ? getRequestStr('sort_by') : 'user_rating';
if (is_numeric(getRequestStr('pageNext')) and getRequestStr('pageNext')>0) {
$iPage=getRequestStr('pageNext');
} else {
$iPage=1;
}
/**
* Получаем из реквеста первые быквы для поиска пользователей по логину
*/
$sTitle=getRequest('sText');
if (is_string($sTitle) and mb_strlen($sTitle,'utf-8')) {
$sTitle=str_replace(array('_','%'),array('\_','\%'),$sTitle);
} else {
$sTitle='';
}
/**
* Как именно искать: совпадение в любой частилогина, или только начало или конец логина
*/
if ($sTitle) {
if (getRequest('isPrefix')) {
$sTitle.='%';
} elseif (getRequest('isPostfix')) {
$sTitle='%'.$sTitle;
} else {
$sTitle='%'.$sTitle.'%';
}
}
if ($sTitle) {
$aFilter['login']=$sTitle;
}
/**
* Пол
*/
if (in_array(getRequestStr('sex'),array('man','woman','other'))) {
$aFilter['profile_sex']=getRequestStr('sex');
}
/**
* Онлайн
* date_last
*/
if (getRequest('is_online')) {
$aFilter['date_last_more']=date('Y-m-d H:i:s',time()-Config::Get('module.user.time_onlive'));
}
/**
* Ищем пользователей
*/
$aResult=$this->User_GetUsersByFilter($aFilter,array($sOrderField=>$sOrderWay),$iPage,Config::Get('module.user.per_page'));
$bHideMore=$iPage*Config::Get('module.user.per_page')>=$aResult['count'];
/**
* Формируем ответ
*/
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aUsersList',$aResult['collection']);
$oViewer->Assign('oUserCurrent',$this->User_GetUserCurrent());
$oViewer->Assign('sUserListEmpty',$this->Lang_Get('search.alerts.empty'));
$oViewer->Assign('bUseMore', true);
$oViewer->Assign('bHideMore', $bHideMore);
$oViewer->Assign('iSearchCount', $aResult['count']);
$this->Viewer_AssignAjax('sText',$oViewer->Fetch("components/user/user-list.tpl"));
/**
* Для подгрузки
*/
$this->Viewer_AssignAjax('count_loaded',count($aResult['collection']));
$this->Viewer_AssignAjax('pageNext',count($aResult['collection'])>0 ? $iPage+1 : $iPage);
$this->Viewer_AssignAjax('bHideMore',$bHideMore);
}
/**
* Показывает юзеров по стране
*
*/
protected function EventCountry() {
$this->sMenuItemSelect='country';
/**
* Страна существует?
*/
if (!($oCountry=$this->Geo_GetCountryById($this->getParam(0)))) {
return parent::EventNotFound();
}
/**
* Получаем статистику
*/
$this->GetStats();
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(1,2) ? $this->GetParamEventMatch(1,2) : 1;
/**
* Получаем список вязей пользователей со страной
*/
$aResult=$this->Geo_GetTargets(array('country_id'=>$oCountry->getId(),'target_type'=>'user'),$iPage,Config::Get('module.user.per_page'));
$aUsersId=array();
foreach($aResult['collection'] as $oTarget) {
$aUsersId[]=$oTarget->getTargetId();
}
$aUsersCountry=$this->User_GetUsersAdditionalData($aUsersId);
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.user.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('people').$this->sCurrentEvent.'/'.$oCountry->getId());
/**
* Загружаем переменные в шаблон
*/
if ($aUsersCountry) {
$this->Viewer_Assign('aPaging',$aPaging);
}
$this->Viewer_Assign('oCountry',$oCountry);
$this->Viewer_Assign('aUsersCountry',$aUsersCountry);
}
/**
* Показывает юзеров по городу
*
*/
protected function EventCity() {
$this->sMenuItemSelect='city';
/**
* Город существует?
*/
if (!($oCity=$this->Geo_GetCityById($this->getParam(0)))) {
return parent::EventNotFound();
}
/**
* Получаем статистику
*/
$this->GetStats();
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(1,2) ? $this->GetParamEventMatch(1,2) : 1;
/**
* Получаем список юзеров
*/
$aResult=$this->Geo_GetTargets(array('city_id'=>$oCity->getId(),'target_type'=>'user'),$iPage,Config::Get('module.user.per_page'));
$aUsersId=array();
foreach($aResult['collection'] as $oTarget) {
$aUsersId[]=$oTarget->getTargetId();
}
$aUsersCity=$this->User_GetUsersAdditionalData($aUsersId);
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.user.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('people').$this->sCurrentEvent.'/'.$oCity->getId());
/**
* Загружаем переменные в шаблон
*/
if ($aUsersCity) {
$this->Viewer_Assign('aPaging',$aPaging);
}
$this->Viewer_Assign('oCity',$oCity);
$this->Viewer_Assign('aUsersCity',$aUsersCity);
}
/**
* Показываем юзеров
*
*/
protected function EventIndex() {
/**
* Получаем статистику
*/
$this->GetStats();
$aFilter=array(
'activate' => 1
);
/**
* Получаем список юзеров
*/
$aResult=$this->User_GetUsersByFilter($aFilter,array('user_rating'=>'desc'),1,Config::Get('module.user.per_page'));
/**
* Получаем алфавитный указатель на список пользователей
*/
$aPrefixUser=$this->User_GetGroupPrefixUser(1);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aUsers',$aResult['collection']);
$this->Viewer_Assign('iSearchCount', $aResult['count']);
$this->Viewer_Assign('aPrefixUser',$aPrefixUser);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Получение статистики
*
*/
protected function GetStats() {
/**
* Статистика кто, где и т.п.
*/
$aStat=$this->User_GetStatUsers();
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aStat',$aStat);
}
/**
* Поиск пользователей по логину
*/
protected function EventAjaxSearch()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Формируем фильтр
*/
$aFilter = array(
'activate' => 1
);
$sOrderWay = in_array(getRequestStr('order'), array('desc', 'asc')) ? getRequestStr('order') : 'desc';
$sOrderField = in_array(getRequestStr('sort_by'), array(
'user_rating',
'user_date_register',
'user_login',
'user_skill',
'user_profile_name'
)) ? getRequestStr('sort_by') : 'user_rating';
if (is_numeric(getRequestStr('pageNext')) and getRequestStr('pageNext') > 0) {
$iPage = getRequestStr('pageNext');
} else {
$iPage = 1;
}
/**
* Получаем из реквеста первые быквы для поиска пользователей по логину
*/
$sTitle = getRequest('sText');
if (is_string($sTitle) and mb_strlen($sTitle, 'utf-8')) {
$sTitle = str_replace(array('_', '%'), array('\_', '\%'), $sTitle);
} else {
$sTitle = '';
}
/**
* Как именно искать: совпадение в любой частилогина, или только начало или конец логина
*/
if ($sTitle) {
if (getRequest('isPrefix')) {
$sTitle .= '%';
} elseif (getRequest('isPostfix')) {
$sTitle = '%' . $sTitle;
} else {
$sTitle = '%' . $sTitle . '%';
}
}
if ($sTitle) {
$aFilter['login'] = $sTitle;
}
/**
* Пол
*/
if (in_array(getRequestStr('sex'), array('man', 'woman', 'other'))) {
$aFilter['profile_sex'] = getRequestStr('sex');
}
/**
* Онлайн
* date_last
*/
if (getRequest('is_online')) {
$aFilter['date_last_more'] = date('Y-m-d H:i:s', time() - Config::Get('module.user.time_onlive'));
}
/**
* Ищем пользователей
*/
$aResult = $this->User_GetUsersByFilter($aFilter, array($sOrderField => $sOrderWay), $iPage,
Config::Get('module.user.per_page'));
$bHideMore = $iPage * Config::Get('module.user.per_page') >= $aResult['count'];
/**
* Формируем ответ
*/
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('aUsersList', $aResult['collection']);
$oViewer->Assign('oUserCurrent', $this->User_GetUserCurrent());
$oViewer->Assign('sUserListEmpty', $this->Lang_Get('search.alerts.empty'));
$oViewer->Assign('bUseMore', true);
$oViewer->Assign('bHideMore', $bHideMore);
$oViewer->Assign('iSearchCount', $aResult['count']);
$this->Viewer_AssignAjax('sText', $oViewer->Fetch("components/user/user-list.tpl"));
/**
* Для подгрузки
*/
$this->Viewer_AssignAjax('count_loaded', count($aResult['collection']));
$this->Viewer_AssignAjax('pageNext', count($aResult['collection']) > 0 ? $iPage + 1 : $iPage);
$this->Viewer_AssignAjax('bHideMore', $bHideMore);
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown() {
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
}
/**
* Показывает юзеров по стране
*
*/
protected function EventCountry()
{
$this->sMenuItemSelect = 'country';
/**
* Страна существует?
*/
if (!($oCountry = $this->Geo_GetCountryById($this->getParam(0)))) {
return parent::EventNotFound();
}
/**
* Получаем статистику
*/
$this->GetStats();
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(1, 2) ? $this->GetParamEventMatch(1, 2) : 1;
/**
* Получаем список вязей пользователей со страной
*/
$aResult = $this->Geo_GetTargets(array('country_id' => $oCountry->getId(), 'target_type' => 'user'), $iPage,
Config::Get('module.user.per_page'));
$aUsersId = array();
foreach ($aResult['collection'] as $oTarget) {
$aUsersId[] = $oTarget->getTargetId();
}
$aUsersCountry = $this->User_GetUsersAdditionalData($aUsersId);
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.user.per_page'),
Config::Get('pagination.pages.count'),
Router::GetPath('people') . $this->sCurrentEvent . '/' . $oCountry->getId());
/**
* Загружаем переменные в шаблон
*/
if ($aUsersCountry) {
$this->Viewer_Assign('aPaging', $aPaging);
}
$this->Viewer_Assign('oCountry', $oCountry);
$this->Viewer_Assign('aUsersCountry', $aUsersCountry);
}
/**
* Показывает юзеров по городу
*
*/
protected function EventCity()
{
$this->sMenuItemSelect = 'city';
/**
* Город существует?
*/
if (!($oCity = $this->Geo_GetCityById($this->getParam(0)))) {
return parent::EventNotFound();
}
/**
* Получаем статистику
*/
$this->GetStats();
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(1, 2) ? $this->GetParamEventMatch(1, 2) : 1;
/**
* Получаем список юзеров
*/
$aResult = $this->Geo_GetTargets(array('city_id' => $oCity->getId(), 'target_type' => 'user'), $iPage,
Config::Get('module.user.per_page'));
$aUsersId = array();
foreach ($aResult['collection'] as $oTarget) {
$aUsersId[] = $oTarget->getTargetId();
}
$aUsersCity = $this->User_GetUsersAdditionalData($aUsersId);
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.user.per_page'),
Config::Get('pagination.pages.count'),
Router::GetPath('people') . $this->sCurrentEvent . '/' . $oCity->getId());
/**
* Загружаем переменные в шаблон
*/
if ($aUsersCity) {
$this->Viewer_Assign('aPaging', $aPaging);
}
$this->Viewer_Assign('oCity', $oCity);
$this->Viewer_Assign('aUsersCity', $aUsersCity);
}
/**
* Показываем юзеров
*
*/
protected function EventIndex()
{
/**
* Получаем статистику
*/
$this->GetStats();
$aFilter = array(
'activate' => 1
);
/**
* Получаем список юзеров
*/
$aResult = $this->User_GetUsersByFilter($aFilter, array('user_rating' => 'desc'), 1,
Config::Get('module.user.per_page'));
/**
* Получаем алфавитный указатель на список пользователей
*/
$aPrefixUser = $this->User_GetGroupPrefixUser(1);
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aUsers', $aResult['collection']);
$this->Viewer_Assign('iSearchCount', $aResult['count']);
$this->Viewer_Assign('aPrefixUser', $aPrefixUser);
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Получение статистики
*
*/
protected function GetStats()
{
/**
* Статистика кто, где и т.п.
*/
$aStat = $this->User_GetStatUsers();
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aStat', $aStat);
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown()
{
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect', $this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect', $this->sMenuItemSelect);
}
}

View file

@ -25,143 +25,156 @@
* @package application.actions
* @since 1.0
*/
class ActionPersonalBlog extends Action {
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect='blog';
/**
* Меню
*
* @var string
*/
protected $sMenuItemSelect='log';
/**
* Субменю
*
* @var string
*/
protected $sMenuSubItemSelect='good';
/**
* URL-префикс для навигации по топикам
*
* @var string
*/
protected $sNavTopicsSubUrl = '';
class ActionPersonalBlog extends Action
{
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect = 'blog';
/**
* Меню
*
* @var string
*/
protected $sMenuItemSelect = 'log';
/**
* Субменю
*
* @var string
*/
protected $sMenuSubItemSelect = 'good';
/**
* URL-префикс для навигации по топикам
*
* @var string
*/
protected $sNavTopicsSubUrl = '';
/**
* Инициализация
*
*/
public function Init() {
$this->SetDefaultEvent('good');
$this->sNavTopicsSubUrl = Router::GetPath('personal_blog');
}
/**
* Регистрируем необходимые евенты
*
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^good$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEvent('good','EventTopics');
$this->AddEventPreg('/^bad$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEventPreg('/^new$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEventPreg('/^newall$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEventPreg('/^discussed$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEventPreg('/^top$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
}
/**
* Инициализация
*
*/
public function Init()
{
$this->SetDefaultEvent('good');
$this->sNavTopicsSubUrl = Router::GetPath('personal_blog');
}
/**
* Регистрируем необходимые евенты
*
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^good$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEvent('good', 'EventTopics');
$this->AddEventPreg('/^bad$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEventPreg('/^new$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEventPreg('/^newall$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEventPreg('/^discussed$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEventPreg('/^top$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Показ топиков
*
*/
protected function EventTopics() {
$sPeriod=1; // по дефолту 1 день
if (in_array(getRequestStr('period'),array(1,7,30,'all'))) {
$sPeriod=getRequestStr('period');
}
$sShowType=$this->sCurrentEvent;
if (!in_array($sShowType,array('discussed','top'))) {
$sPeriod='all';
}
/**
* Меню
*/
$this->sMenuSubItemSelect=$sShowType=='newall' ? 'new' : $sShowType;
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
if ($iPage==1 and !getRequest('period')) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('personal_blog').$sShowType.'/');
}
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsPersonal($iPage,Config::Get('module.topic.per_page'),$sShowType,$sPeriod=='all' ? null : $sPeriod*60*60*24);
/**
* Если нет топиков за 1 день, то показываем за неделю (7)
*/
if (in_array($sShowType,array('discussed','top')) and !$aResult['count'] and $iPage==1 and !getRequest('period')) {
$sPeriod=7;
$aResult=$this->Topic_GetTopicsPersonal($iPage,Config::Get('module.topic.per_page'),$sShowType,$sPeriod=='all' ? null : $sPeriod*60*60*24);
}
$aTopics=$aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>$aTopics));
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('personal_blog').$sShowType,in_array($sShowType,array('discussed','top')) ? array('period'=>$sPeriod) : array());
/**
* Вызов хуков
*/
$this->Hook_Run('personal_show',array('sShowType'=>$sShowType));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('aPaging',$aPaging);
if (in_array($sShowType,array('discussed','top'))) {
$this->Viewer_Assign('sPeriodSelectCurrent',$sPeriod);
$this->Viewer_Assign('sPeriodSelectRoot',Router::GetPath('personal_blog').$sShowType.'/');
}
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* При завершении экшена загружаем в шаблон необходимые переменные
*
*/
public function EventShutdown() {
/**
* Подсчитываем новые топики
*/
$iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew();
$iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew();
$iCountTopicsNew=$iCountTopicsCollectiveNew+$iCountTopicsPersonalNew;
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsCollectiveNew',$iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew',$iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsNew',$iCountTopicsNew);
$this->Viewer_Assign('iCountTopicsSubNew',$iCountTopicsPersonalNew);
$this->Viewer_Assign('sNavTopicsSubUrl',$this->sNavTopicsSubUrl);
}
/**
* Показ топиков
*
*/
protected function EventTopics()
{
$sPeriod = 1; // по дефолту 1 день
if (in_array(getRequestStr('period'), array(1, 7, 30, 'all'))) {
$sPeriod = getRequestStr('period');
}
$sShowType = $this->sCurrentEvent;
if (!in_array($sShowType, array('discussed', 'top'))) {
$sPeriod = 'all';
}
/**
* Меню
*/
$this->sMenuSubItemSelect = $sShowType == 'newall' ? 'new' : $sShowType;
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
if ($iPage == 1 and !getRequest('period')) {
$this->Viewer_SetHtmlCanonical(Router::GetPath('personal_blog') . $sShowType . '/');
}
/**
* Получаем список топиков
*/
$aResult = $this->Topic_GetTopicsPersonal($iPage, Config::Get('module.topic.per_page'), $sShowType,
$sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
/**
* Если нет топиков за 1 день, то показываем за неделю (7)
*/
if (in_array($sShowType,
array('discussed', 'top')) and !$aResult['count'] and $iPage == 1 and !getRequest('period')
) {
$sPeriod = 7;
$aResult = $this->Topic_GetTopicsPersonal($iPage, Config::Get('module.topic.per_page'), $sShowType,
$sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
}
$aTopics = $aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => $aTopics));
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('personal_blog') . $sShowType,
in_array($sShowType, array('discussed', 'top')) ? array('period' => $sPeriod) : array());
/**
* Вызов хуков
*/
$this->Hook_Run('personal_show', array('sShowType' => $sShowType));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aTopics', $aTopics);
$this->Viewer_Assign('aPaging', $aPaging);
if (in_array($sShowType, array('discussed', 'top'))) {
$this->Viewer_Assign('sPeriodSelectCurrent', $sPeriod);
$this->Viewer_Assign('sPeriodSelectRoot', Router::GetPath('personal_blog') . $sShowType . '/');
}
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* При завершении экшена загружаем в шаблон необходимые переменные
*
*/
public function EventShutdown()
{
/**
* Подсчитываем новые топики
*/
$iCountTopicsCollectiveNew = $this->Topic_GetCountTopicsCollectiveNew();
$iCountTopicsPersonalNew = $this->Topic_GetCountTopicsPersonalNew();
$iCountTopicsNew = $iCountTopicsCollectiveNew + $iCountTopicsPersonalNew;
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('sMenuHeadItemSelect', $this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect', $this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect', $this->sMenuSubItemSelect);
$this->Viewer_Assign('iCountTopicsCollectiveNew', $iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew', $iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsNew', $iCountTopicsNew);
$this->Viewer_Assign('iCountTopicsSubNew', $iCountTopicsPersonalNew);
$this->Viewer_Assign('sNavTopicsSubUrl', $this->sNavTopicsSubUrl);
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,91 +25,99 @@
* @package application.actions
* @since 2.0
*/
class ActionProperty extends Action {
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent=null;
/**
* Инициализация
*/
public function Init() {
/**
* Достаём текущего пользователя
*/
$this->oUserCurrent=$this->User_GetUserCurrent();
}
/**
* Регистрируем евенты
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^download$/i','/^[\w]{10,32}$/i','/^$/i','EventDownloadFile');
}
class ActionProperty extends Action
{
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent = null;
/**
* Инициализация
*/
public function Init()
{
/**
* Достаём текущего пользователя
*/
$this->oUserCurrent = $this->User_GetUserCurrent();
}
/**
* Регистрируем евенты
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^download$/i', '/^[\w]{10,32}$/i', '/^$/i', 'EventDownloadFile');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Загрузка файла
*/
protected function EventDownloadFile() {
$sKey=$this->GetParam(0);
/**
* Выполняем проверки
*/
if (!$oValue=$this->Property_GetValueByValueVarchar($sKey)) {
return parent::EventNotFound();
}
if (!$oProperty=$oValue->getProperty()) {
return parent::EventNotFound();
}
if ($oProperty->getType()!=ModuleProperty::PROPERTY_TYPE_FILE) {
return parent::EventNotFound();
}
if (!$oTargetRel=$this->Property_GetTargetByType($oValue->getTargetType())) {
return parent::EventNotFound();
}
if ($oTargetRel->getState()!=ModuleProperty::TARGET_STATE_ACTIVE) {
return parent::EventNotFound();
}
/**
* Загрузка файла
*/
protected function EventDownloadFile()
{
$sKey = $this->GetParam(0);
/**
* Выполняем проверки
*/
if (!$oValue = $this->Property_GetValueByValueVarchar($sKey)) {
return parent::EventNotFound();
}
if (!$oProperty = $oValue->getProperty()) {
return parent::EventNotFound();
}
if ($oProperty->getType() != ModuleProperty::PROPERTY_TYPE_FILE) {
return parent::EventNotFound();
}
if (!$oTargetRel = $this->Property_GetTargetByType($oValue->getTargetType())) {
return parent::EventNotFound();
}
if ($oTargetRel->getState() != ModuleProperty::TARGET_STATE_ACTIVE) {
return parent::EventNotFound();
}
$bAllowDownload=false;
if (!$this->oUserCurrent) {
if ($oProperty->getParam('access_only_auth')) {
return Router::Action('error','403');
} else {
$bAllowDownload=true;
}
}
if (!$bAllowDownload) {
/**
* Проверяем доступ пользователя к объекту, которому принадлежит свойство
*/
if ($this->Property_CheckAllowTargetObject($oValue->getTargetType(),$oValue->getTargetId(),array('user'=>$this->oUserCurrent))) {
$bAllowDownload=true;
}
}
if ($bAllowDownload) {
/**
* Увеличиваем количество загрузок
*/
$aStats=$oValue->getDataOne('stats');
$aStats['count_download']=(isset($aStats['count_download']) ? $aStats['count_download'] : 0 ) +1;
$oValue->setDataOne('stats',$aStats);
$oValue->Update();
$oValueType=$oValue->getValueTypeObject();
if (!$oValueType->DownloadFile()) {
return parent::EventNotFound();
}
} else {
return Router::Action('error','403');
}
$bAllowDownload = false;
if (!$this->oUserCurrent) {
if ($oProperty->getParam('access_only_auth')) {
return Router::Action('error', '403');
} else {
$bAllowDownload = true;
}
}
if (!$bAllowDownload) {
/**
* Проверяем доступ пользователя к объекту, которому принадлежит свойство
*/
if ($this->Property_CheckAllowTargetObject($oValue->getTargetType(), $oValue->getTargetId(),
array('user' => $this->oUserCurrent))
) {
$bAllowDownload = true;
}
}
if ($bAllowDownload) {
/**
* Увеличиваем количество загрузок
*/
$aStats = $oValue->getDataOne('stats');
$aStats['count_download'] = (isset($aStats['count_download']) ? $aStats['count_download'] : 0) + 1;
$oValue->setDataOne('stats', $aStats);
$oValue->Update();
$oValueType = $oValue->getValueTypeObject();
if (!$oValueType->DownloadFile()) {
return parent::EventNotFound();
}
} else {
return Router::Action('error', '403');
}
$this->SetTemplate(false);
}
$this->SetTemplate(false);
}
}

View file

@ -25,366 +25,396 @@
* @package application.actions
* @since 1.0
*/
class ActionRegistration extends Action {
/**
* Инициализация
*
*/
public function Init() {
/**
* Проверяем аторизован ли юзер
*/
if ($this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.already_registered'),$this->Lang_Get('attention'));
return Router::Action('error');
}
/**
* Если включены инвайты то перенаправляем на страницу регистрации по инвайтам
*/
if (!$this->User_IsAuthorization() and Config::Get('general.reg.invite') and !in_array(Router::GetActionEvent(),array('invite','activate','reactivation','confirm')) and !$this->CheckInviteRegister()) {
return Router::Action('registration','invite');
}
$this->SetDefaultEvent('index');
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.registration.title'));
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventIndex');
$this->AddEvent('confirm','EventConfirm');
$this->AddEvent('activate','EventActivate');
$this->AddEvent('invite','EventInvite');
$this->AddEvent('reactivation','EventReactivation');
class ActionRegistration extends Action
{
/**
* Инициализация
*
*/
public function Init()
{
/**
* Проверяем аторизован ли юзер
*/
if ($this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.already_registered'),
$this->Lang_Get('attention'));
return Router::Action('error');
}
/**
* Если включены инвайты то перенаправляем на страницу регистрации по инвайтам
*/
if (!$this->User_IsAuthorization() and Config::Get('general.reg.invite') and !in_array(Router::GetActionEvent(),
array('invite', 'activate', 'reactivation', 'confirm')) and !$this->CheckInviteRegister()
) {
return Router::Action('registration', 'invite');
}
$this->SetDefaultEvent('index');
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.registration.title'));
}
$this->AddEvent('ajax-validate-fields','EventAjaxValidateFields');
$this->AddEvent('ajax-registration','EventAjaxRegistration');
$this->AddEvent('ajax-reactivation','EventAjaxReactivation');
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent()
{
$this->AddEvent('index', 'EventIndex');
$this->AddEvent('confirm', 'EventConfirm');
$this->AddEvent('activate', 'EventActivate');
$this->AddEvent('invite', 'EventInvite');
$this->AddEvent('reactivation', 'EventReactivation');
$this->AddEvent('ajax-validate-fields', 'EventAjaxValidateFields');
$this->AddEvent('ajax-registration', 'EventAjaxRegistration');
$this->AddEvent('ajax-reactivation', 'EventAjaxReactivation');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Ajax валидация форму регистрации
*/
protected function EventAjaxValidateFields() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Создаем объект пользователя и устанавливаем сценарий валидации
*/
$oUser=Engine::GetEntity('ModuleUser_EntityUser');
$oUser->_setValidateScenario('registration');
/**
* Пробегаем по переданным полям/значениям и валидируем их каждое в отдельности
*/
$aFields=getRequest('fields');
if (is_array($aFields)) {
foreach($aFields as $aField) {
if (isset($aField['field']) and isset($aField['value'])) {
$this->Hook_Run('registration_validate_field', array('aField'=>&$aField));
/**
* Ajax валидация форму регистрации
*/
protected function EventAjaxValidateFields()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Создаем объект пользователя и устанавливаем сценарий валидации
*/
$oUser = Engine::GetEntity('ModuleUser_EntityUser');
$oUser->_setValidateScenario('registration');
/**
* Пробегаем по переданным полям/значениям и валидируем их каждое в отдельности
*/
$aFields = getRequest('fields');
if (is_array($aFields)) {
foreach ($aFields as $aField) {
if (isset($aField['field']) and isset($aField['value'])) {
$this->Hook_Run('registration_validate_field', array('aField' => &$aField));
$sField=$aField['field'];
$sValue=$aField['value'];
/**
* Список полей для валидации
*/
switch($sField){
case 'login':
$oUser->setLogin($sValue);
break;
case 'mail':
$oUser->setMail($sValue);
break;
case 'captcha':
$oUser->setCaptcha($sValue);
break;
case 'password':
$oUser->setPassword($sValue);
break;
case 'password_confirm':
$oUser->setPasswordConfirm($sValue);
$oUser->setPassword(isset($aField['params']['password']) ? $aField['params']['password'] : null);
break;
default:
continue;
break;
}
/**
* Валидируем поле
*/
$oUser->_Validate(array($sField),false);
}
}
}
/**
* Возникли ошибки?
*/
if ($oUser->_hasValidateErrors()) {
/**
* Получаем ошибки
*/
$this->Viewer_AssignAjax('aErrors',$oUser->_getValidateErrors());
}
}
/**
* Обработка Ajax регистрации
*/
protected function EventAjaxRegistration() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Создаем объект пользователя и устанавливаем сценарий валидации
*/
$oUser=Engine::GetEntity('ModuleUser_EntityUser');
$oUser->_setValidateScenario('registration');
/**
* Заполняем поля (данные)
*/
$oUser->setLogin(getRequestStr('login'));
$oUser->setMail(getRequestStr('mail'));
$oUser->setPassword(getRequestStr('password'));
$oUser->setPasswordConfirm(getRequestStr('password_confirm'));
$oUser->setCaptcha(getRequestStr('captcha'));
$oUser->setDateRegister(date("Y-m-d H:i:s"));
$oUser->setIpRegister(func_getIp());
/**
* Если используется активация, то генерим код активации
*/
if (Config::Get('general.reg.activation')) {
$oUser->setActivate(0);
$oUser->setActivateKey(md5(func_generator().time()));
} else {
$oUser->setActivate(1);
$oUser->setActivateKey(null);
}
$this->Hook_Run('registration_validate_before', array('oUser'=>$oUser));
/**
* Запускаем валидацию
*/
if ($oUser->_Validate()) {
$this->Hook_Run('registration_validate_after', array('oUser'=>$oUser));
$oUser->setPassword(func_encrypt($oUser->getPassword()));
if ($this->User_Add($oUser)) {
$this->Hook_Run('registration_after', array('oUser'=>$oUser));
/**
* Убиваем каптчу
*/
unset($_SESSION['captcha_keystring_user_signup']);
/**
* Подписываем пользователя на дефолтные события в ленте активности
*/
$this->Stream_switchUserEventDefaultTypes($oUser->getId());
/**
* Если юзер зарегистрировался по приглашению то обновляем инвайт
*/
if (Config::Get('general.reg.invite') and $oInvite=$this->User_GetInviteByCode($this->GetInviteRegister())) {
$oInvite->setUserToId($oUser->getId());
$oInvite->setDateUsed(date("Y-m-d H:i:s"));
$oInvite->setUsed(1);
$this->User_UpdateInvite($oInvite);
}
/**
* Если стоит регистрация с активацией то проводим её
*/
if (Config::Get('general.reg.activation')) {
/**
* Отправляем на мыло письмо о подтверждении регистрации
*/
$this->Notify_SendRegistrationActivate($oUser,getRequestStr('password'));
$this->Viewer_AssignAjax('sUrlRedirect',Router::GetPath('registration').'confirm/');
} else {
$this->Notify_SendRegistration($oUser,getRequestStr('password'));
$oUser=$this->User_GetUserById($oUser->getId());
/**
* Сразу авторизуем
*/
$this->User_Authorization($oUser,false);
$this->DropInviteRegister();
/**
* Определяем URL для редиректа после авторизации
*/
$sUrl=Config::Get('module.user.redirect_after_registration');
if (getRequestStr('return-path')) {
$sUrl=getRequestStr('return-path');
}
$this->Viewer_AssignAjax('sUrlRedirect',$sUrl ? $sUrl : Router::GetPath('/'));
$this->Message_AddNoticeSingle($this->Lang_Get('auth.registration.notices.success'));
}
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return;
}
} else {
/**
* Получаем ошибки
*/
$this->Viewer_AssignAjax('aErrors',$oUser->_getValidateErrors());
}
}
/**
* Показывает страничку регистрации
* Просто вывод шаблона
*/
protected function EventIndex() {
$sField = $aField['field'];
$sValue = $aField['value'];
/**
* Список полей для валидации
*/
switch ($sField) {
case 'login':
$oUser->setLogin($sValue);
break;
case 'mail':
$oUser->setMail($sValue);
break;
case 'captcha':
$oUser->setCaptcha($sValue);
break;
case 'password':
$oUser->setPassword($sValue);
break;
case 'password_confirm':
$oUser->setPasswordConfirm($sValue);
$oUser->setPassword(isset($aField['params']['password']) ? $aField['params']['password'] : null);
break;
default:
continue;
break;
}
/**
* Валидируем поле
*/
$oUser->_Validate(array($sField), false);
}
}
}
/**
* Возникли ошибки?
*/
if ($oUser->_hasValidateErrors()) {
/**
* Получаем ошибки
*/
$this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
}
}
}
/**
* Обрабатывает активацию аккаунта
*/
protected function EventActivate() {
$bError=false;
/**
* Проверяет передан ли код активации
*/
$sActivateKey=$this->GetParam(0);
if (!func_check($sActivateKey,'md5')) {
$bError=true;
}
/**
* Проверяет верный ли код активации
*/
if (!($oUser=$this->User_GetUserByActivateKey($sActivateKey))) {
$bError=true;
}
/**
*
*/
if ($oUser and $oUser->getActivate()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_reactivate'),$this->Lang_Get('error'));
return Router::Action('error');
}
/**
* Если что то не то
*/
if ($bError) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_code'),$this->Lang_Get('error'));
return Router::Action('error');
}
/**
* Активируем
*/
$oUser->setActivate(1);
$oUser->setDateActivate(date("Y-m-d H:i:s"));
/**
* Сохраняем юзера
*/
if ($this->User_Update($oUser)) {
$this->DropInviteRegister();
$this->User_Authorization($oUser,false);
return;
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return Router::Action('error');
}
}
/**
* Повторный запрос активации
*/
protected function EventReactivation() {
if($this->User_GetUserCurrent()) {
Router::Location(Router::GetPath('/'));
}
/**
* Обработка Ajax регистрации
*/
protected function EventAjaxRegistration()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Создаем объект пользователя и устанавливаем сценарий валидации
*/
$oUser = Engine::GetEntity('ModuleUser_EntityUser');
$oUser->_setValidateScenario('registration');
/**
* Заполняем поля (данные)
*/
$oUser->setLogin(getRequestStr('login'));
$oUser->setMail(getRequestStr('mail'));
$oUser->setPassword(getRequestStr('password'));
$oUser->setPasswordConfirm(getRequestStr('password_confirm'));
$oUser->setCaptcha(getRequestStr('captcha'));
$oUser->setDateRegister(date("Y-m-d H:i:s"));
$oUser->setIpRegister(func_getIp());
/**
* Если используется активация, то генерим код активации
*/
if (Config::Get('general.reg.activation')) {
$oUser->setActivate(0);
$oUser->setActivateKey(md5(func_generator() . time()));
} else {
$oUser->setActivate(1);
$oUser->setActivateKey(null);
}
$this->Hook_Run('registration_validate_before', array('oUser' => $oUser));
/**
* Запускаем валидацию
*/
if ($oUser->_Validate()) {
$this->Hook_Run('registration_validate_after', array('oUser' => $oUser));
$oUser->setPassword(func_encrypt($oUser->getPassword()));
if ($this->User_Add($oUser)) {
$this->Hook_Run('registration_after', array('oUser' => $oUser));
/**
* Убиваем каптчу
*/
unset($_SESSION['captcha_keystring_user_signup']);
/**
* Подписываем пользователя на дефолтные события в ленте активности
*/
$this->Stream_switchUserEventDefaultTypes($oUser->getId());
/**
* Если юзер зарегистрировался по приглашению то обновляем инвайт
*/
if (Config::Get('general.reg.invite') and $oInvite = $this->User_GetInviteByCode($this->GetInviteRegister())) {
$oInvite->setUserToId($oUser->getId());
$oInvite->setDateUsed(date("Y-m-d H:i:s"));
$oInvite->setUsed(1);
$this->User_UpdateInvite($oInvite);
}
/**
* Если стоит регистрация с активацией то проводим её
*/
if (Config::Get('general.reg.activation')) {
/**
* Отправляем на мыло письмо о подтверждении регистрации
*/
$this->Notify_SendRegistrationActivate($oUser, getRequestStr('password'));
$this->Viewer_AssignAjax('sUrlRedirect', Router::GetPath('registration') . 'confirm/');
} else {
$this->Notify_SendRegistration($oUser, getRequestStr('password'));
$oUser = $this->User_GetUserById($oUser->getId());
/**
* Сразу авторизуем
*/
$this->User_Authorization($oUser, false);
$this->DropInviteRegister();
/**
* Определяем URL для редиректа после авторизации
*/
$sUrl = Config::Get('module.user.redirect_after_registration');
if (getRequestStr('return-path')) {
$sUrl = getRequestStr('return-path');
}
$this->Viewer_AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Router::GetPath('/'));
$this->Message_AddNoticeSingle($this->Lang_Get('auth.registration.notices.success'));
}
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return;
}
} else {
/**
* Получаем ошибки
*/
$this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
}
}
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.reactivation.title'));
}
/**
* Ajax повторной активации
*/
protected function EventAjaxReactivation() {
$this->Viewer_SetResponseAjax('json');
/**
* Показывает страничку регистрации
* Просто вывод шаблона
*/
protected function EventIndex()
{
if ((func_check(getRequestStr('mail'), 'mail') and $oUser = $this->User_GetUserByMail(getRequestStr('mail')))) {
if ($oUser->getActivate()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_reactivate'));
return;
} else {
$oUser->setActivateKey(md5(func_generator() . time()));
if ($this->User_Update($oUser)) {
$this->Message_AddNotice($this->Lang_Get('auth.reactivation.notices.success'));
$this->Notify_SendReactivationCode($oUser);
return;
}
}
}
}
$this->Message_AddErrorSingle($this->Lang_Get('auth.notices.error_bad_email'));
}
/**
* Обработка кода приглашения при включеном режиме инвайтов
*
*/
protected function EventInvite() {
if (!Config::Get('general.reg.invite')) {
return parent::EventNotFound();
}
/**
* Обработка отправки формы с кодом приглашения
*/
if (isPost('submit_invite')) {
/**
* проверяем код приглашения на валидность
*/
if ($this->CheckInviteRegister()) {
$sInviteId=$this->GetInviteRegister();
} else {
$sInviteId=getRequestStr('invite_code');
}
$oInvate=$this->User_GetInviteByCode($sInviteId);
if ($oInvate) {
if (!$this->CheckInviteRegister()) {
$this->Session_Set('invite_code',$oInvate->getCode());
}
return Router::Action('registration');
} else {
$this->Message_AddError($this->Lang_Get('auth.invite.alerts.error_code'),$this->Lang_Get('error'));
}
}
}
/**
* Пытается ли юзер зарегистрироваться с помощью кода приглашения
*
* @return bool
*/
protected function CheckInviteRegister() {
if ($this->Session_Get('invite_code')) {
return true;
}
return false;
}
/**
* Вожвращает код приглашения из сессии
*
* @return string
*/
protected function GetInviteRegister() {
return $this->Session_Get('invite_code');
}
/**
* Удаляет код приглашения из сессии
*/
protected function DropInviteRegister() {
if (Config::Get('general.reg.invite')) {
$this->Session_Drop('invite_code');
}
}
/**
* Просто выводит шаблон для подтверждения регистрации
*
*/
protected function EventConfirm() {
}
/**
* Обрабатывает активацию аккаунта
*/
protected function EventActivate()
{
$bError = false;
/**
* Проверяет передан ли код активации
*/
$sActivateKey = $this->GetParam(0);
if (!func_check($sActivateKey, 'md5')) {
$bError = true;
}
/**
* Проверяет верный ли код активации
*/
if (!($oUser = $this->User_GetUserByActivateKey($sActivateKey))) {
$bError = true;
}
/**
*
*/
if ($oUser and $oUser->getActivate()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_reactivate'),
$this->Lang_Get('error'));
return Router::Action('error');
}
/**
* Если что то не то
*/
if ($bError) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_code'),
$this->Lang_Get('error'));
return Router::Action('error');
}
/**
* Активируем
*/
$oUser->setActivate(1);
$oUser->setDateActivate(date("Y-m-d H:i:s"));
/**
* Сохраняем юзера
*/
if ($this->User_Update($oUser)) {
$this->DropInviteRegister();
$this->User_Authorization($oUser, false);
return;
} else {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return Router::Action('error');
}
}
/**
* Повторный запрос активации
*/
protected function EventReactivation()
{
if ($this->User_GetUserCurrent()) {
Router::Location(Router::GetPath('/'));
}
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.reactivation.title'));
}
/**
* Ajax повторной активации
*/
protected function EventAjaxReactivation()
{
$this->Viewer_SetResponseAjax('json');
if ((func_check(getRequestStr('mail'), 'mail') and $oUser = $this->User_GetUserByMail(getRequestStr('mail')))) {
if ($oUser->getActivate()) {
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_reactivate'));
return;
} else {
$oUser->setActivateKey(md5(func_generator() . time()));
if ($this->User_Update($oUser)) {
$this->Message_AddNotice($this->Lang_Get('auth.reactivation.notices.success'));
$this->Notify_SendReactivationCode($oUser);
return;
}
}
}
$this->Message_AddErrorSingle($this->Lang_Get('auth.notices.error_bad_email'));
}
/**
* Обработка кода приглашения при включеном режиме инвайтов
*
*/
protected function EventInvite()
{
if (!Config::Get('general.reg.invite')) {
return parent::EventNotFound();
}
/**
* Обработка отправки формы с кодом приглашения
*/
if (isPost('submit_invite')) {
/**
* проверяем код приглашения на валидность
*/
if ($this->CheckInviteRegister()) {
$sInviteId = $this->GetInviteRegister();
} else {
$sInviteId = getRequestStr('invite_code');
}
$oInvate = $this->User_GetInviteByCode($sInviteId);
if ($oInvate) {
if (!$this->CheckInviteRegister()) {
$this->Session_Set('invite_code', $oInvate->getCode());
}
return Router::Action('registration');
} else {
$this->Message_AddError($this->Lang_Get('auth.invite.alerts.error_code'), $this->Lang_Get('error'));
}
}
}
/**
* Пытается ли юзер зарегистрироваться с помощью кода приглашения
*
* @return bool
*/
protected function CheckInviteRegister()
{
if ($this->Session_Get('invite_code')) {
return true;
}
return false;
}
/**
* Вожвращает код приглашения из сессии
*
* @return string
*/
protected function GetInviteRegister()
{
return $this->Session_Get('invite_code');
}
/**
* Удаляет код приглашения из сессии
*/
protected function DropInviteRegister()
{
if (Config::Get('general.reg.invite')) {
$this->Session_Drop('invite_code');
}
}
/**
* Просто выводит шаблон для подтверждения регистрации
*
*/
protected function EventConfirm()
{
}
}

View file

@ -26,356 +26,383 @@
* @package application.actions
* @since 1.0
*/
class ActionRss extends Action {
/**
* Инициализация
*/
public function Init() {
$this->SetDefaultEvent('index');
Router::SetIsShowStats(false);
}
/**
* Указывает браузеру правильный content type в случае вывода RSS-ленты
*/
protected function InitRss() {
header('Content-Type: application/rss+xml; charset=utf-8');
}
/**
* Регистрация евентов
*/
protected function RegisterEvent() {
$this->AddEvent('index','RssGood');
$this->AddEvent('new','RssNew');
$this->AddEvent('allcomments','RssComments');
$this->AddEvent('comments','RssTopicComments');
$this->AddEvent('tag','RssTag');
$this->AddEvent('blog','RssColectiveBlog');
$this->AddEvent('personal_blog','RssPersonalBlog');
}
/**
* Вывод RSS интересных топиков
*/
protected function RssGood() {
/**
* Получаем топики
*/
$aResult=$this->Topic_GetTopicsGood(1,Config::Get('module.topic.per_page')*2,false);
$aTopics=$aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title']=Config::Get('view.name');
$aChannel['link']=Router::GetPath('/');
$aChannel['description']=Config::Get('view.name').' / RSS channel';
$aChannel['language']='ru';
$aChannel['managingEditor']=Config::Get('general.rss_editor_mail');
$aChannel['generator']=Config::Get('view.name');
/**
* Формируем записи RSS
*/
$topics=array();
foreach ($aTopics as $oTopic){
$item['title']=$oTopic->getTitle();
$item['guid']=$oTopic->getUrl();
$item['link']=$oTopic->getUrl();
$item['description']=$this->getTopicText($oTopic);
$item['pubDate']=$oTopic->getDateAdd();
$item['author']=$oTopic->getUser()->getLogin();
$item['category']=htmlspecialchars($oTopic->getTags());
$topics[]=$item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel',$aChannel);
$this->Viewer_Assign('aItems',$topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS новых топиков
*/
protected function RssNew() {
/**
* Получаем топики
*/
$aResult=$this->Topic_GetTopicsNew(1,Config::Get('module.topic.per_page')*2,false);
$aTopics=$aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title']=Config::Get('view.name');
$aChannel['link']=Router::GetPath('/');
$aChannel['description']=Router::GetPath('/').' / RSS channel';
$aChannel['language']='ru';
$aChannel['managingEditor']=Config::Get('general.rss_editor_mail');
$aChannel['generator']=Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics = array();
foreach ($aTopics as $oTopic){
$item['title']=$oTopic->getTitle();
$item['guid']=$oTopic->getUrl();
$item['link']=$oTopic->getUrl();
$item['description']=$this->getTopicText($oTopic);
$item['pubDate']=$oTopic->getDateAdd();
$item['author']=$oTopic->getUser()->getLogin();
$item['category']=htmlspecialchars($oTopic->getTags());
$topics[]=$item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel',$aChannel);
$this->Viewer_Assign('aItems',$topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS последних комментариев
*/
protected function RssComments() {
/**
* Получаем закрытые блоги, чтобы исключить их из выдачи
*/
$aCloseBlogs = $this->Blog_GetInaccessibleBlogsByUser();
/**
* Получаем комментарии
*/
$aResult=$this->Comment_GetCommentsAll('topic',1,Config::Get('module.comment.per_page')*2,array(),$aCloseBlogs);
$aComments=$aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title']=Config::Get('view.name');
$aChannel['link']=Router::GetPath('/');
$aChannel['description']=Router::GetPath('/').' / RSS channel';
$aChannel['language']='ru';
$aChannel['managingEditor']=Config::Get('general.rss_editor_mail');
$aChannel['generator']=Router::GetPath('/');
/**
* Формируем записи RSS
*/
$comments=array();
foreach ($aComments as $oComment){
$item['title']='Comments: '.$oComment->getTarget()->getTitle();
$item['guid']=$oComment->getTarget()->getUrl().'#comment'.$oComment->getId();
$item['link']=$oComment->getTarget()->getUrl().'#comment'.$oComment->getId();
$item['description']=$oComment->getText();
$item['pubDate']=$oComment->getDate();
$item['author']=$oComment->getUser()->getLogin();
$item['category']='comments';
$comments[]=$item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel',$aChannel);
$this->Viewer_Assign('aItems',$comments);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS комментариев конкретного топика
*/
protected function RssTopicComments() {
$sTopicId=$this->GetParam(0);
/**
* Топик существует?
*/
if (!($oTopic=$this->Topic_GetTopicById($sTopicId)) or !$oTopic->getPublish() or $oTopic->getBlog()->getType()=='close') {
return parent::EventNotFound();
}
/**
* Получаем комментарии
*/
$aResult=$this->Comment_GetCommentsByFilter(array('target_id'=>$oTopic->getId(),'target_type'=>'topic','delete'=>0),array('comment_id'=>'desc'),1,100);
$aComments=$aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title']=Config::Get('view.name');
$aChannel['link']=Router::GetPath('/');
$aChannel['description']=Router::GetPath('/').' / RSS channel';
$aChannel['language']='ru';
$aChannel['managingEditor']=Config::Get('general.rss_editor_mail');
$aChannel['generator']=Router::GetPath('/');
/**
* Формируем записи RSS
*/
$comments=array();
foreach ($aComments as $oComment){
$item['title']='Comments: '.$oTopic->getTitle();
$item['guid']=$oTopic->getUrl().'#comment'.$oComment->getId();
$item['link']=$oTopic->getUrl().'#comment'.$oComment->getId();
$item['description']=$oComment->getText();
$item['pubDate']=$oComment->getDate();
$item['author']=$oComment->getUser()->getLogin();
$item['category']='comments';
$comments[]=$item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel',$aChannel);
$this->Viewer_Assign('aItems',$comments);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS топиков по определенному тегу
*/
protected function RssTag() {
$sTag=urldecode($this->GetParam(0));
/**
* Получаем топики
*/
$aResult=$this->Topic_GetTopicsByTag($sTag,1,Config::Get('module.topic.per_page')*2,false);
$aTopics=$aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title']=Config::Get('view.name');
$aChannel['link']=Router::GetPath('/');
$aChannel['description']=Router::GetPath('/').' / RSS channel';
$aChannel['language']='ru';
$aChannel['managingEditor']=Config::Get('general.rss_editor_mail');
$aChannel['generator']=Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics=array();
foreach ($aTopics as $oTopic){
$item['title']=$oTopic->getTitle();
$item['guid']=$oTopic->getUrl();
$item['link']=$oTopic->getUrl();
$item['description']=$this->getTopicText($oTopic);
$item['pubDate']=$oTopic->getDateAdd();
$item['author']=$oTopic->getUser()->getLogin();
$item['category']=htmlspecialchars($oTopic->getTags());
$topics[]=$item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel',$aChannel);
$this->Viewer_Assign('aItems',$topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS топиков из коллективного блога
*/
protected function RssColectiveBlog() {
$sBlogUrl=$this->GetParam(0);
/**
* Если блог существует, то получаем записи
*/
if (!$sBlogUrl or !($oBlog=$this->Blog_GetBlogByUrl($sBlogUrl)) or $oBlog->getType()=="close") {
return parent::EventNotFound();
}else{
$aResult=$this->Topic_GetTopicsByBlog($oBlog,1,Config::Get('module.topic.per_page')*2,'good');
}
$aTopics=$aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title']=Config::Get('view.name');
$aChannel['link']=Router::GetPath('/');
$aChannel['description']=Router::GetPath('/').' / '.$oBlog->getTitle().' / RSS channel';
$aChannel['language']='ru';
$aChannel['managingEditor']=Config::Get('general.rss_editor_mail');
$aChannel['generator']=Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics=array();
foreach ($aTopics as $oTopic){
$item['title']=$oTopic->getTitle();
$item['guid']=$oTopic->getUrl();
$item['link']=$oTopic->getUrl();
$item['description']=$this->getTopicText($oTopic);
$item['pubDate']=$oTopic->getDateAdd();
$item['author']=$oTopic->getUser()->getLogin();
$item['category']=htmlspecialchars($oTopic->getTags());
$topics[]=$item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel',$aChannel);
$this->Viewer_Assign('aItems',$topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS топиков из персонального блога или всех персональных
*/
protected function RssPersonalBlog() {
$this->sUserLogin=$this->GetParam(0);
if(!$this->sUserLogin){
/**
* RSS-лента всех записей из персональных блогов
*/
$aResult=$this->Topic_GetTopicsPersonal(1,Config::Get('module.topic.per_page')*2);
}elseif(!$oUser=$this->User_GetUserByLogin($this->sUserLogin)){
return parent::EventNotFound();
}else{
/**
* RSS-лента записей персонального блога указанного пользователя
*/
$aResult=$this->Topic_GetTopicsPersonalByUser($oUser->getId(),1,1,Config::Get('module.topic.per_page')*2);
}
$aTopics=$aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title']=Config::Get('view.name');
$aChannel['link']=Router::GetPath('/');
$aChannel['description']=($this->sUserLogin)
? Router::GetPath('/').' / '.$oUser->getLogin().' / RSS channel'
: Router::GetPath('/').' / RSS channel';
$aChannel['language']='ru';
$aChannel['managingEditor']=Config::Get('general.rss_editor_mail');
$aChannel['generator']=Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics=array();
foreach ($aTopics as $oTopic){
$item['title']=$oTopic->getTitle();
$item['guid']=$oTopic->getUrl();
$item['link']=$oTopic->getUrl();
$item['description']=$this->getTopicText($oTopic);
$item['pubDate']=$oTopic->getDateAdd();
$item['author']=$oTopic->getUser()->getLogin();
$item['category']=htmlspecialchars($oTopic->getTags());
$topics[]=$item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel',$aChannel);
$this->Viewer_Assign('aItems',$topics);
$this->SetTemplateAction('index');
}
/**
* Формирует текст топика для RSS
*
*/
protected function getTopicText($oTopic) {
$sText=$oTopic->getTextShort();
if ($oTopic->getTextShort()!=$oTopic->getText()) {
$sText.="<br><a href=\"{$oTopic->getUrl()}#cut\" title=\"{$this->Lang_Get('topic.read_more')}\">";
if ($oTopic->getCutText()) {
$sText.=htmlspecialchars($oTopic->getCutText());
} else {
$sText.=$this->Lang_Get('topic.read_more');
}
$sText.="</a>";
}
return $sText;
}
class ActionRss extends Action
{
/**
* Инициализация
*/
public function Init()
{
$this->SetDefaultEvent('index');
Router::SetIsShowStats(false);
}
/**
* Указывает браузеру правильный content type в случае вывода RSS-ленты
*/
protected function InitRss()
{
header('Content-Type: application/rss+xml; charset=utf-8');
}
/**
* Регистрация евентов
*/
protected function RegisterEvent()
{
$this->AddEvent('index', 'RssGood');
$this->AddEvent('new', 'RssNew');
$this->AddEvent('allcomments', 'RssComments');
$this->AddEvent('comments', 'RssTopicComments');
$this->AddEvent('tag', 'RssTag');
$this->AddEvent('blog', 'RssColectiveBlog');
$this->AddEvent('personal_blog', 'RssPersonalBlog');
}
/**
* Вывод RSS интересных топиков
*/
protected function RssGood()
{
/**
* Получаем топики
*/
$aResult = $this->Topic_GetTopicsGood(1, Config::Get('module.topic.per_page') * 2, false);
$aTopics = $aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title'] = Config::Get('view.name');
$aChannel['link'] = Router::GetPath('/');
$aChannel['description'] = Config::Get('view.name') . ' / RSS channel';
$aChannel['language'] = 'ru';
$aChannel['managingEditor'] = Config::Get('general.rss_editor_mail');
$aChannel['generator'] = Config::Get('view.name');
/**
* Формируем записи RSS
*/
$topics = array();
foreach ($aTopics as $oTopic) {
$item['title'] = $oTopic->getTitle();
$item['guid'] = $oTopic->getUrl();
$item['link'] = $oTopic->getUrl();
$item['description'] = $this->getTopicText($oTopic);
$item['pubDate'] = $oTopic->getDateAdd();
$item['author'] = $oTopic->getUser()->getLogin();
$item['category'] = htmlspecialchars($oTopic->getTags());
$topics[] = $item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel', $aChannel);
$this->Viewer_Assign('aItems', $topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS новых топиков
*/
protected function RssNew()
{
/**
* Получаем топики
*/
$aResult = $this->Topic_GetTopicsNew(1, Config::Get('module.topic.per_page') * 2, false);
$aTopics = $aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title'] = Config::Get('view.name');
$aChannel['link'] = Router::GetPath('/');
$aChannel['description'] = Router::GetPath('/') . ' / RSS channel';
$aChannel['language'] = 'ru';
$aChannel['managingEditor'] = Config::Get('general.rss_editor_mail');
$aChannel['generator'] = Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics = array();
foreach ($aTopics as $oTopic) {
$item['title'] = $oTopic->getTitle();
$item['guid'] = $oTopic->getUrl();
$item['link'] = $oTopic->getUrl();
$item['description'] = $this->getTopicText($oTopic);
$item['pubDate'] = $oTopic->getDateAdd();
$item['author'] = $oTopic->getUser()->getLogin();
$item['category'] = htmlspecialchars($oTopic->getTags());
$topics[] = $item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel', $aChannel);
$this->Viewer_Assign('aItems', $topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS последних комментариев
*/
protected function RssComments()
{
/**
* Получаем закрытые блоги, чтобы исключить их из выдачи
*/
$aCloseBlogs = $this->Blog_GetInaccessibleBlogsByUser();
/**
* Получаем комментарии
*/
$aResult = $this->Comment_GetCommentsAll('topic', 1, Config::Get('module.comment.per_page') * 2, array(),
$aCloseBlogs);
$aComments = $aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title'] = Config::Get('view.name');
$aChannel['link'] = Router::GetPath('/');
$aChannel['description'] = Router::GetPath('/') . ' / RSS channel';
$aChannel['language'] = 'ru';
$aChannel['managingEditor'] = Config::Get('general.rss_editor_mail');
$aChannel['generator'] = Router::GetPath('/');
/**
* Формируем записи RSS
*/
$comments = array();
foreach ($aComments as $oComment) {
$item['title'] = 'Comments: ' . $oComment->getTarget()->getTitle();
$item['guid'] = $oComment->getTarget()->getUrl() . '#comment' . $oComment->getId();
$item['link'] = $oComment->getTarget()->getUrl() . '#comment' . $oComment->getId();
$item['description'] = $oComment->getText();
$item['pubDate'] = $oComment->getDate();
$item['author'] = $oComment->getUser()->getLogin();
$item['category'] = 'comments';
$comments[] = $item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel', $aChannel);
$this->Viewer_Assign('aItems', $comments);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS комментариев конкретного топика
*/
protected function RssTopicComments()
{
$sTopicId = $this->GetParam(0);
/**
* Топик существует?
*/
if (!($oTopic = $this->Topic_GetTopicById($sTopicId)) or !$oTopic->getPublish() or $oTopic->getBlog()->getType() == 'close') {
return parent::EventNotFound();
}
/**
* Получаем комментарии
*/
$aResult = $this->Comment_GetCommentsByFilter(array('target_id' => $oTopic->getId(),
'target_type' => 'topic',
'delete' => 0
), array('comment_id' => 'desc'), 1, 100);
$aComments = $aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title'] = Config::Get('view.name');
$aChannel['link'] = Router::GetPath('/');
$aChannel['description'] = Router::GetPath('/') . ' / RSS channel';
$aChannel['language'] = 'ru';
$aChannel['managingEditor'] = Config::Get('general.rss_editor_mail');
$aChannel['generator'] = Router::GetPath('/');
/**
* Формируем записи RSS
*/
$comments = array();
foreach ($aComments as $oComment) {
$item['title'] = 'Comments: ' . $oTopic->getTitle();
$item['guid'] = $oTopic->getUrl() . '#comment' . $oComment->getId();
$item['link'] = $oTopic->getUrl() . '#comment' . $oComment->getId();
$item['description'] = $oComment->getText();
$item['pubDate'] = $oComment->getDate();
$item['author'] = $oComment->getUser()->getLogin();
$item['category'] = 'comments';
$comments[] = $item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel', $aChannel);
$this->Viewer_Assign('aItems', $comments);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS топиков по определенному тегу
*/
protected function RssTag()
{
$sTag = urldecode($this->GetParam(0));
/**
* Получаем топики
*/
$aResult = $this->Topic_GetTopicsByTag($sTag, 1, Config::Get('module.topic.per_page') * 2, false);
$aTopics = $aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title'] = Config::Get('view.name');
$aChannel['link'] = Router::GetPath('/');
$aChannel['description'] = Router::GetPath('/') . ' / RSS channel';
$aChannel['language'] = 'ru';
$aChannel['managingEditor'] = Config::Get('general.rss_editor_mail');
$aChannel['generator'] = Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics = array();
foreach ($aTopics as $oTopic) {
$item['title'] = $oTopic->getTitle();
$item['guid'] = $oTopic->getUrl();
$item['link'] = $oTopic->getUrl();
$item['description'] = $this->getTopicText($oTopic);
$item['pubDate'] = $oTopic->getDateAdd();
$item['author'] = $oTopic->getUser()->getLogin();
$item['category'] = htmlspecialchars($oTopic->getTags());
$topics[] = $item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel', $aChannel);
$this->Viewer_Assign('aItems', $topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS топиков из коллективного блога
*/
protected function RssColectiveBlog()
{
$sBlogUrl = $this->GetParam(0);
/**
* Если блог существует, то получаем записи
*/
if (!$sBlogUrl or !($oBlog = $this->Blog_GetBlogByUrl($sBlogUrl)) or $oBlog->getType() == "close") {
return parent::EventNotFound();
} else {
$aResult = $this->Topic_GetTopicsByBlog($oBlog, 1, Config::Get('module.topic.per_page') * 2, 'good');
}
$aTopics = $aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title'] = Config::Get('view.name');
$aChannel['link'] = Router::GetPath('/');
$aChannel['description'] = Router::GetPath('/') . ' / ' . $oBlog->getTitle() . ' / RSS channel';
$aChannel['language'] = 'ru';
$aChannel['managingEditor'] = Config::Get('general.rss_editor_mail');
$aChannel['generator'] = Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics = array();
foreach ($aTopics as $oTopic) {
$item['title'] = $oTopic->getTitle();
$item['guid'] = $oTopic->getUrl();
$item['link'] = $oTopic->getUrl();
$item['description'] = $this->getTopicText($oTopic);
$item['pubDate'] = $oTopic->getDateAdd();
$item['author'] = $oTopic->getUser()->getLogin();
$item['category'] = htmlspecialchars($oTopic->getTags());
$topics[] = $item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel', $aChannel);
$this->Viewer_Assign('aItems', $topics);
$this->SetTemplateAction('index');
}
/**
* Вывод RSS топиков из персонального блога или всех персональных
*/
protected function RssPersonalBlog()
{
$this->sUserLogin = $this->GetParam(0);
if (!$this->sUserLogin) {
/**
* RSS-лента всех записей из персональных блогов
*/
$aResult = $this->Topic_GetTopicsPersonal(1, Config::Get('module.topic.per_page') * 2);
} elseif (!$oUser = $this->User_GetUserByLogin($this->sUserLogin)) {
return parent::EventNotFound();
} else {
/**
* RSS-лента записей персонального блога указанного пользователя
*/
$aResult = $this->Topic_GetTopicsPersonalByUser($oUser->getId(), 1, 1,
Config::Get('module.topic.per_page') * 2);
}
$aTopics = $aResult['collection'];
/**
* Формируем данные канала RSS
*/
$aChannel['title'] = Config::Get('view.name');
$aChannel['link'] = Router::GetPath('/');
$aChannel['description'] = ($this->sUserLogin)
? Router::GetPath('/') . ' / ' . $oUser->getLogin() . ' / RSS channel'
: Router::GetPath('/') . ' / RSS channel';
$aChannel['language'] = 'ru';
$aChannel['managingEditor'] = Config::Get('general.rss_editor_mail');
$aChannel['generator'] = Router::GetPath('/');
/**
* Формируем записи RSS
*/
$topics = array();
foreach ($aTopics as $oTopic) {
$item['title'] = $oTopic->getTitle();
$item['guid'] = $oTopic->getUrl();
$item['link'] = $oTopic->getUrl();
$item['description'] = $this->getTopicText($oTopic);
$item['pubDate'] = $oTopic->getDateAdd();
$item['author'] = $oTopic->getUser()->getLogin();
$item['category'] = htmlspecialchars($oTopic->getTags());
$topics[] = $item;
}
/**
* Формируем ответ
*/
$this->InitRss();
$this->Viewer_Assign('aChannel', $aChannel);
$this->Viewer_Assign('aItems', $topics);
$this->SetTemplateAction('index');
}
/**
* Формирует текст топика для RSS
*
*/
protected function getTopicText($oTopic)
{
$sText = $oTopic->getTextShort();
if ($oTopic->getTextShort() != $oTopic->getText()) {
$sText .= "<br><a href=\"{$oTopic->getUrl()}#cut\" title=\"{$this->Lang_Get('topic.read_more')}\">";
if ($oTopic->getCutText()) {
$sText .= htmlspecialchars($oTopic->getCutText());
} else {
$sText .= $this->Lang_Get('topic.read_more');
}
$sText .= "</a>";
}
return $sText;
}
}

View file

@ -25,136 +25,148 @@
* @package application.actions
* @since 1.0
*/
class ActionSearch extends Action {
class ActionSearch extends Action
{
public function Init() {
$this->SetDefaultEvent('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('search.search'));
}
public function Init()
{
$this->SetDefaultEvent('index');
$this->Viewer_AddHtmlTitle($this->Lang_Get('search.search'));
}
/**
* Регистрация евентов
*/
protected function RegisterEvent() {
$this->AddEvent('index','EventIndex');
$this->AddEventPreg('/^topics$/i','/^(page([1-9]\d{0,5}))?$/i','EventTopics');
$this->AddEventPreg('/^comments$/i','/^(page([1-9]\d{0,5}))?$/i','EventComments');
$this->AddEvent('opensearch','EventOpenSearch');
}
/**
* Регистрация евентов
*/
protected function RegisterEvent()
{
$this->AddEvent('index', 'EventIndex');
$this->AddEventPreg('/^topics$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTopics');
$this->AddEventPreg('/^comments$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventComments');
$this->AddEvent('opensearch', 'EventOpenSearch');
}
/**
* Главная страница поиска
*/
protected function EventIndex() {
$this->SetTemplateAction('index');
}
/**
* Обработка стандарта для браузеров Open Search
*/
function EventOpenSearch(){
Router::SetIsShowStats(false);
header('Content-type: text/xml; charset=utf-8');
}
/**
* Обработка поиска топиков
*/
protected function EventTopics() {
$this->SetTemplateAction('index');
$sSearchType=$this->sCurrentEvent;
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
/**
* Получаем список слов для поиска
*/
$aWords=$this->Search_GetWordsForSearch(getRequestStr('q'));
if (!$aWords) {
$this->Message_AddErrorSingle($this->Lang_Get('search.alerts.query_incorrect'));
return;
}
$sQuery=join(' ',$aWords);
/**
* Формируем регулярное выражение для поиска
*/
$sRegexp=$this->Search_GetRegexpForWords($aWords);
/**
* Выполняем поиск
*/
$aResult=$this->Search_SearchTopics($sRegexp,$iPage,Config::Get('module.topic.per_page'));
$aResultItems=$aResult['collection'];
/**
* Конфигурируем парсер jevix
*/
$this->Text_LoadJevixConfig('search');
/**
* Делаем сниппеты
*/
foreach($aResultItems AS $oItem){
/**
* Т.к. текст в сниппетах небольшой, то можно прогнать через парсер
*/
$oItem->setTextShort($this->Text_JevixParser($this->Search_BuildExcerpts($oItem->getText(),$aWords)));
}
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('search').$sSearchType,array('q'=>$sQuery));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aResultItems',$aResultItems);
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('sSearchType',$sSearchType);
$this->Viewer_Assign('sQuery',$sQuery);
$this->Viewer_Assign('aTypeCounts',array($sSearchType=>$aResult['count']));
}
/**
* Обработка поиска комментариев
*/
protected function EventComments() {
$this->SetTemplateAction('index');
$sSearchType=$this->sCurrentEvent;
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
/**
* Получаем список слов для поиска
*/
$aWords=$this->Search_GetWordsForSearch(getRequestStr('q'));
if (!$aWords) {
$this->Message_AddErrorSingle($this->Lang_Get('search.alerts.query_incorrect'));
return;
}
$sQuery=join(' ',$aWords);
/**
* Формируем регулярное выражение для поиска
*/
$sRegexp=$this->Search_GetRegexpForWords($aWords);
/**
* Выполняем поиск
*/
$aResult=$this->Search_SearchComments($sRegexp,$iPage,4,'topic');
$aResultItems=$aResult['collection'];
/**
* Конфигурируем парсер jevix
*/
$this->Text_LoadJevixConfig('search');
/**
* Делаем сниппеты
*/
foreach($aResultItems AS $oItem){
/**
* Т.к. текст в сниппетах небольшой, то можно прогнать через парсер
*/
$oItem->setText($this->Text_JevixParser($this->Search_BuildExcerpts($oItem->getText(),$aWords)));
}
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,4,Config::Get('pagination.pages.count'),Router::GetPath('search').$sSearchType,array('q'=>$sQuery));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aResultItems',$aResultItems);
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('sSearchType',$sSearchType);
$this->Viewer_Assign('sQuery',$sQuery);
$this->Viewer_Assign('aTypeCounts',array($sSearchType=>$aResult['count']));
}
/**
* Главная страница поиска
*/
protected function EventIndex()
{
$this->SetTemplateAction('index');
}
/**
* Обработка стандарта для браузеров Open Search
*/
function EventOpenSearch()
{
Router::SetIsShowStats(false);
header('Content-type: text/xml; charset=utf-8');
}
/**
* Обработка поиска топиков
*/
protected function EventTopics()
{
$this->SetTemplateAction('index');
$sSearchType = $this->sCurrentEvent;
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
/**
* Получаем список слов для поиска
*/
$aWords = $this->Search_GetWordsForSearch(getRequestStr('q'));
if (!$aWords) {
$this->Message_AddErrorSingle($this->Lang_Get('search.alerts.query_incorrect'));
return;
}
$sQuery = join(' ', $aWords);
/**
* Формируем регулярное выражение для поиска
*/
$sRegexp = $this->Search_GetRegexpForWords($aWords);
/**
* Выполняем поиск
*/
$aResult = $this->Search_SearchTopics($sRegexp, $iPage, Config::Get('module.topic.per_page'));
$aResultItems = $aResult['collection'];
/**
* Конфигурируем парсер jevix
*/
$this->Text_LoadJevixConfig('search');
/**
* Делаем сниппеты
*/
foreach ($aResultItems AS $oItem) {
/**
* Т.к. текст в сниппетах небольшой, то можно прогнать через парсер
*/
$oItem->setTextShort($this->Text_JevixParser($this->Search_BuildExcerpts($oItem->getText(), $aWords)));
}
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('search') . $sSearchType, array('q' => $sQuery));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aResultItems', $aResultItems);
$this->Viewer_Assign('aPaging', $aPaging);
$this->Viewer_Assign('sSearchType', $sSearchType);
$this->Viewer_Assign('sQuery', $sQuery);
$this->Viewer_Assign('aTypeCounts', array($sSearchType => $aResult['count']));
}
/**
* Обработка поиска комментариев
*/
protected function EventComments()
{
$this->SetTemplateAction('index');
$sSearchType = $this->sCurrentEvent;
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
/**
* Получаем список слов для поиска
*/
$aWords = $this->Search_GetWordsForSearch(getRequestStr('q'));
if (!$aWords) {
$this->Message_AddErrorSingle($this->Lang_Get('search.alerts.query_incorrect'));
return;
}
$sQuery = join(' ', $aWords);
/**
* Формируем регулярное выражение для поиска
*/
$sRegexp = $this->Search_GetRegexpForWords($aWords);
/**
* Выполняем поиск
*/
$aResult = $this->Search_SearchComments($sRegexp, $iPage, 4, 'topic');
$aResultItems = $aResult['collection'];
/**
* Конфигурируем парсер jevix
*/
$this->Text_LoadJevixConfig('search');
/**
* Делаем сниппеты
*/
foreach ($aResultItems AS $oItem) {
/**
* Т.к. текст в сниппетах небольшой, то можно прогнать через парсер
*/
$oItem->setText($this->Text_JevixParser($this->Search_BuildExcerpts($oItem->getText(), $aWords)));
}
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, 4, Config::Get('pagination.pages.count'),
Router::GetPath('search') . $sSearchType, array('q' => $sQuery));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aResultItems', $aResultItems);
$this->Viewer_Assign('aPaging', $aPaging);
$this->Viewer_Assign('sSearchType', $sSearchType);
$this->Viewer_Assign('sQuery', $sQuery);
$this->Viewer_Assign('aTypeCounts', array($sSearchType => $aResult['count']));
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,311 +25,329 @@
* @package application.actions
* @since 1.0
*/
class ActionStream extends Action {
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
class ActionStream extends Action
{
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
/**
* Какое меню активно
*
* @var string
*/
protected $sMenuItemSelect='user';
/**
* Какое меню активно
*
* @var string
*/
protected $sMenuItemSelect = 'user';
/**
* Инициализация
*/
public function Init() {
$this->oUserCurrent = $this->User_getUserCurrent();
/**
* Инициализация
*/
public function Init()
{
$this->oUserCurrent = $this->User_getUserCurrent();
// Личная лента доступна только для авторизованных, гостям показываем общую ленту
if ($this->oUserCurrent) {
$this->SetDefaultEvent('personal');
} else {
$this->SetDefaultEvent('all');
}
// Личная лента доступна только для авторизованных, гостям показываем общую ленту
if ($this->oUserCurrent) {
$this->SetDefaultEvent('personal');
} else {
$this->SetDefaultEvent('all');
}
$this->Viewer_Assign('sMenuHeadItemSelect', 'stream');
$this->Viewer_Assign('sMenuHeadItemSelect', 'stream');
/**
* Загружаем в шаблон JS текстовки
*/
$this->Lang_AddLangJs(array(
'activity.notices.error_already_subscribed', 'error'
));
}
/**
* Загружаем в шаблон JS текстовки
*/
$this->Lang_AddLangJs(array(
'activity.notices.error_already_subscribed',
'error'
));
}
/**
* Регистрация евентов
*/
protected function RegisterEvent() {
$this->AddEvent('personal', 'EventPersonal');
$this->AddEvent('all', 'EventAll');
/**
* Регистрация евентов
*/
protected function RegisterEvent()
{
$this->AddEvent('personal', 'EventPersonal');
$this->AddEvent('all', 'EventAll');
$this->AddEvent('subscribe', 'EventSubscribe'); // TODO: возможно нужно удалить
$this->AddEvent('ajaxadduser', 'EventAjaxAddUser');
$this->AddEvent('ajaxremoveuser', 'EventAjaxRemoveUser');
$this->AddEvent('switchEventType', 'EventSwitchEventType');
$this->AddEvent('subscribe', 'EventSubscribe'); // TODO: возможно нужно удалить
$this->AddEvent('ajaxadduser', 'EventAjaxAddUser');
$this->AddEvent('ajaxremoveuser', 'EventAjaxRemoveUser');
$this->AddEvent('switchEventType', 'EventSwitchEventType');
$this->AddEvent('get_more_all', 'EventGetMoreAll');
$this->AddEvent('get_more_personal', 'EventGetMore');
$this->AddEvent('get_more_user', 'EventGetMoreUser');
}
$this->AddEvent('get_more_all', 'EventGetMoreAll');
$this->AddEvent('get_more_personal', 'EventGetMore');
$this->AddEvent('get_more_user', 'EventGetMoreUser');
}
/**
* Персональная активность
*/
protected function EventPersonal() {
if ( ! $this->oUserCurrent ) {
return parent::EventNotFound();
}
/**
* Персональная активность
*/
protected function EventPersonal()
{
if (!$this->oUserCurrent) {
return parent::EventNotFound();
}
$this->Viewer_AddBlock('right', 'activitySettings');
$this->Viewer_AddBlock('right', 'activityUsers');
$this->Viewer_AddBlock('right', 'activitySettings');
$this->Viewer_AddBlock('right', 'activityUsers');
$this->Viewer_Assign('activityEvents', $this->Stream_Read());
$this->Viewer_Assign('activityEventsAllCount', $this->Stream_GetCountByReaderId( $this->oUserCurrent->getId()) );
}
$this->Viewer_Assign('activityEvents', $this->Stream_Read());
$this->Viewer_Assign('activityEventsAllCount', $this->Stream_GetCountByReaderId($this->oUserCurrent->getId()));
}
/**
* Общая активность
*/
protected function EventAll() {
$this->sMenuItemSelect = 'all';
/**
* Общая активность
*/
protected function EventAll()
{
$this->sMenuItemSelect = 'all';
$this->Viewer_Assign('activityEvents', $this->Stream_ReadAll());
$this->Viewer_Assign('activityEventsAllCount', $this->Stream_GetCountAll());
}
$this->Viewer_Assign('activityEvents', $this->Stream_ReadAll());
$this->Viewer_Assign('activityEventsAllCount', $this->Stream_GetCountAll());
}
/**
* Активаци/деактивация типа события
*/
protected function EventSwitchEventType() {
$this->Viewer_SetResponseAjax('json');
/**
* Активаци/деактивация типа события
*/
protected function EventSwitchEventType()
{
$this->Viewer_SetResponseAjax('json');
if ( ! $this->oUserCurrent ) {
return parent::EventNotFound();
}
if (!$this->oUserCurrent) {
return parent::EventNotFound();
}
if ( ! getRequest('type') ) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
}
if (!getRequest('type')) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
}
/**
* Активируем/деактивируем тип
*/
$this->Stream_switchUserEventType($this->oUserCurrent->getId(), getRequestStr('type'));
$this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('attention'));
}
/**
* Активируем/деактивируем тип
*/
$this->Stream_switchUserEventType($this->oUserCurrent->getId(), getRequestStr('type'));
$this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('attention'));
}
/**
* Подгрузка событий (замена постраничности)
*/
protected function EventGetMore() {
if ( ! $this->oUserCurrent ) {
return parent::EventNotFound();
}
/**
* Подгрузка событий (замена постраничности)
*/
protected function EventGetMore()
{
if (!$this->oUserCurrent) {
return parent::EventNotFound();
}
$this->GetMore(function($lastId) {
return $this->Stream_Read(null, $lastId);
});
}
$this->GetMore(function ($lastId) {
return $this->Stream_Read(null, $lastId);
});
}
/**
* Подгрузка событий для всего сайта
*/
protected function EventGetMoreAll() {
$this->GetMore(function($lastId) {
return $this->Stream_ReadAll(null, $lastId);
});
}
/**
* Подгрузка событий для всего сайта
*/
protected function EventGetMoreAll()
{
$this->GetMore(function ($lastId) {
return $this->Stream_ReadAll(null, $lastId);
});
}
/**
* Подгрузка событий для пользователя
*/
protected function EventGetMoreUser() {
$this->GetMore(function($lastId) {
if ( ! ( $oUser = $this->User_GetUserById(getRequestStr('target_id')) ) ) {
return false;
}
/**
* Подгрузка событий для пользователя
*/
protected function EventGetMoreUser()
{
$this->GetMore(function ($lastId) {
if (!($oUser = $this->User_GetUserById(getRequestStr('target_id')))) {
return false;
}
return $this->Stream_ReadByUserId($oUser->getId(), null, $lastId);
});
}
return $this->Stream_ReadByUserId($oUser->getId(), null, $lastId);
});
}
/**
* Общий метод подгрузки событий
*
* @param callback $getEvents Метод возвращающий список событий
*/
protected function GetMore( $getEvents ) {
$this->Viewer_SetResponseAjax('json');
/**
* Общий метод подгрузки событий
*
* @param callback $getEvents Метод возвращающий список событий
*/
protected function GetMore($getEvents)
{
$this->Viewer_SetResponseAjax('json');
// Необходимо передать последний просмотренный ID событий
$iLastId = getRequestStr('last_id');
// Необходимо передать последний просмотренный ID событий
$iLastId = getRequestStr('last_id');
if ( ! $iLastId ) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
if (!$iLastId) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
// Получаем события
$aEvents = $getEvents( $iLastId );
// Получаем события
$aEvents = $getEvents($iLastId);
if ( $aEvents === false ) {
return $this->EventErrorDebug();
}
if ($aEvents === false) {
return $this->EventErrorDebug();
}
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('events', $aEvents, true);
$oViewer->Assign('dateLast', getRequestStr('date_last'), true);
$oViewer->Assign('events', $aEvents, true);
$oViewer->Assign('dateLast', getRequestStr('date_last'), true);
if ( count($aEvents) ) {
$this->Viewer_AssignAjax('last_id', end($aEvents)->getId(), true);
}
if (count($aEvents)) {
$this->Viewer_AssignAjax('last_id', end($aEvents)->getId(), true);
}
$this->Viewer_AssignAjax('count_loaded', count($aEvents));
$this->Viewer_AssignAjax('html', $oViewer->Fetch('components/activity/event-list.tpl'));
}
$this->Viewer_AssignAjax('count_loaded', count($aEvents));
$this->Viewer_AssignAjax('html', $oViewer->Fetch('components/activity/event-list.tpl'));
}
/**
* Подписка на пользователя по ID
*
*/
protected function EventSubscribe() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Пользователь авторизован?
*/
if (!$this->oUserCurrent) {
return parent::EventNotFound();
}
/**
* Проверяем существование пользователя
*/
if (!$this->User_getUserById(getRequestStr('id'))) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
}
if ($this->oUserCurrent->getId() == getRequestStr('id')) {
$this->Message_AddError($this->Lang_Get('user_list_add.notices.error_self'),$this->Lang_Get('error'));
return;
}
/**
* Подписываем на пользователя
*/
$this->Stream_subscribeUser($this->oUserCurrent->getId(), getRequestStr('id'));
$this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
}
/**
* Подписка на пользователя по ID
*
*/
protected function EventSubscribe()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Пользователь авторизован?
*/
if (!$this->oUserCurrent) {
return parent::EventNotFound();
}
/**
* Проверяем существование пользователя
*/
if (!$this->User_getUserById(getRequestStr('id'))) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
}
if ($this->oUserCurrent->getId() == getRequestStr('id')) {
$this->Message_AddError($this->Lang_Get('user_list_add.notices.error_self'), $this->Lang_Get('error'));
return;
}
/**
* Подписываем на пользователя
*/
$this->Stream_subscribeUser($this->oUserCurrent->getId(), getRequestStr('id'));
$this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
}
/**
* Подписка на пользователя по логину
*/
protected function EventAjaxAddUser() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
$aUsers=getRequest('aUserList',null,'post');
/**
* Подписка на пользователя по логину
*/
protected function EventAjaxAddUser()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
$aUsers = getRequest('aUserList', null, 'post');
/**
* Валидация
*/
if ( ! is_array($aUsers) ) {
return $this->EventErrorDebug();
}
/**
* Валидация
*/
if (!is_array($aUsers)) {
return $this->EventErrorDebug();
}
/**
* Если пользователь не авторизирован, возвращаем ошибку
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
/**
* Если пользователь не авторизирован, возвращаем ошибку
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
return;
}
$aResult=array();
/**
* Обрабатываем добавление по каждому из переданных логинов
*/
foreach ($aUsers as $sUser) {
$sUser=trim($sUser);
if ($sUser=='') {
continue;
}
/**
* Если пользователь не найден или неактивен, возвращаем ошибку
*/
if ($oUser=$this->User_GetUserByLogin($sUser) and $oUser->getActivate()==1) {
$this->Stream_subscribeUser($this->oUserCurrent->getId(),$oUser->getId());
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('oUser', $oUser);
$oViewer->Assign('bUserListSmallShowActions', true);
$aResult = array();
/**
* Обрабатываем добавление по каждому из переданных логинов
*/
foreach ($aUsers as $sUser) {
$sUser = trim($sUser);
if ($sUser == '') {
continue;
}
/**
* Если пользователь не найден или неактивен, возвращаем ошибку
*/
if ($oUser = $this->User_GetUserByLogin($sUser) and $oUser->getActivate() == 1) {
$this->Stream_subscribeUser($this->oUserCurrent->getId(), $oUser->getId());
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('oUser', $oUser);
$oViewer->Assign('bUserListSmallShowActions', true);
$aResult[]=array(
'bStateError'=>false,
'sMsgTitle'=>$this->Lang_Get('attention'),
'sMsg'=>$this->Lang_Get('common.success.add',array('login'=>htmlspecialchars($sUser))),
'sUserId'=>$oUser->getId(),
'sUserLogin'=>htmlspecialchars($sUser),
'sUserWebPath'=>$oUser->getUserWebPath(),
'sUserAvatar48'=>$oUser->getProfileAvatarPath(48),
'sHtml'=>$oViewer->Fetch("components/user_list_small/user_list_small_item.tpl")
);
} else {
$aResult[]=array(
'bStateError'=>true,
'sMsgTitle'=>$this->Lang_Get('error'),
'sMsg'=>$this->Lang_Get('user.notices.not_found',array('login'=>htmlspecialchars($sUser))),
'sUserLogin'=>htmlspecialchars($sUser)
);
}
}
/**
* Передаем во вьевер массив с результатами обработки по каждому пользователю
*/
$this->Viewer_AssignAjax('aUserList',$aResult);
}
/**
* Отписка от пользователя
*/
protected function EventAjaxRemoveUser() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Пользователь авторизован?
*/
if (!$this->oUserCurrent) {
return $this->EventErrorDebug();
}
/**
* Пользователь с таким ID существует?
*/
if (!$this->User_GetUserById(getRequestStr('iUserId'))) {
return $this->EventErrorDebug();
}
/**
* Отписываем
*/
$this->Stream_unsubscribeUser($this->oUserCurrent->getId(), getRequestStr('iUserId'));
$this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
}
$aResult[] = array(
'bStateError' => false,
'sMsgTitle' => $this->Lang_Get('attention'),
'sMsg' => $this->Lang_Get('common.success.add',
array('login' => htmlspecialchars($sUser))),
'sUserId' => $oUser->getId(),
'sUserLogin' => htmlspecialchars($sUser),
'sUserWebPath' => $oUser->getUserWebPath(),
'sUserAvatar48' => $oUser->getProfileAvatarPath(48),
'sHtml' => $oViewer->Fetch("components/user_list_small/user_list_small_item.tpl")
);
} else {
$aResult[] = array(
'bStateError' => true,
'sMsgTitle' => $this->Lang_Get('error'),
'sMsg' => $this->Lang_Get('user.notices.not_found',
array('login' => htmlspecialchars($sUser))),
'sUserLogin' => htmlspecialchars($sUser)
);
}
}
/**
* Передаем во вьевер массив с результатами обработки по каждому пользователю
*/
$this->Viewer_AssignAjax('aUserList', $aResult);
}
/**
* Выполняется при завершении работы экшена
*/
public function EventShutdown() {
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
}
/**
* Отписка от пользователя
*/
protected function EventAjaxRemoveUser()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Пользователь авторизован?
*/
if (!$this->oUserCurrent) {
return $this->EventErrorDebug();
}
/**
* Пользователь с таким ID существует?
*/
if (!$this->User_GetUserById(getRequestStr('iUserId'))) {
return $this->EventErrorDebug();
}
/**
* Отписываем
*/
$this->Stream_unsubscribeUser($this->oUserCurrent->getId(), getRequestStr('iUserId'));
$this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
}
/**
* Выполняется при завершении работы экшена
*/
public function EventShutdown()
{
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuItemSelect', $this->sMenuItemSelect);
}
}

View file

@ -25,114 +25,123 @@
* @package application.actions
* @since 1.0
*/
class ActionSubscribe extends Action {
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent=null;
class ActionSubscribe extends Action
{
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent = null;
/**
* Инициализация
*
*/
public function Init() {
$this->oUserCurrent=$this->User_GetUserCurrent();
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^unsubscribe$/i','/^\w{32}$/i','EventUnsubscribe');
$this->AddEvent('ajax-subscribe-toggle','EventAjaxSubscribeToggle');
}
/**
* Инициализация
*
*/
public function Init()
{
$this->oUserCurrent = $this->User_GetUserCurrent();
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^unsubscribe$/i', '/^\w{32}$/i', 'EventUnsubscribe');
$this->AddEvent('ajax-subscribe-toggle', 'EventAjaxSubscribeToggle');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Отписка от подписки
*/
protected function EventUnsubscribe() {
/**
* Получаем подписку по ключу
*/
if ($oSubscribe=$this->Subscribe_GetSubscribeByKey($this->getParam(0)) and $oSubscribe->getStatus()==1) {
/**
* Отписываем пользователя
*/
$oSubscribe->setStatus(0);
$oSubscribe->setDateRemove(date("Y-m-d H:i:s"));
$this->Subscribe_UpdateSubscribe($oSubscribe);
/**
* Отписка от подписки
*/
protected function EventUnsubscribe()
{
/**
* Получаем подписку по ключу
*/
if ($oSubscribe = $this->Subscribe_GetSubscribeByKey($this->getParam(0)) and $oSubscribe->getStatus() == 1) {
/**
* Отписываем пользователя
*/
$oSubscribe->setStatus(0);
$oSubscribe->setDateRemove(date("Y-m-d H:i:s"));
$this->Subscribe_UpdateSubscribe($oSubscribe);
$this->Message_AddNotice($this->Lang_Get('common.success.save'),null,true);
}
/**
* Получаем URL для редиректа
*/
if ((!$sUrl=$this->Subscribe_GetUrlTarget($oSubscribe->getTargetType(),$oSubscribe->getTargetId()))) {
$sUrl=Router::GetPath('index');
}
Router::Location($sUrl);
}
/**
* Изменение состояния подписки
*/
protected function EventAjaxSubscribeToggle() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Получаем емайл подписки и проверяем его на валидность
*/
$sMail=getRequestStr('mail');
if ($this->oUserCurrent) {
$sMail=$this->oUserCurrent->getMail();
}
if (!func_check($sMail,'mail')) {
$this->Message_AddError($this->Lang_Get('field.email.notices.error'),$this->Lang_Get('error'));
return ;
}
/**
* Получаем тип объекта подписки
*/
$sTargetType=getRequestStr('target_type');
if (!$this->Subscribe_IsAllowTargetType($sTargetType)) {
return $this->EventErrorDebug();
}
$sTargetId=getRequestStr('target_id') ? getRequestStr('target_id') : null;
$iValue=getRequest('value') ? 1 : 0;
$this->Message_AddNotice($this->Lang_Get('common.success.save'), null, true);
}
/**
* Получаем URL для редиректа
*/
if ((!$sUrl = $this->Subscribe_GetUrlTarget($oSubscribe->getTargetType(), $oSubscribe->getTargetId()))) {
$sUrl = Router::GetPath('index');
}
Router::Location($sUrl);
}
$oSubscribe=null;
/**
* Есть ли доступ к подписке гостям?
*/
if (!$this->oUserCurrent and !$this->Subscribe_IsAllowTargetForGuest($sTargetType)) {
$this->Message_AddError($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return ;
}
/**
* Проверка объекта подписки
*/
if (!$this->Subscribe_CheckTarget($sTargetType,$sTargetId,$iValue)) {
return $this->EventErrorDebug();
}
/**
* Если подписка еще не существовала, то создаем её
*/
if ($oSubscribe=$this->Subscribe_AddSubscribeSimple($sTargetType,$sTargetId,$sMail,$this->oUserCurrent ? $this->oUserCurrent->getId() : null)) {
$oSubscribe->setStatus($iValue);
$this->Subscribe_UpdateSubscribe($oSubscribe);
$this->Message_AddNotice($this->Lang_Get('common.success.save'),$this->Lang_Get('attention'));
return ;
}
return $this->EventErrorDebug();
}
/**
* Изменение состояния подписки
*/
protected function EventAjaxSubscribeToggle()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Получаем емайл подписки и проверяем его на валидность
*/
$sMail = getRequestStr('mail');
if ($this->oUserCurrent) {
$sMail = $this->oUserCurrent->getMail();
}
if (!func_check($sMail, 'mail')) {
$this->Message_AddError($this->Lang_Get('field.email.notices.error'), $this->Lang_Get('error'));
return;
}
/**
* Получаем тип объекта подписки
*/
$sTargetType = getRequestStr('target_type');
if (!$this->Subscribe_IsAllowTargetType($sTargetType)) {
return $this->EventErrorDebug();
}
$sTargetId = getRequestStr('target_id') ? getRequestStr('target_id') : null;
$iValue = getRequest('value') ? 1 : 0;
$oSubscribe = null;
/**
* Есть ли доступ к подписке гостям?
*/
if (!$this->oUserCurrent and !$this->Subscribe_IsAllowTargetForGuest($sTargetType)) {
$this->Message_AddError($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
return;
}
/**
* Проверка объекта подписки
*/
if (!$this->Subscribe_CheckTarget($sTargetType, $sTargetId, $iValue)) {
return $this->EventErrorDebug();
}
/**
* Если подписка еще не существовала, то создаем её
*/
if ($oSubscribe = $this->Subscribe_AddSubscribeSimple($sTargetType, $sTargetId, $sMail,
$this->oUserCurrent ? $this->oUserCurrent->getId() : null)
) {
$oSubscribe->setStatus($iValue);
$this->Subscribe_UpdateSubscribe($oSubscribe);
$this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('attention'));
return;
}
return $this->EventErrorDebug();
}
}

View file

@ -25,87 +25,95 @@
* @package application.actions
* @since 1.0
*/
class ActionTag extends Action {
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect='blog';
class ActionTag extends Action
{
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect = 'blog';
/**
* Инициализация
*
*/
public function Init() {
}
/**
* Регистрация евентов
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^.+$/i','/^(page([1-9]\d{0,5}))?$/i','EventTags');
}
/**
* Инициализация
*
*/
public function Init()
{
}
/**
* Регистрация евентов
*/
protected function RegisterEvent()
{
$this->AddEventPreg('/^.+$/i', '/^(page([1-9]\d{0,5}))?$/i', 'EventTags');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Отображение топиков
*
*/
protected function EventTags() {
/**
* Получаем тег из УРЛа
*/
$sTag=$this->sCurrentEvent;
/**
* Передан ли номер страницы
*/
$iPage=$this->GetParamEventMatch(0,2) ? $this->GetParamEventMatch(0,2) : 1;
/**
* Получаем список топиков
*/
$aResult=$this->Topic_GetTopicsByTag($sTag,$iPage,Config::Get('module.topic.per_page'));
$aTopics=$aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>$aTopics));
/**
* Формируем постраничность
*/
$aPaging=$this->Viewer_MakePaging($aResult['count'],$iPage,Config::Get('module.topic.per_page'),Config::Get('pagination.pages.count'),Router::GetPath('tag').htmlspecialchars($sTag));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging',$aPaging);
$this->Viewer_Assign('aTopics',$aTopics);
$this->Viewer_Assign('sTag',$sTag);
$this->Viewer_AddHtmlTitle($this->Lang_Get('tag_title'));
$this->Viewer_AddHtmlTitle($sTag);
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss').'tag/'.$sTag.'/',$sTag);
/**
* Если не удалось найти топиков, то ыставляем 404 заголовок
*/
if (!count($aTopics)) {
header("HTTP/1.1 404 Not Found");
}
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown() {
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
}
/**
* Отображение топиков
*
*/
protected function EventTags()
{
/**
* Получаем тег из УРЛа
*/
$sTag = $this->sCurrentEvent;
/**
* Передан ли номер страницы
*/
$iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
/**
* Получаем список топиков
*/
$aResult = $this->Topic_GetTopicsByTag($sTag, $iPage, Config::Get('module.topic.per_page'));
$aTopics = $aResult['collection'];
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => $aTopics));
/**
* Формируем постраничность
*/
$aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'),
Config::Get('pagination.pages.count'), Router::GetPath('tag') . htmlspecialchars($sTag));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aPaging', $aPaging);
$this->Viewer_Assign('aTopics', $aTopics);
$this->Viewer_Assign('sTag', $sTag);
$this->Viewer_AddHtmlTitle($this->Lang_Get('tag_title'));
$this->Viewer_AddHtmlTitle($sTag);
$this->Viewer_SetHtmlRssAlternate(Router::GetPath('rss') . 'tag/' . $sTag . '/', $sTag);
/**
* Если не удалось найти топиков, то ыставляем 404 заголовок
*/
if (!count($aTopics)) {
header("HTTP/1.1 404 Not Found");
}
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('index');
}
/**
* Выполняется при завершении работы экшена
*
*/
public function EventShutdown()
{
/**
* Загружаем в шаблон необходимые переменные
*/
$this->Viewer_Assign('sMenuHeadItemSelect', $this->sMenuHeadItemSelect);
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,271 +25,291 @@
* @package application.actions
* @since 1.0
*/
class ActionUserfeed extends Action {
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
class ActionUserfeed extends Action
{
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
/**
* Инициализация
*
*/
public function Init() {
/**
* Доступ только у авторизованных пользователей
*/
$this->oUserCurrent = $this->User_getUserCurrent();
if (!$this->oUserCurrent) {
parent::EventNotFound();
}
$this->SetDefaultEvent('index');
/**
* Инициализация
*
*/
public function Init()
{
/**
* Доступ только у авторизованных пользователей
*/
$this->oUserCurrent = $this->User_getUserCurrent();
if (!$this->oUserCurrent) {
parent::EventNotFound();
}
$this->SetDefaultEvent('index');
$this->Viewer_Assign('sMenuItemSelect', 'feed');
}
/**
* Регистрация евентов
*
*/
protected function RegisterEvent() {
$this->AddEvent('index', 'EventIndex');
$this->AddEvent('subscribe', 'EventSubscribe');
$this->AddEvent('ajaxadduser', 'EventAjaxAddUser');
$this->AddEvent('unsubscribe', 'EventUnSubscribe');
$this->AddEvent('get_more', 'EventGetMore');
}
/**
* Выводит ленту контента(топики) для пользователя
*
*/
protected function EventIndex() {
// Получаем топики
$aTopics = $this->Userfeed_read($this->oUserCurrent->getId());
$this->Viewer_Assign('sMenuItemSelect', 'feed');
}
// Вызов хуков
$this->Hook_Run('topics_list_show', array('aTopics' => $aTopics));
/**
* Регистрация евентов
*
*/
protected function RegisterEvent()
{
$this->AddEvent('index', 'EventIndex');
$this->AddEvent('subscribe', 'EventSubscribe');
$this->AddEvent('ajaxadduser', 'EventAjaxAddUser');
$this->AddEvent('unsubscribe', 'EventUnSubscribe');
$this->AddEvent('get_more', 'EventGetMore');
}
$this->Viewer_Assign('feedTopics', $aTopics);
// TODO: Добавить метод возвращающий общее кол-во топиков в ленте (нужно для нормальной работы блока подгрузки)
$this->Viewer_Assign('feedTopicsAllCount', 0);
/**
* Выводит ленту контента(топики) для пользователя
*
*/
protected function EventIndex()
{
// Получаем топики
$aTopics = $this->Userfeed_read($this->oUserCurrent->getId());
$this->SetTemplateAction('list');
}
/**
* Подгрузка ленты топиков (замена постраничности)
*
*/
protected function EventGetMore() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Проверяем последний просмотренный ID топика
*/
$iFromId = getRequestStr('last_id');
if (!$iFromId) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
/**
* Получаем топики
*/
$aTopics = $this->Userfeed_read($this->oUserCurrent->getId(), null, $iFromId);
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show',array('aTopics'=>$aTopics));
/**
* Загружаем данные в ajax ответ
*/
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('topics', $aTopics, true);
$this->Viewer_AssignAjax('html', $oViewer->Fetch('components/topic/topic-list.tpl'));
$this->Viewer_AssignAjax('count_loaded', count($aTopics));
// Вызов хуков
$this->Hook_Run('topics_list_show', array('aTopics' => $aTopics));
if (count($aTopics)) {
$this->Viewer_AssignAjax('last_id', end($aTopics)->getId());
}
}
/**
* Подписка на контент блога или пользователя
*
*/
protected function EventSubscribe() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Проверяем наличие ID блога или пользователя
*/
if (!getRequest('id')) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
}
$sType = getRequestStr('type');
$iType = null;
/**
* Определяем тип подписки
*/
switch($sType) {
case 'blogs':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG;
/**
* Проверяем существование блога
*/
if (!$this->Blog_GetBlogById(getRequestStr('id'))) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
break;
case 'users':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER;
/**
* Проверяем существование пользователя
*/
if (!$this->User_GetUserById(getRequestStr('id'))) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if ($this->oUserCurrent->getId() == getRequestStr('id')) {
$this->Message_AddError($this->Lang_Get('user_list_add.notices.error_self'),$this->Lang_Get('error'));
return;
}
break;
default:
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
/**
* Подписываем
*/
$this->Userfeed_subscribeUser($this->oUserCurrent->getId(), $iType, getRequestStr('id'));
$this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('attention'));
}
/**
* Подписка на пользвователя по логину
*
*/
protected function EventAjaxAddUser() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
$aUsers=getRequest('aUserList',null,'post');
/**
* Валидация
*/
if ( ! is_array($aUsers) ) {
return $this->EventErrorDebug();
}
/**
* Если пользователь не авторизирован, возвращаем ошибку
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
return;
}
$this->Viewer_Assign('feedTopics', $aTopics);
// TODO: Добавить метод возвращающий общее кол-во топиков в ленте (нужно для нормальной работы блока подгрузки)
$this->Viewer_Assign('feedTopicsAllCount', 0);
$aResult=array();
/**
* Обрабатываем добавление по каждому из переданных логинов
*/
foreach ($aUsers as $sUser) {
$sUser=trim($sUser);
if ($sUser=='') {
continue;
}
/**
* Если пользователь не найден или неактивен, возвращаем ошибку
*/
if ($oUser=$this->User_GetUserByLogin($sUser) and $oUser->getActivate()==1) {
$this->Userfeed_subscribeUser($this->oUserCurrent->getId(), ModuleUserfeed::SUBSCRIBE_TYPE_USER, $oUser->getId());
$this->SetTemplateAction('list');
}
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('oUser', $oUser);
$oViewer->Assign('bUserListSmallShowActions', true);
/**
* Подгрузка ленты топиков (замена постраничности)
*
*/
protected function EventGetMore()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Проверяем последний просмотренный ID топика
*/
$iFromId = getRequestStr('last_id');
if (!$iFromId) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
/**
* Получаем топики
*/
$aTopics = $this->Userfeed_read($this->oUserCurrent->getId(), null, $iFromId);
/**
* Вызов хуков
*/
$this->Hook_Run('topics_list_show', array('aTopics' => $aTopics));
/**
* Загружаем данные в ajax ответ
*/
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('topics', $aTopics, true);
$this->Viewer_AssignAjax('html', $oViewer->Fetch('components/topic/topic-list.tpl'));
$this->Viewer_AssignAjax('count_loaded', count($aTopics));
$aResult[]=array(
'bStateError'=>false,
'sMsgTitle'=>$this->Lang_Get('attention'),
'sMsg'=>$this->Lang_Get('common.success.add',array('login'=>htmlspecialchars($sUser))),
'sUserId'=>$oUser->getId(),
'sUserLogin'=>htmlspecialchars($sUser),
'sUserWebPath'=>$oUser->getUserWebPath(),
'sUserAvatar48'=>$oUser->getProfileAvatarPath(48),
'sHtml'=>$oViewer->Fetch("components/user_list_small/user_list_small_item.tpl")
);
} else {
$aResult[]=array(
'bStateError'=>true,
'sMsgTitle'=>$this->Lang_Get('error'),
'sMsg'=>$this->Lang_Get('user.notices.not_found',array('login'=>htmlspecialchars($sUser))),
'sUserLogin'=>htmlspecialchars($sUser)
);
}
}
/**
* Передаем во вьевер массив с результатами обработки по каждому пользователю
*/
$this->Viewer_AssignAjax('aUserList',$aResult);
}
/**
* Отписка от блога или пользователя
*
*/
protected function EventUnsubscribe() {
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
$sId=getRequestStr('id');
if (count($aTopics)) {
$this->Viewer_AssignAjax('last_id', end($aTopics)->getId());
}
}
$sType = getRequestStr('type');
$iType = null;
/**
* Определяем от чего отписываемся
*/
switch($sType) {
case 'blogs':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG;
break;
case 'users':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER;
$sId=getRequestStr('iUserId');
break;
default:
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
if (!$sId) {
$this->Message_AddError($this->Lang_Get('system_error'),$this->Lang_Get('error'));
return;
}
/**
* Отписываем пользователя
*/
$this->Userfeed_unsubscribeUser($this->oUserCurrent->getId(), $iType, $sId);
$this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('attention'));
}
/**
* При завершении экшена загружаем в шаблон необходимые переменные
*
*/
public function EventShutdown() {
/**
* Подсчитываем новые топики
*/
$iCountTopicsCollectiveNew=$this->Topic_GetCountTopicsCollectiveNew();
$iCountTopicsPersonalNew=$this->Topic_GetCountTopicsPersonalNew();
$iCountTopicsNew=$iCountTopicsCollectiveNew+$iCountTopicsPersonalNew;
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('iCountTopicsCollectiveNew',$iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew',$iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsNew',$iCountTopicsNew);
}
/**
* Подписка на контент блога или пользователя
*
*/
protected function EventSubscribe()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
/**
* Проверяем наличие ID блога или пользователя
*/
if (!getRequest('id')) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
}
$sType = getRequestStr('type');
$iType = null;
/**
* Определяем тип подписки
*/
switch ($sType) {
case 'blogs':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG;
/**
* Проверяем существование блога
*/
if (!$this->Blog_GetBlogById(getRequestStr('id'))) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
break;
case 'users':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER;
/**
* Проверяем существование пользователя
*/
if (!$this->User_GetUserById(getRequestStr('id'))) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
if ($this->oUserCurrent->getId() == getRequestStr('id')) {
$this->Message_AddError($this->Lang_Get('user_list_add.notices.error_self'),
$this->Lang_Get('error'));
return;
}
break;
default:
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
/**
* Подписываем
*/
$this->Userfeed_subscribeUser($this->oUserCurrent->getId(), $iType, getRequestStr('id'));
$this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('attention'));
}
/**
* Подписка на пользвователя по логину
*
*/
protected function EventAjaxAddUser()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
$aUsers = getRequest('aUserList', null, 'post');
/**
* Валидация
*/
if (!is_array($aUsers)) {
return $this->EventErrorDebug();
}
/**
* Если пользователь не авторизирован, возвращаем ошибку
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
return;
}
$aResult = array();
/**
* Обрабатываем добавление по каждому из переданных логинов
*/
foreach ($aUsers as $sUser) {
$sUser = trim($sUser);
if ($sUser == '') {
continue;
}
/**
* Если пользователь не найден или неактивен, возвращаем ошибку
*/
if ($oUser = $this->User_GetUserByLogin($sUser) and $oUser->getActivate() == 1) {
$this->Userfeed_subscribeUser($this->oUserCurrent->getId(), ModuleUserfeed::SUBSCRIBE_TYPE_USER,
$oUser->getId());
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('oUser', $oUser);
$oViewer->Assign('bUserListSmallShowActions', true);
$aResult[] = array(
'bStateError' => false,
'sMsgTitle' => $this->Lang_Get('attention'),
'sMsg' => $this->Lang_Get('common.success.add',
array('login' => htmlspecialchars($sUser))),
'sUserId' => $oUser->getId(),
'sUserLogin' => htmlspecialchars($sUser),
'sUserWebPath' => $oUser->getUserWebPath(),
'sUserAvatar48' => $oUser->getProfileAvatarPath(48),
'sHtml' => $oViewer->Fetch("components/user_list_small/user_list_small_item.tpl")
);
} else {
$aResult[] = array(
'bStateError' => true,
'sMsgTitle' => $this->Lang_Get('error'),
'sMsg' => $this->Lang_Get('user.notices.not_found',
array('login' => htmlspecialchars($sUser))),
'sUserLogin' => htmlspecialchars($sUser)
);
}
}
/**
* Передаем во вьевер массив с результатами обработки по каждому пользователю
*/
$this->Viewer_AssignAjax('aUserList', $aResult);
}
/**
* Отписка от блога или пользователя
*
*/
protected function EventUnsubscribe()
{
/**
* Устанавливаем формат Ajax ответа
*/
$this->Viewer_SetResponseAjax('json');
$sId = getRequestStr('id');
$sType = getRequestStr('type');
$iType = null;
/**
* Определяем от чего отписываемся
*/
switch ($sType) {
case 'blogs':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG;
break;
case 'users':
$iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER;
$sId = getRequestStr('iUserId');
break;
default:
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
if (!$sId) {
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
return;
}
/**
* Отписываем пользователя
*/
$this->Userfeed_unsubscribeUser($this->oUserCurrent->getId(), $iType, $sId);
$this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('attention'));
}
/**
* При завершении экшена загружаем в шаблон необходимые переменные
*
*/
public function EventShutdown()
{
/**
* Подсчитываем новые топики
*/
$iCountTopicsCollectiveNew = $this->Topic_GetCountTopicsCollectiveNew();
$iCountTopicsPersonalNew = $this->Topic_GetCountTopicsPersonalNew();
$iCountTopicsNew = $iCountTopicsCollectiveNew + $iCountTopicsPersonalNew;
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('iCountTopicsCollectiveNew', $iCountTopicsCollectiveNew);
$this->Viewer_Assign('iCountTopicsPersonalNew', $iCountTopicsPersonalNew);
$this->Viewer_Assign('iCountTopicsNew', $iCountTopicsNew);
}
}

View file

@ -25,17 +25,19 @@
* @package application.blocks
* @since 1.0
*/
class BlockActivitySettings extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
$this->Viewer_Assign('types', $this->Stream_getEventTypes());
$this->Viewer_Assign('typesActive', $this->Stream_getTypesList($oUserCurrent->getId()));
}
}
class BlockActivitySettings extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
$this->Viewer_Assign('types', $this->Stream_getEventTypes());
$this->Viewer_Assign('typesActive', $this->Stream_getTypesList($oUserCurrent->getId()));
}
}
}

View file

@ -25,16 +25,18 @@
* @package application.blocks
* @since 1.0
*/
class BlockActivityUsers extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
$this->Viewer_Assign('users', $this->Stream_getUserSubscribes($oUserCurrent->getId()));
}
}
class BlockActivityUsers extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
$this->Viewer_Assign('users', $this->Stream_getUserSubscribes($oUserCurrent->getId()));
}
}
}

View file

@ -25,15 +25,17 @@
* @package application.blocks
* @since 2.0
*/
class BlockBlogNav extends Block {
/**
* Запуск обработки
*/
public function Exec() {
if (!Config::Get('module.blog.category_allow')) {
return;
}
$aCategories=$this->Blog_GetCategoriesTree();
$this->Viewer_Assign("aNavigatorBlogCategories",$aCategories);
}
class BlockBlogNav extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
if (!Config::Get('module.blog.category_allow')) {
return;
}
$aCategories = $this->Blog_GetCategoriesTree();
$this->Viewer_Assign("aNavigatorBlogCategories", $aCategories);
}
}

View file

@ -25,23 +25,25 @@
* @package application.blocks
* @since 1.0
*/
class BlockBlogs extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Получаем список блогов
*/
if ($aResult=$this->Blog_GetBlogsRating(1,Config::Get('block.blogs.row'))) {
$aBlogs=$aResult['collection'];
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aBlogs',$aBlogs);
/**
* Формируем результат в виде шаблона и возвращаем
*/
$sTextResult=$oViewer->Fetch("blocks/block.blogs_top.tpl");
$this->Viewer_Assign('sBlogsTop',$sTextResult);
}
}
class BlockBlogs extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Получаем список блогов
*/
if ($aResult = $this->Blog_GetBlogsRating(1, Config::Get('block.blogs.row'))) {
$aBlogs = $aResult['collection'];
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('aBlogs', $aBlogs);
/**
* Формируем результат в виде шаблона и возвращаем
*/
$sTextResult = $oViewer->Fetch("blocks/block.blogs_top.tpl");
$this->Viewer_Assign('sBlogsTop', $sTextResult);
}
}
}

View file

@ -25,17 +25,19 @@
* @package application.blocks
* @since 2.0
*/
class BlockBlogsSearch extends Block {
/**
* Запуск обработки
*/
public function Exec() {
if (!Config::Get('module.blog.category_allow')) {
return;
}
$aCategories=$this->Blog_GetCategoriesTree();
$aBlogsAll=$this->Blog_GetBlogsByFilter(array('exclude_type' => 'personal'),array(),1,1,array());
$this->Viewer_Assign("aBlogCategories",$aCategories);
$this->Viewer_Assign("iCountBlogsAll",$aBlogsAll['count']);
}
class BlockBlogsSearch extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
if (!Config::Get('module.blog.category_allow')) {
return;
}
$aCategories = $this->Blog_GetCategoriesTree();
$aBlogsAll = $this->Blog_GetBlogsByFilter(array('exclude_type' => 'personal'), array(), 1, 1, array());
$this->Viewer_Assign("aBlogCategories", $aCategories);
$this->Viewer_Assign("iCountBlogsAll", $aBlogsAll['count']);
}
}

View file

@ -25,43 +25,46 @@
* @package application.blocks
* @since 2.0
*/
class BlockCategoryUpdate extends Block {
/**
* Запуск обработки
*/
public function Exec() {
$sEntity = $this->GetParam('entity');
$oTarget = $this->GetParam('target');
$sTargetType = $this->GetParam('target_type');
class BlockCategoryUpdate extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
$sEntity = $this->GetParam('entity');
$oTarget = $this->GetParam('target');
$sTargetType = $this->GetParam('target_type');
if (!$oTarget) {
$oTarget=Engine::GetEntity($sEntity);
}
if (!$oTarget) {
$oTarget = Engine::GetEntity($sEntity);
}
$aBehaviors=$oTarget->GetBehaviors();
foreach($aBehaviors as $oBehavior) {
if ($oBehavior instanceof ModuleCategory_BehaviorEntity) {
/**
* Если в параметрах был тип, то переопределяем значение. Это необходимо для корректной работы, когда тип динамический.
*/
if ($sTargetType) {
$oBehavior->setParam('target_type',$sTargetType);
}
/**
* Нужное нам поведение - получаем список текущих категорий
*/
$this->Viewer_Assign('categoriesSelected', $oBehavior->getCategories(), true);
/**
* Загружаем параметры
*/
$aParams=$oBehavior->getParams();
$this->Viewer_Assign('params', $aParams, true);
/**
* Загружаем список доступных категорий
*/
$this->Viewer_Assign('categories', $this->Category_GetCategoriesTreeByTargetType($oBehavior->getCategoryTargetType()), true);
break;
}
}
}
$aBehaviors = $oTarget->GetBehaviors();
foreach ($aBehaviors as $oBehavior) {
if ($oBehavior instanceof ModuleCategory_BehaviorEntity) {
/**
* Если в параметрах был тип, то переопределяем значение. Это необходимо для корректной работы, когда тип динамический.
*/
if ($sTargetType) {
$oBehavior->setParam('target_type', $sTargetType);
}
/**
* Нужное нам поведение - получаем список текущих категорий
*/
$this->Viewer_Assign('categoriesSelected', $oBehavior->getCategories(), true);
/**
* Загружаем параметры
*/
$aParams = $oBehavior->getParams();
$this->Viewer_Assign('params', $aParams, true);
/**
* Загружаем список доступных категорий
*/
$this->Viewer_Assign('categories',
$this->Category_GetCategoriesTreeByTargetType($oBehavior->getCategoryTargetType()), true);
break;
}
}
}
}

View file

@ -25,31 +25,33 @@
* @package application.blocks
* @since 2.0
*/
class BlockPollFormItems extends Block {
/**
* Запуск обработки
*/
public function Exec() {
$sTargetType=$this->GetParam('target_type');
$sTargetId=$this->GetParam('target_id');
$sTargetTmp=empty($_COOKIE['poll_target_tmp_'.$sTargetType]) ? $this->GetParam('target_tmp') : $_COOKIE['poll_target_tmp_'.$sTargetType];
class BlockPollFormItems extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
$sTargetType = $this->GetParam('target_type');
$sTargetId = $this->GetParam('target_id');
$sTargetTmp = empty($_COOKIE['poll_target_tmp_' . $sTargetType]) ? $this->GetParam('target_tmp') : $_COOKIE['poll_target_tmp_' . $sTargetType];
$aFilter=array('target_type'=>$sTargetType,'#order'=>array('id'=>'asc'));
if ($sTargetId) {
$sTargetTmp=null;
if (!$this->Poll_CheckTarget($sTargetType,$sTargetId)) {
return false;
}
$aFilter['target_id']=$sTargetId;
} else {
$sTargetId=null;
if (!$sTargetTmp or !$this->Poll_IsAllowTargetType($sTargetType)) {
return false;
}
$aFilter['target_tmp']=$sTargetTmp;
}
$aPollItems=$this->Poll_GetPollItemsByFilter($aFilter);
$aFilter = array('target_type' => $sTargetType, '#order' => array('id' => 'asc'));
if ($sTargetId) {
$sTargetTmp = null;
if (!$this->Poll_CheckTarget($sTargetType, $sTargetId)) {
return false;
}
$aFilter['target_id'] = $sTargetId;
} else {
$sTargetId = null;
if (!$sTargetTmp or !$this->Poll_IsAllowTargetType($sTargetType)) {
return false;
}
$aFilter['target_tmp'] = $sTargetTmp;
}
$aPollItems = $this->Poll_GetPollItemsByFilter($aFilter);
$this->Viewer_Assign('aPollItems',$aPollItems);
}
$this->Viewer_Assign('aPollItems', $aPollItems);
}
}

View file

@ -25,35 +25,38 @@
* @package application.blocks
* @since 2.0
*/
class BlockPropertyUpdate extends Block {
/**
* Запуск обработки
*/
public function Exec() {
$sEntity = $this->GetParam('entity');
$oTarget = $this->GetParam('target');
$sTargetType = $this->GetParam('target_type');
class BlockPropertyUpdate extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
$sEntity = $this->GetParam('entity');
$oTarget = $this->GetParam('target');
$sTargetType = $this->GetParam('target_type');
if (!$oTarget) {
$oTarget=Engine::GetEntity($sEntity);
}
if (!$oTarget) {
$oTarget = Engine::GetEntity($sEntity);
}
$aBehaviors=$oTarget->GetBehaviors();
foreach($aBehaviors as $oBehavior) {
/**
* Определяем нужное нам поведение
*/
if ($oBehavior instanceof ModuleProperty_BehaviorEntity) {
/**
* Если в параметрах был тип, то переопределяем значение. Это необходимо для корректной работы, когда тип динамический.
*/
if ($sTargetType) {
$oBehavior->setParam('target_type',$sTargetType);
}
$aProperties = $this->Property_GetPropertiesForUpdate($oBehavior->getPropertyTargetType(),$oTarget->getId());
$this->Viewer_Assign('aProperties',$aProperties);
break;
}
}
}
$aBehaviors = $oTarget->GetBehaviors();
foreach ($aBehaviors as $oBehavior) {
/**
* Определяем нужное нам поведение
*/
if ($oBehavior instanceof ModuleProperty_BehaviorEntity) {
/**
* Если в параметрах был тип, то переопределяем значение. Это необходимо для корректной работы, когда тип динамический.
*/
if ($sTargetType) {
$oBehavior->setParam('target_type', $sTargetType);
}
$aProperties = $this->Property_GetPropertiesForUpdate($oBehavior->getPropertyTargetType(),
$oTarget->getId());
$this->Viewer_Assign('aProperties', $aProperties);
break;
}
}
}
}

View file

@ -25,22 +25,24 @@
* @package application.blocks
* @since 1.0
*/
class BlockStream extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Получаем комментарии
*/
if ($aComments=$this->Comment_GetCommentsOnline('topic',Config::Get('block.stream.row'))) {
$oViewer=$this->Viewer_GetLocalViewer();
$oViewer->Assign('aComments',$aComments);
/**
* Формируем результат в виде шаблона и возвращаем
*/
$sTextResult=$oViewer->Fetch("blocks/block.stream_comment.tpl");
$this->Viewer_Assign('sStreamComments',$sTextResult);
}
}
class BlockStream extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Получаем комментарии
*/
if ($aComments = $this->Comment_GetCommentsOnline('topic', Config::Get('block.stream.row'))) {
$oViewer = $this->Viewer_GetLocalViewer();
$oViewer->Assign('aComments', $aComments);
/**
* Формируем результат в виде шаблона и возвращаем
*/
$sTextResult = $oViewer->Fetch("blocks/block.stream_comment.tpl");
$this->Viewer_Assign('sStreamComments', $sTextResult);
}
}
}

View file

@ -25,40 +25,43 @@
* @package application.blocks
* @since 1.0
*/
class BlockTags extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Получаем список тегов
*/
$aTags=$this->Topic_GetOpenTopicTags(Config::Get('block.tags.tags_count'));
/**
* Расчитываем логарифмическое облако тегов
*/
if ($aTags) {
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aTags",$aTags);
}
/**
* Теги пользователя
*/
if ($oUserCurrent=$this->User_getUserCurrent()) {
$aTags=$this->Topic_GetOpenTopicTags(Config::Get('block.tags.personal_tags_count'), $oUserCurrent->getId());
/**
* Расчитываем логарифмическое облако тегов
*/
if ($aTags) {
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aTagsUser",$aTags);
}
}
}
class BlockTags extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Получаем список тегов
*/
$aTags = $this->Topic_GetOpenTopicTags(Config::Get('block.tags.tags_count'));
/**
* Расчитываем логарифмическое облако тегов
*/
if ($aTags) {
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aTags", $aTags);
}
/**
* Теги пользователя
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
$aTags = $this->Topic_GetOpenTopicTags(Config::Get('block.tags.personal_tags_count'),
$oUserCurrent->getId());
/**
* Расчитываем логарифмическое облако тегов
*/
if ($aTags) {
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aTagsUser", $aTags);
}
}
}
}

View file

@ -25,22 +25,24 @@
* @package application.blocks
* @since 1.0
*/
class BlockTagsCity extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Получаем города
*/
$aCities=$this->Geo_GetGroupCitiesByTargetType('user',20);
/**
* Формируем облако тегов
*/
$this->Tools_MakeCloud($aCities);
/**
* Выводим в шаблон
*/
$this->Viewer_Assign("aCityList",$aCities);
}
class BlockTagsCity extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Получаем города
*/
$aCities = $this->Geo_GetGroupCitiesByTargetType('user', 20);
/**
* Формируем облако тегов
*/
$this->Tools_MakeCloud($aCities);
/**
* Выводим в шаблон
*/
$this->Viewer_Assign("aCityList", $aCities);
}
}

View file

@ -25,22 +25,24 @@
* @package application.blocks
* @since 1.0
*/
class BlockTagsCountry extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Получаем страны
*/
$aCountries=$this->Geo_GetGroupCountriesByTargetType('user',20);
/**
* Формируем облако тегов
*/
$this->Tools_MakeCloud($aCountries);
/**
* Выводим в шаблон
*/
$this->Viewer_Assign("aCountryList",$aCountries);
}
class BlockTagsCountry extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Получаем страны
*/
$aCountries = $this->Geo_GetGroupCountriesByTargetType('user', 20);
/**
* Формируем облако тегов
*/
$this->Tools_MakeCloud($aCountries);
/**
* Выводим в шаблон
*/
$this->Viewer_Assign("aCountryList", $aCountries);
}
}

View file

@ -25,43 +25,45 @@
* @package application.blocks
* @since 1.0
*/
class BlockTagsFavouriteTopic extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
if (!($oUser=$this->getParam('user'))) {
$oUser=$oUserCurrent;
}
/**
* Получаем список тегов
*/
$aTags=$this->Favourite_GetGroupTags($oUser->getId(),'topic',null,70);
/**
* Расчитываем логарифмическое облако тегов
*/
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aFavouriteTopicTags",$aTags);
/**
* Получаем список тегов пользователя
*/
$aTags=$this->Favourite_GetGroupTags($oUser->getId(),'topic',true,70);
/**
* Расчитываем логарифмическое облако тегов
*/
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aFavouriteTopicUserTags",$aTags);
$this->Viewer_Assign("oFavouriteUser",$oUser);
}
}
class BlockTagsFavouriteTopic extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
if (!($oUser = $this->getParam('user'))) {
$oUser = $oUserCurrent;
}
/**
* Получаем список тегов
*/
$aTags = $this->Favourite_GetGroupTags($oUser->getId(), 'topic', null, 70);
/**
* Расчитываем логарифмическое облако тегов
*/
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aFavouriteTopicTags", $aTags);
/**
* Получаем список тегов пользователя
*/
$aTags = $this->Favourite_GetGroupTags($oUser->getId(), 'topic', true, 70);
/**
* Расчитываем логарифмическое облако тегов
*/
$this->Tools_MakeCloud($aTags);
/**
* Устанавливаем шаблон вывода
*/
$this->Viewer_Assign("aFavouriteTopicUserTags", $aTags);
$this->Viewer_Assign("oFavouriteUser", $oUser);
}
}
}

View file

@ -25,32 +25,39 @@
* @package application.blocks
* @since 1.0
*/
class BlockUserfeedBlogs extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
$aUserSubscribes = $this->Userfeed_getUserSubscribes($oUserCurrent->getId());
/**
* Получаем список ID блогов, в которых состоит пользователь
*/
$aBlogsId = $this->Blog_GetBlogUsersByUserId($oUserCurrent->getId(), array(ModuleBlog::BLOG_USER_ROLE_USER,ModuleBlog::BLOG_USER_ROLE_MODERATOR,ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR),true);
/**
* Получаем список ID блогов, которые создал пользователь
*/
$aBlogsOwnerId=$this->Blog_GetBlogsByOwnerId($oUserCurrent->getId(),true);
$aBlogsId=array_merge($aBlogsId,$aBlogsOwnerId);
class BlockUserfeedBlogs extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
$aUserSubscribes = $this->Userfeed_getUserSubscribes($oUserCurrent->getId());
/**
* Получаем список ID блогов, в которых состоит пользователь
*/
$aBlogsId = $this->Blog_GetBlogUsersByUserId($oUserCurrent->getId(), array(
ModuleBlog::BLOG_USER_ROLE_USER,
ModuleBlog::BLOG_USER_ROLE_MODERATOR,
ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR
), true);
/**
* Получаем список ID блогов, которые создал пользователь
*/
$aBlogsOwnerId = $this->Blog_GetBlogsByOwnerId($oUserCurrent->getId(), true);
$aBlogsId = array_merge($aBlogsId, $aBlogsOwnerId);
$aBlogs=$this->Blog_GetBlogsAdditionalData($aBlogsId,array('owner'=>array()),array('blog_title'=>'asc'));
/**
* Выводим в шаблон
*/
$this->Viewer_Assign('blogsSubscribed', $aUserSubscribes['blogs']);
$this->Viewer_Assign('blogsJoined', $aBlogs);
}
}
$aBlogs = $this->Blog_GetBlogsAdditionalData($aBlogsId, array('owner' => array()),
array('blog_title' => 'asc'));
/**
* Выводим в шаблон
*/
$this->Viewer_Assign('blogsSubscribed', $aUserSubscribes['blogs']);
$this->Viewer_Assign('blogsJoined', $aBlogs);
}
}
}

View file

@ -25,20 +25,22 @@
* @package application.blocks
* @since 1.0
*/
class BlockUserfeedUsers extends Block {
/**
* Запуск обработки
*/
public function Exec() {
/**
* Пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
/**
* Получаем необходимые переменные и прогружаем в шаблон
*/
$aResult=$this->Userfeed_getUserSubscribes($oUserCurrent->getId());
$this->Viewer_Assign('users', $aResult['users']);
}
}
class BlockUserfeedUsers extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
/**
* Пользователь авторизован?
*/
if ($oUserCurrent = $this->User_getUserCurrent()) {
/**
* Получаем необходимые переменные и прогружаем в шаблон
*/
$aResult = $this->Userfeed_getUserSubscribes($oUserCurrent->getId());
$this->Viewer_Assign('users', $aResult['users']);
}
}
}

View file

@ -25,24 +25,27 @@
* @package application.blocks
* @since 2.0
*/
class BlockWall extends Block {
/**
* Запуск обработки
*/
public function Exec() {
$wall = $this->Wall_GetWall( array( 'wall_user_id' => (int) $this->GetParam('user_id'), 'pid' => null ), array( 'id' => 'desc' ), 1, Config::Get( 'module.wall.per_page' ) );
$posts = $wall['collection'];
class BlockWall extends Block
{
/**
* Запуск обработки
*/
public function Exec()
{
$wall = $this->Wall_GetWall(array('wall_user_id' => (int)$this->GetParam('user_id'), 'pid' => null),
array('id' => 'desc'), 1, Config::Get('module.wall.per_page'));
$posts = $wall['collection'];
$this->Viewer_Assign('posts', $posts, true);
$this->Viewer_Assign('count', $wall['count'], true);
$this->Viewer_Assign('classes', $this->GetParam('classes'), true);
$this->Viewer_Assign('attributes', $this->GetParam('attributes'), true);
$this->Viewer_Assign('mods', $this->GetParam('mods'), true);
$this->Viewer_Assign('posts', $posts, true);
$this->Viewer_Assign('count', $wall['count'], true);
$this->Viewer_Assign('classes', $this->GetParam('classes'), true);
$this->Viewer_Assign('attributes', $this->GetParam('attributes'), true);
$this->Viewer_Assign('mods', $this->GetParam('mods'), true);
if ( count($posts) ) {
$this->Viewer_Assign('lastId', end($posts)->getId(), true);
}
if (count($posts)) {
$this->Viewer_Assign('lastId', end($posts)->getId(), true);
}
$this->SetTemplate('components/wall/wall.tpl');
}
$this->SetTemplate('components/wall/wall.tpl');
}
}

View file

@ -25,22 +25,26 @@
* @package application.hooks
* @since 1.0
*/
class HookCopyright extends Hook {
/**
* Регистрируем хуки
*/
public function RegisterHook() {
$this->AddHook('template_copyright','CopyrightLink',__CLASS__,-100);
}
/**
* Обработка хука копирайта
*
* @return string
*/
public function CopyrightLink() {
/**
* Выводим везде, кроме страницы списка блогов и списка всех комментов
*/
return '&copy; Powered by <a href="http://livestreetcms.org">LiveStreet CMS</a>';
}
class HookCopyright extends Hook
{
/**
* Регистрируем хуки
*/
public function RegisterHook()
{
$this->AddHook('template_copyright', 'CopyrightLink', __CLASS__, -100);
}
/**
* Обработка хука копирайта
*
* @return string
*/
public function CopyrightLink()
{
/**
* Выводим везде, кроме страницы списка блогов и списка всех комментов
*/
return '&copy; Powered by <a href="http://livestreetcms.org">LiveStreet CMS</a>';
}
}

View file

@ -25,38 +25,45 @@
* @package application.hooks
* @since 1.0
*/
class HookMain extends Hook {
/**
* Регистрируем хуки
*/
public function RegisterHook() {
$this->AddHook('init_action','InitAction',__CLASS__,1000);
}
/**
* Обработка хука инициализации экшенов
*/
public function InitAction() {
/**
* Проверяем наличие директории install
*/
if(is_dir(rtrim(Config::Get('path.application.server'),'/').'/install') && (!isset($_SERVER['HTTP_APP_ENV']) or $_SERVER['HTTP_APP_ENV']!='test')){
if (Config::Get('install_completed')) {
$this->Message_AddErrorSingle($this->Lang_Get('install_directory_exists'));
Router::Action('error');
} else {
Router::Location(rtrim(str_replace('index.php','',$_SERVER['PHP_SELF']),'/\\').'/application/install/');
}
}
/**
* Проверка на закрытый режим
*/
$oUserCurrent=$this->User_GetUserCurrent();
if (!$oUserCurrent and Config::Get('general.close') and Router::GetAction()!='registration' and Router::GetAction()!='login') {
Router::Action('login');
}
/**
* Запуск обработки сборщика
*/
$this->Ls_SenderRun();
}
class HookMain extends Hook
{
/**
* Регистрируем хуки
*/
public function RegisterHook()
{
$this->AddHook('init_action', 'InitAction', __CLASS__, 1000);
}
/**
* Обработка хука инициализации экшенов
*/
public function InitAction()
{
/**
* Проверяем наличие директории install
*/
if (is_dir(rtrim(Config::Get('path.application.server'),
'/') . '/install') && (!isset($_SERVER['HTTP_APP_ENV']) or $_SERVER['HTTP_APP_ENV'] != 'test')
) {
if (Config::Get('install_completed')) {
$this->Message_AddErrorSingle($this->Lang_Get('install_directory_exists'));
Router::Action('error');
} else {
Router::Location(rtrim(str_replace('index.php', '', $_SERVER['PHP_SELF']),
'/\\') . '/application/install/');
}
}
/**
* Проверка на закрытый режим
*/
$oUserCurrent = $this->User_GetUserCurrent();
if (!$oUserCurrent and Config::Get('general.close') and Router::GetAction() != 'registration' and Router::GetAction() != 'login') {
Router::Action('login');
}
/**
* Запуск обработки сборщика
*/
$this->Ls_SenderRun();
}
}

View file

@ -25,36 +25,40 @@
* @package application.hooks
* @since 1.0
*/
class HookStatisticsPerformance extends Hook {
/**
* Регистрируем хуки
*/
public function RegisterHook() {
$this->AddHook('template_body_end','Statistics',__CLASS__,-1000);
}
/**
* Обработка хука перед закрывающим тегом body
*
* @return string
*/
public function Statistics() {
$oEngine=Engine::getInstance();
/**
* Подсчитываем время выполнения
*/
$iTimeInit=$oEngine->GetTimeInit();
$iTimeFull=round(microtime(true)-$iTimeInit,3);
$this->Viewer_Assign('iTimeFullPerformance',$iTimeFull);
/**
* Получаем статистику по кешу и БД
*/
$aStats=$oEngine->getStats();
$aStats['cache']['time']=round($aStats['cache']['time'],5);
$this->Viewer_Assign('aStatsPerformance',$aStats);
$this->Viewer_Assign('bIsShowStatsPerformance',Router::GetIsShowStats());
/**
* В ответ рендерим шаблон статистики
*/
return $this->Viewer_Fetch('actions/ActionAdmin/statistics_performance.tpl');
}
class HookStatisticsPerformance extends Hook
{
/**
* Регистрируем хуки
*/
public function RegisterHook()
{
$this->AddHook('template_body_end', 'Statistics', __CLASS__, -1000);
}
/**
* Обработка хука перед закрывающим тегом body
*
* @return string
*/
public function Statistics()
{
$oEngine = Engine::getInstance();
/**
* Подсчитываем время выполнения
*/
$iTimeInit = $oEngine->GetTimeInit();
$iTimeFull = round(microtime(true) - $iTimeInit, 3);
$this->Viewer_Assign('iTimeFullPerformance', $iTimeFull);
/**
* Получаем статистику по кешу и БД
*/
$aStats = $oEngine->getStats();
$aStats['cache']['time'] = round($aStats['cache']['time'], 5);
$this->Viewer_Assign('aStatsPerformance', $aStats);
$this->Viewer_Assign('bIsShowStatsPerformance', Router::GetIsShowStats());
/**
* В ответ рендерим шаблон статистики
*/
return $this->Viewer_Fetch('actions/ActionAdmin/statistics_performance.tpl');
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -25,375 +25,457 @@
* @package application.modules.blog
* @since 1.0
*/
class ModuleBlog_EntityBlog extends Entity {
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,
),
);
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 блога
*
* @return int|null
*/
public function getId() {
return $this->_getDataOne('blog_id');
}
/**
* Возвращает ID хозяина блога
*
* @return int|null
*/
public function getOwnerId() {
return $this->_getDataOne('user_owner_id');
}
/**
* Возвращает название блога
*
* @return string|null
*/
public function getTitle() {
return $this->_getDataOne('blog_title');
}
/**
* Возвращает описание блога
*
* @return string|null
*/
public function getDescription() {
return $this->_getDataOne('blog_description');
}
/**
* Возвращает тип блога
*
* @return string|null
*/
public function getType() {
return $this->_getDataOne('blog_type');
}
/**
* Возвращает дату создания блога
*
* @return string|null
*/
public function getDateAdd() {
return $this->_getDataOne('blog_date_add');
}
/**
* Возвращает дату редактирования блога
*
* @return string|null
*/
public function getDateEdit() {
return $this->_getDataOne('blog_date_edit');
}
/**
* Возвращает рейтинг блога
*
* @return string
*/
public function getRating() {
return number_format(round($this->_getDataOne('blog_rating'),2), 2, '.', '');
}
/**
* Возврщает количество проголосовавших за блог
*
* @return int|null
*/
public function getCountVote() {
return $this->_getDataOne('blog_count_vote');
}
/**
* Возвращает количество пользователей в блоге
*
* @return int|null
*/
public function getCountUser() {
return $this->_getDataOne('blog_count_user');
}
/**
* Возвращает количество топиков в блоге
*
* @return int|null
*/
public function getCountTopic() {
return $this->_getDataOne('blog_count_topic');
}
/**
* Возвращает ограничение по рейтингу для постинга в блог
*
* @return int|null
*/
public function getLimitRatingTopic() {
return $this->_getDataOne('blog_limit_rating_topic');
}
/**
* Возвращает URL блога
*
* @return string|null
*/
public function getUrl() {
return $this->_getDataOne('blog_url');
}
/**
* Возвращает полный серверный путь до аватара блога
*
* @return string|null
*/
public function getAvatar() {
return $this->_getDataOne('blog_avatar');
}
/**
* Возвращает расширения аватра блога
*
* @return string|null
*/
public function getAvatarType() {
return ($sPath=$this->getAvatarPath()) ? pathinfo($sPath,PATHINFO_EXTENSION) : null;
}
/**
* Инициализация
*/
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 блога
*
* @return int|null
*/
public function getId()
{
return $this->_getDataOne('blog_id');
}
/**
* Возвращает ID хозяина блога
*
* @return int|null
*/
public function getOwnerId()
{
return $this->_getDataOne('user_owner_id');
}
/**
* Возвращает название блога
*
* @return string|null
*/
public function getTitle()
{
return $this->_getDataOne('blog_title');
}
/**
* Возвращает описание блога
*
* @return string|null
*/
public function getDescription()
{
return $this->_getDataOne('blog_description');
}
/**
* Возвращает тип блога
*
* @return string|null
*/
public function getType()
{
return $this->_getDataOne('blog_type');
}
/**
* Возвращает дату создания блога
*
* @return string|null
*/
public function getDateAdd()
{
return $this->_getDataOne('blog_date_add');
}
/**
* Возвращает дату редактирования блога
*
* @return string|null
*/
public function getDateEdit()
{
return $this->_getDataOne('blog_date_edit');
}
/**
* Возвращает рейтинг блога
*
* @return string
*/
public function getRating()
{
return number_format(round($this->_getDataOne('blog_rating'), 2), 2, '.', '');
}
/**
* Возврщает количество проголосовавших за блог
*
* @return int|null
*/
public function getCountVote()
{
return $this->_getDataOne('blog_count_vote');
}
/**
* Возвращает количество пользователей в блоге
*
* @return int|null
*/
public function getCountUser()
{
return $this->_getDataOne('blog_count_user');
}
/**
* Возвращает количество топиков в блоге
*
* @return int|null
*/
public function getCountTopic()
{
return $this->_getDataOne('blog_count_topic');
}
/**
* Возвращает ограничение по рейтингу для постинга в блог
*
* @return int|null
*/
public function getLimitRatingTopic()
{
return $this->_getDataOne('blog_limit_rating_topic');
}
/**
* Возвращает URL блога
*
* @return string|null
*/
public function getUrl()
{
return $this->_getDataOne('blog_url');
}
/**
* Возвращает полный серверный путь до аватара блога
*
* @return string|null
*/
public function getAvatar()
{
return $this->_getDataOne('blog_avatar');
}
/**
* Возвращает расширения аватра блога
*
* @return string|null
*/
public function getAvatarType()
{
return ($sPath = $this->getAvatarPath()) ? pathinfo($sPath, PATHINFO_EXTENSION) : null;
}
/**
* Возвращает объект пользователя хозяина блога
*
* @return ModuleUser_EntityUser|null
*/
public function getOwner() {
return $this->_getDataOne('owner');
}
/**
* Возвращает объект голосования за блог
*
* @return ModuleVote_EntityVote|null
*/
public function getVote() {
return $this->_getDataOne('vote');
}
/**
* Возвращает полный серверный путь до аватара блога определенного размера
*
* @param int $iSize Размер аватара
* @return string
*/
public function getAvatarPath($iSize=48) {
if ($sPath=$this->getAvatar()) {
if (is_numeric($iSize)) {
$iSize.='crop';
}
return $this->Media_GetImageWebPath($sPath,$iSize);
} else {
return Config::Get('path.skin.assets.web').'/images/avatars/avatar_blog_'.$iSize.'x'.$iSize.'.png';
}
}
/**
* Возвращает факт присоединения пользователя к блогу
*
* @return bool|null
*/
public function getUserIsJoin() {
return $this->_getDataOne('user_is_join');
}
/**
* Проверяет является ли пользователь администратором блога
*
* @return bool|null
*/
public function getUserIsAdministrator() {
return $this->_getDataOne('user_is_administrator');
}
/**
* Проверяет является ли пользователь модератором блога
*
* @return bool|null
*/
public function getUserIsModerator() {
return $this->_getDataOne('user_is_moderator');
}
/**
* Возвращает полный URL блога
*
* @return string
*/
public function getUrlFull() {
if ($this->getType()=='personal') {
return $this->getOwner()->getUserWebPath().'created/topics/';
} else {
return Router::GetPath('blog').$this->getUrl().'/';
}
}
/**
* Возвращает объект пользователя хозяина блога
*
* @return ModuleUser_EntityUser|null
*/
public function getOwner()
{
return $this->_getDataOne('owner');
}
/**
* Устанавливает ID блога
*
* @param int $data
*/
public function setId($data) {
$this->_aData['blog_id']=$data;
}
/**
* Устанавливает ID хозяина блога
*
* @param int $data
*/
public function setOwnerId($data) {
$this->_aData['user_owner_id']=$data;
}
/**
* Устанавливает заголовок блога
*
* @param string $data
*/
public function setTitle($data) {
$this->_aData['blog_title']=$data;
}
/**
* Устанавливает описание блога
*
* @param string $data
*/
public function setDescription($data) {
$this->_aData['blog_description']=$data;
}
/**
* Устанавливает тип блога
*
* @param string $data
*/
public function setType($data) {
$this->_aData['blog_type']=$data;
}
/**
* Устанавливает дату создания блога
*
* @param string $data
*/
public function setDateAdd($data) {
$this->_aData['blog_date_add']=$data;
}
/**
* Устанавливает дату редактирования топика
*
* @param string $data
*/
public function setDateEdit($data) {
$this->_aData['blog_date_edit']=$data;
}
/**
* Устанавливает рейтинг блога
*
* @param float $data
*/
public function setRating($data) {
$this->_aData['blog_rating']=$data;
}
/**
* Устаналивает количество проголосовавших
*
* @param int $data
*/
public function setCountVote($data) {
$this->_aData['blog_count_vote']=$data;
}
/**
* Устанавливает количество пользователей блога
*
* @param int $data
*/
public function setCountUser($data) {
$this->_aData['blog_count_user']=$data;
}
/**
* Устанавливает количество топиков в блоге
*
* @param int $data
*/
public function setCountTopic($data) {
$this->_aData['blog_count_topic']=$data;
}
/**
* Устанавливает ограничение на постинг в блог
*
* @param float $data
*/
public function setLimitRatingTopic($data) {
$this->_aData['blog_limit_rating_topic']=$data;
}
/**
* Устанавливает URL блога
*
* @param string $data
*/
public function setUrl($data) {
$this->_aData['blog_url']=$data;
}
/**
* Устанавливает полный серверный путь до аватара блога
*
* @param string $data
*/
public function setAvatar($data) {
$this->_aData['blog_avatar']=$data;
}
/**
* Устанавливает автора блога
*
* @param ModuleUser_EntityUser $data
*/
public function setOwner($data) {
$this->_aData['owner']=$data;
}
/**
* Устанавливает статус администратора блога для текущего пользователя
*
* @param bool $data
*/
public function setUserIsAdministrator($data) {
$this->_aData['user_is_administrator']=$data;
}
/**
* Устанавливает статус модератора блога для текущего пользователя
*
* @param bool $data
*/
public function setUserIsModerator($data) {
$this->_aData['user_is_moderator']=$data;
}
/**
* Устаналивает статус присоединения польователя к блогу
*
* @param bool $data
*/
public function setUserIsJoin($data) {
$this->_aData['user_is_join']=$data;
}
/**
* Устанавливает объект голосования за блог
*
* @param ModuleVote_EntityVote $data
*/
public function setVote($data) {
$this->_aData['vote']=$data;
}
/**
* Возвращает объект голосования за блог
*
* @return ModuleVote_EntityVote|null
*/
public function getVote()
{
return $this->_getDataOne('vote');
}
/**
* Возвращает полный серверный путь до аватара блога определенного размера
*
* @param int $iSize Размер аватара
* @return string
*/
public function getAvatarPath($iSize = 48)
{
if ($sPath = $this->getAvatar()) {
if (is_numeric($iSize)) {
$iSize .= 'crop';
}
return $this->Media_GetImageWebPath($sPath, $iSize);
} else {
return Config::Get('path.skin.assets.web') . '/images/avatars/avatar_blog_' . $iSize . 'x' . $iSize . '.png';
}
}
/**
* Возвращает факт присоединения пользователя к блогу
*
* @return bool|null
*/
public function getUserIsJoin()
{
return $this->_getDataOne('user_is_join');
}
/**
* Проверяет является ли пользователь администратором блога
*
* @return bool|null
*/
public function getUserIsAdministrator()
{
return $this->_getDataOne('user_is_administrator');
}
/**
* Проверяет является ли пользователь модератором блога
*
* @return bool|null
*/
public function getUserIsModerator()
{
return $this->_getDataOne('user_is_moderator');
}
/**
* Возвращает полный URL блога
*
* @return string
*/
public function getUrlFull()
{
if ($this->getType() == 'personal') {
return $this->getOwner()->getUserWebPath() . 'created/topics/';
} else {
return Router::GetPath('blog') . $this->getUrl() . '/';
}
}
/**
* Устанавливает ID блога
*
* @param int $data
*/
public function setId($data)
{
$this->_aData['blog_id'] = $data;
}
/**
* Устанавливает ID хозяина блога
*
* @param int $data
*/
public function setOwnerId($data)
{
$this->_aData['user_owner_id'] = $data;
}
/**
* Устанавливает заголовок блога
*
* @param string $data
*/
public function setTitle($data)
{
$this->_aData['blog_title'] = $data;
}
/**
* Устанавливает описание блога
*
* @param string $data
*/
public function setDescription($data)
{
$this->_aData['blog_description'] = $data;
}
/**
* Устанавливает тип блога
*
* @param string $data
*/
public function setType($data)
{
$this->_aData['blog_type'] = $data;
}
/**
* Устанавливает дату создания блога
*
* @param string $data
*/
public function setDateAdd($data)
{
$this->_aData['blog_date_add'] = $data;
}
/**
* Устанавливает дату редактирования топика
*
* @param string $data
*/
public function setDateEdit($data)
{
$this->_aData['blog_date_edit'] = $data;
}
/**
* Устанавливает рейтинг блога
*
* @param float $data
*/
public function setRating($data)
{
$this->_aData['blog_rating'] = $data;
}
/**
* Устаналивает количество проголосовавших
*
* @param int $data
*/
public function setCountVote($data)
{
$this->_aData['blog_count_vote'] = $data;
}
/**
* Устанавливает количество пользователей блога
*
* @param int $data
*/
public function setCountUser($data)
{
$this->_aData['blog_count_user'] = $data;
}
/**
* Устанавливает количество топиков в блоге
*
* @param int $data
*/
public function setCountTopic($data)
{
$this->_aData['blog_count_topic'] = $data;
}
/**
* Устанавливает ограничение на постинг в блог
*
* @param float $data
*/
public function setLimitRatingTopic($data)
{
$this->_aData['blog_limit_rating_topic'] = $data;
}
/**
* Устанавливает URL блога
*
* @param string $data
*/
public function setUrl($data)
{
$this->_aData['blog_url'] = $data;
}
/**
* Устанавливает полный серверный путь до аватара блога
*
* @param string $data
*/
public function setAvatar($data)
{
$this->_aData['blog_avatar'] = $data;
}
/**
* Устанавливает автора блога
*
* @param ModuleUser_EntityUser $data
*/
public function setOwner($data)
{
$this->_aData['owner'] = $data;
}
/**
* Устанавливает статус администратора блога для текущего пользователя
*
* @param bool $data
*/
public function setUserIsAdministrator($data)
{
$this->_aData['user_is_administrator'] = $data;
}
/**
* Устанавливает статус модератора блога для текущего пользователя
*
* @param bool $data
*/
public function setUserIsModerator($data)
{
$this->_aData['user_is_moderator'] = $data;
}
/**
* Устаналивает статус присоединения польователя к блогу
*
* @param bool $data
*/
public function setUserIsJoin($data)
{
$this->_aData['user_is_join'] = $data;
}
/**
* Устанавливает объект голосования за блог
*
* @param ModuleVote_EntityVote $data
*/
public function setVote($data)
{
$this->_aData['vote'] = $data;
}
}

View file

@ -25,129 +25,156 @@
* @package application.modules.blog
* @since 1.0
*/
class ModuleBlog_EntityBlogUser extends Entity {
/**
* Возвращает ID блога
*
* @return int|null
*/
public function getBlogId() {
return $this->_getDataOne('blog_id');
}
/**
* Возвращает ID пользователя
*
* @return int|null
*/
public function getUserId() {
return $this->_getDataOne('user_id');
}
/**
* Возвращает статус модератор пользователь или нет
*
* @return bool
*/
public function getIsModerator() {
return ($this->getUserRole()==ModuleBlog::BLOG_USER_ROLE_MODERATOR);
}
/**
* Возвращает статус администратор пользователь или нет
*
* @return bool
*/
public function getIsAdministrator() {
return ($this->getUserRole()==ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR);
}
/**
* Возвращает текущую роль пользователя в блоге
*
* @return int|null
*/
public function getUserRole() {
return $this->_getDataOne('user_role');
}
/**
* Возвращает объект блога
*
* @return ModuleBlog_EntityBlog|null
*/
public function getBlog() {
return $this->_getDataOne('blog');
}
/**
* Возвращает объект пользователя
*
* @return ModuleUser_EntityUser|null
*/
public function getUser() {
return $this->_getDataOne('user');
}
class ModuleBlog_EntityBlogUser extends Entity
{
/**
* Возвращает ID блога
*
* @return int|null
*/
public function getBlogId()
{
return $this->_getDataOne('blog_id');
}
/**
* Возвращает ID пользователя
*
* @return int|null
*/
public function getUserId()
{
return $this->_getDataOne('user_id');
}
/**
* Возвращает статус модератор пользователь или нет
*
* @return bool
*/
public function getIsModerator()
{
return ($this->getUserRole() == ModuleBlog::BLOG_USER_ROLE_MODERATOR);
}
/**
* Возвращает статус администратор пользователь или нет
*
* @return bool
*/
public function getIsAdministrator()
{
return ($this->getUserRole() == ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR);
}
/**
* Возвращает текущую роль пользователя в блоге
*
* @return int|null
*/
public function getUserRole()
{
return $this->_getDataOne('user_role');
}
/**
* Возвращает объект блога
*
* @return ModuleBlog_EntityBlog|null
*/
public function getBlog()
{
return $this->_getDataOne('blog');
}
/**
* Возвращает объект пользователя
*
* @return ModuleUser_EntityUser|null
*/
public function getUser()
{
return $this->_getDataOne('user');
}
/**
* Устанавливает ID блога
*
* @param int $data
*/
public function setBlogId($data) {
$this->_aData['blog_id']=$data;
}
/**
* Устанавливает ID пользователя
*
* @param int $data
*/
public function setUserId($data) {
$this->_aData['user_id']=$data;
}
/**
* Устанавливает статус модератора блога
*
* @param bool $data
*/
public function setIsModerator($data) {
if($data && !$this->getIsModerator()) {
/**
* Повышаем статус до модератора
*/
$this->setUserRole(ModuleBlog::BLOG_USER_ROLE_MODERATOR);
}
}
/**
* Устанавливает статус администратора блога
*
* @param bool $data
*/
public function setIsAdministrator($data) {
if($data && !$this->getIsAdministrator()) {
/**
* Повышаем статус до администратора
*/
$this->setUserRole(ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR);
}
}
/**
* Устанавливает роль пользователя
*
* @param int $data
*/
public function setUserRole($data) {
$this->_aData['user_role']=$data;
}
/**
* Устанавливает блог
*
* @param ModuleBlog_EntityBlog $data
*/
public function setBlog($data) {
$this->_aData['blog']=$data;
}
/**
* Устанавливаем пользователя
*
* @param ModuleUser_EntityUser $data
*/
public function setUser($data) {
$this->_aData['user']=$data;
}
/**
* Устанавливает ID блога
*
* @param int $data
*/
public function setBlogId($data)
{
$this->_aData['blog_id'] = $data;
}
/**
* Устанавливает ID пользователя
*
* @param int $data
*/
public function setUserId($data)
{
$this->_aData['user_id'] = $data;
}
/**
* Устанавливает статус модератора блога
*
* @param bool $data
*/
public function setIsModerator($data)
{
if ($data && !$this->getIsModerator()) {
/**
* Повышаем статус до модератора
*/
$this->setUserRole(ModuleBlog::BLOG_USER_ROLE_MODERATOR);
}
}
/**
* Устанавливает статус администратора блога
*
* @param bool $data
*/
public function setIsAdministrator($data)
{
if ($data && !$this->getIsAdministrator()) {
/**
* Повышаем статус до администратора
*/
$this->setUserRole(ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR);
}
}
/**
* Устанавливает роль пользователя
*
* @param int $data
*/
public function setUserRole($data)
{
$this->_aData['user_role'] = $data;
}
/**
* Устанавливает блог
*
* @param ModuleBlog_EntityBlog $data
*/
public function setBlog($data)
{
$this->_aData['blog'] = $data;
}
/**
* Устанавливаем пользователя
*
* @param ModuleUser_EntityUser $data
*/
public function setUser($data)
{
$this->_aData['user'] = $data;
}
}

View file

@ -25,15 +25,17 @@
* @package application.modules.blog
* @since 1.0
*/
class ModuleBlog_MapperBlog extends Mapper {
/**
* Добавляет блог в БД
*
* @param ModuleBlog_EntityBlog $oBlog Объект блога
* @return int|bool
*/
public function AddBlog(ModuleBlog_EntityBlog $oBlog) {
$sql = "INSERT INTO ".Config::Get('db.table.blog')."
class ModuleBlog_MapperBlog extends Mapper
{
/**
* Добавляет блог в БД
*
* @param ModuleBlog_EntityBlog $oBlog Объект блога
* @return int|bool
*/
public function AddBlog(ModuleBlog_EntityBlog $oBlog)
{
$sql = "INSERT INTO " . Config::Get('db.table.blog') . "
(user_owner_id,
blog_title,
blog_description,
@ -45,19 +47,24 @@ class ModuleBlog_MapperBlog extends Mapper {
)
VALUES(?d, ?, ?, ?, ?, ?, ?, ?)
";
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;
}
/**
* Обновляет блог в БД
*
* @param ModuleBlog_EntityBlog $oBlog Объект блога
* @return bool
*/
public function UpdateBlog(ModuleBlog_EntityBlog $oBlog) {
$sql = "UPDATE ".Config::Get('db.table.blog')."
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;
}
/**
* Обновляет блог в БД
*
* @param ModuleBlog_EntityBlog $oBlog Объект блога
* @return bool
*/
public function UpdateBlog(ModuleBlog_EntityBlog $oBlog)
{
$sql = "UPDATE " . Config::Get('db.table.blog') . "
SET
blog_title= ?,
blog_description= ?,
@ -73,94 +80,112 @@ class ModuleBlog_MapperBlog extends Mapper {
WHERE
blog_id = ?d
";
$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);
}
/**
* Получает список блогов по ID
*
* @param array $aArrayId Список ID блогов
* @param array|null $aOrder Сортировка блогов
* @return array
*/
public function GetBlogsByArrayId($aArrayId,$aOrder=null) {
if (!is_array($aArrayId) or count($aArrayId)==0) {
return array();
}
$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);
}
if (!is_array($aOrder)) $aOrder=array($aOrder);
$sOrder='';
foreach ($aOrder as $key=>$value) {
$value=(string)$value;
if (!in_array($key,array('blog_id','blog_title','blog_type','blog_rating','blog_count_user','blog_date_add'))) {
unset($aOrder[$key]);
} elseif (in_array($value,array('asc','desc'))) {
$sOrder.=" {$key} {$value},";
}
}
$sOrder=trim($sOrder,',');
/**
* Получает список блогов по ID
*
* @param array $aArrayId Список ID блогов
* @param array|null $aOrder Сортировка блогов
* @return array
*/
public function GetBlogsByArrayId($aArrayId, $aOrder = null)
{
if (!is_array($aArrayId) or count($aArrayId) == 0) {
return array();
}
$sql = "SELECT
if (!is_array($aOrder)) {
$aOrder = array($aOrder);
}
$sOrder = '';
foreach ($aOrder as $key => $value) {
$value = (string)$value;
if (!in_array($key,
array('blog_id', 'blog_title', 'blog_type', 'blog_rating', 'blog_count_user', 'blog_date_add'))
) {
unset($aOrder[$key]);
} elseif (in_array($value, array('asc', 'desc'))) {
$sOrder .= " {$key} {$value},";
}
}
$sOrder = trim($sOrder, ',');
$sql = "SELECT
*
FROM
".Config::Get('db.table.blog')."
" . Config::Get('db.table.blog') . "
WHERE
blog_id IN(?a)
ORDER BY
{ FIELD(blog_id,?a) } ";
if ($sOrder!='') $sql.=$sOrder;
if ($sOrder != '') {
$sql .= $sOrder;
}
$aBlogs=array();
if ($aRows=$this->oDb->select($sql,$aArrayId,$sOrder=='' ? $aArrayId : DBSIMPLE_SKIP)) {
foreach ($aRows as $aBlog) {
$aBlogs[]=Engine::GetEntity('Blog',$aBlog);
}
}
return $aBlogs;
}
/**
* Добавляет свзяь пользователя с блогом в БД
*
* @param ModuleBlog_EntityBlogUser $oBlogUser Объект отношения пользователя с блогом
* @return bool
*/
public function AddRelationBlogUser(ModuleBlog_EntityBlogUser $oBlogUser) {
$sql = "INSERT INTO ".Config::Get('db.table.blog_user')."
$aBlogs = array();
if ($aRows = $this->oDb->select($sql, $aArrayId, $sOrder == '' ? $aArrayId : DBSIMPLE_SKIP)) {
foreach ($aRows as $aBlog) {
$aBlogs[] = Engine::GetEntity('Blog', $aBlog);
}
}
return $aBlogs;
}
/**
* Добавляет свзяь пользователя с блогом в БД
*
* @param ModuleBlog_EntityBlogUser $oBlogUser Объект отношения пользователя с блогом
* @return bool
*/
public function AddRelationBlogUser(ModuleBlog_EntityBlogUser $oBlogUser)
{
$sql = "INSERT INTO " . Config::Get('db.table.blog_user') . "
(blog_id,
user_id,
user_role
)
VALUES(?d, ?d, ?d)
";
if ($this->oDb->query($sql,$oBlogUser->getBlogId(),$oBlogUser->getUserId(),$oBlogUser->getUserRole())===0) {
return true;
}
return false;
}
/**
* Удаляет отношение пользователя с блогом
*
* @param ModuleBlog_EntityBlogUser $oBlogUser Объект отношения пользователя с блогом
* @return bool
*/
public function DeleteRelationBlogUser(ModuleBlog_EntityBlogUser $oBlogUser) {
$sql = "DELETE FROM ".Config::Get('db.table.blog_user')."
if ($this->oDb->query($sql, $oBlogUser->getBlogId(), $oBlogUser->getUserId(), $oBlogUser->getUserRole()) === 0
) {
return true;
}
return false;
}
/**
* Удаляет отношение пользователя с блогом
*
* @param ModuleBlog_EntityBlogUser $oBlogUser Объект отношения пользователя с блогом
* @return bool
*/
public function DeleteRelationBlogUser(ModuleBlog_EntityBlogUser $oBlogUser)
{
$sql = "DELETE FROM " . Config::Get('db.table.blog_user') . "
WHERE
blog_id = ?d
AND
user_id = ?d
";
$res=$this->oDb->query($sql,$oBlogUser->getBlogId(),$oBlogUser->getUserId());
return $this->IsSuccessful($res);
}
/**
* Обновляет отношение пользователя с блогом
*
* @param ModuleBlog_EntityBlogUser $oBlogUser Объект отношения пользователя с блогом
* @return bool
*/
public function UpdateRelationBlogUser(ModuleBlog_EntityBlogUser $oBlogUser) {
$sql = "UPDATE ".Config::Get('db.table.blog_user')."
$res = $this->oDb->query($sql, $oBlogUser->getBlogId(), $oBlogUser->getUserId());
return $this->IsSuccessful($res);
}
/**
* Обновляет отношение пользователя с блогом
*
* @param ModuleBlog_EntityBlogUser $oBlogUser Объект отношения пользователя с блогом
* @return bool
*/
public function UpdateRelationBlogUser(ModuleBlog_EntityBlogUser $oBlogUser)
{
$sql = "UPDATE " . Config::Get('db.table.blog_user') . "
SET
user_role = ?d
WHERE
@ -168,213 +193,231 @@ class ModuleBlog_MapperBlog extends Mapper {
AND
user_id = ?d
";
$res=$this->oDb->query($sql,$oBlogUser->getUserRole(),$oBlogUser->getBlogId(),$oBlogUser->getUserId());
return $this->IsSuccessful($res);
}
/**
* Получает список отношений пользователей с блогами
*
* @param array $aFilter Фильтр поиска отношений
* @param int $iCount Возвращает общее количество элементов
* @param int $iCurrPage Номер текущейс страницы
* @param int $iPerPage Количество элементов на одну страницу
* @return array
*/
public function GetBlogUsers($aFilter,&$iCount=null,$iCurrPage=null,$iPerPage=null) {
$sWhere=' 1=1 ';
if (isset($aFilter['blog_id'])) {
$sWhere.=" AND bu.blog_id = ".(int)$aFilter['blog_id'];
}
if (isset($aFilter['user_id'])) {
$sWhere.=" AND bu.user_id = ".(int)$aFilter['user_id'];
}
if (isset($aFilter['user_role'])) {
if(!is_array($aFilter['user_role'])) {
$aFilter['user_role']=array($aFilter['user_role']);
}
$sWhere.=" AND bu.user_role IN ('".join("', '",$aFilter['user_role'])."')";
} else {
$sWhere.=" AND bu.user_role>".ModuleBlog::BLOG_USER_ROLE_GUEST;
}
$res = $this->oDb->query($sql, $oBlogUser->getUserRole(), $oBlogUser->getBlogId(), $oBlogUser->getUserId());
return $this->IsSuccessful($res);
}
$sql = "SELECT
/**
* Получает список отношений пользователей с блогами
*
* @param array $aFilter Фильтр поиска отношений
* @param int $iCount Возвращает общее количество элементов
* @param int $iCurrPage Номер текущейс страницы
* @param int $iPerPage Количество элементов на одну страницу
* @return array
*/
public function GetBlogUsers($aFilter, &$iCount = null, $iCurrPage = null, $iPerPage = null)
{
$sWhere = ' 1=1 ';
if (isset($aFilter['blog_id'])) {
$sWhere .= " AND bu.blog_id = " . (int)$aFilter['blog_id'];
}
if (isset($aFilter['user_id'])) {
$sWhere .= " AND bu.user_id = " . (int)$aFilter['user_id'];
}
if (isset($aFilter['user_role'])) {
if (!is_array($aFilter['user_role'])) {
$aFilter['user_role'] = array($aFilter['user_role']);
}
$sWhere .= " AND bu.user_role IN ('" . join("', '", $aFilter['user_role']) . "')";
} else {
$sWhere .= " AND bu.user_role>" . ModuleBlog::BLOG_USER_ROLE_GUEST;
}
$sql = "SELECT
bu.*
FROM
".Config::Get('db.table.blog_user')." as bu
" . Config::Get('db.table.blog_user') . " as bu
WHERE
".$sWhere." ";
" . $sWhere . " ";
if (is_null($iCurrPage)) {
$aRows=$this->oDb->select($sql);
} else {
$sql.=" LIMIT ?d, ?d ";
$aRows=$this->oDb->selectPage($iCount,$sql,($iCurrPage-1)*$iPerPage, $iPerPage);
}
if (is_null($iCurrPage)) {
$aRows = $this->oDb->select($sql);
} else {
$sql .= " LIMIT ?d, ?d ";
$aRows = $this->oDb->selectPage($iCount, $sql, ($iCurrPage - 1) * $iPerPage, $iPerPage);
}
$aBlogUsers=array();
if ($aRows) {
foreach ($aRows as $aUser) {
$aBlogUsers[]=Engine::GetEntity('Blog_BlogUser',$aUser);
}
}
return $aBlogUsers;
}
/**
* Получает список отношений пользователя к блогам
*
* @param array $aArrayId Список ID блогов
* @param int $sUserId ID блогов
* @return array
*/
public function GetBlogUsersByArrayBlog($aArrayId,$sUserId) {
if (!is_array($aArrayId) or count($aArrayId)==0) {
return array();
}
$aBlogUsers = array();
if ($aRows) {
foreach ($aRows as $aUser) {
$aBlogUsers[] = Engine::GetEntity('Blog_BlogUser', $aUser);
}
}
return $aBlogUsers;
}
$sql = "SELECT
/**
* Получает список отношений пользователя к блогам
*
* @param array $aArrayId Список ID блогов
* @param int $sUserId ID блогов
* @return array
*/
public function GetBlogUsersByArrayBlog($aArrayId, $sUserId)
{
if (!is_array($aArrayId) or count($aArrayId) == 0) {
return array();
}
$sql = "SELECT
bu.*
FROM
".Config::Get('db.table.blog_user')." as bu
" . Config::Get('db.table.blog_user') . " as bu
WHERE
bu.blog_id IN(?a)
AND
bu.user_id = ?d ";
$aBlogUsers=array();
if ($aRows=$this->oDb->select($sql,$aArrayId,$sUserId)) {
foreach ($aRows as $aUser) {
$aBlogUsers[]=Engine::GetEntity('Blog_BlogUser',$aUser);
}
}
return $aBlogUsers;
}
/**
* Получает ID персонального блога пользователя
*
* @param int $sUserId ID пользователя
* @return int|null
*/
public function GetPersonalBlogByUserId($sUserId) {
$sql = "SELECT blog_id FROM ".Config::Get('db.table.blog')." WHERE user_owner_id = ?d and blog_type='personal'";
if ($aRow=$this->oDb->selectRow($sql,$sUserId)) {
return $aRow['blog_id'];
}
return null;
}
/**
* Получает блог по названию
*
* @param string $sTitle Нащвание блога
* @return ModuleBlog_EntityBlog|null
*/
public function GetBlogByTitle($sTitle) {
$sql = "SELECT blog_id FROM ".Config::Get('db.table.blog')." WHERE blog_title = ? ";
if ($aRow=$this->oDb->selectRow($sql,$sTitle)) {
return $aRow['blog_id'];
}
return null;
}
/**
* Получает блог по URL
*
* @param string $sUrl URL блога
* @return ModuleBlog_EntityBlog|null
*/
public function GetBlogByUrl($sUrl) {
$sql = "SELECT
$aBlogUsers = array();
if ($aRows = $this->oDb->select($sql, $aArrayId, $sUserId)) {
foreach ($aRows as $aUser) {
$aBlogUsers[] = Engine::GetEntity('Blog_BlogUser', $aUser);
}
}
return $aBlogUsers;
}
/**
* Получает ID персонального блога пользователя
*
* @param int $sUserId ID пользователя
* @return int|null
*/
public function GetPersonalBlogByUserId($sUserId)
{
$sql = "SELECT blog_id FROM " . Config::Get('db.table.blog') . " WHERE user_owner_id = ?d and blog_type='personal'";
if ($aRow = $this->oDb->selectRow($sql, $sUserId)) {
return $aRow['blog_id'];
}
return null;
}
/**
* Получает блог по названию
*
* @param string $sTitle Нащвание блога
* @return ModuleBlog_EntityBlog|null
*/
public function GetBlogByTitle($sTitle)
{
$sql = "SELECT blog_id FROM " . Config::Get('db.table.blog') . " WHERE blog_title = ? ";
if ($aRow = $this->oDb->selectRow($sql, $sTitle)) {
return $aRow['blog_id'];
}
return null;
}
/**
* Получает блог по URL
*
* @param string $sUrl URL блога
* @return ModuleBlog_EntityBlog|null
*/
public function GetBlogByUrl($sUrl)
{
$sql = "SELECT
b.blog_id
FROM
".Config::Get('db.table.blog')." as b
" . Config::Get('db.table.blog') . " as b
WHERE
b.blog_url = ?
";
if ($aRow=$this->oDb->selectRow($sql,$sUrl)) {
return $aRow['blog_id'];
}
return null;
}
/**
* Получить список блогов по хозяину
*
* @param int $sUserId ID пользователя
* @return array
*/
public function GetBlogsByOwnerId($sUserId) {
$sql = "SELECT
if ($aRow = $this->oDb->selectRow($sql, $sUrl)) {
return $aRow['blog_id'];
}
return null;
}
/**
* Получить список блогов по хозяину
*
* @param int $sUserId ID пользователя
* @return array
*/
public function GetBlogsByOwnerId($sUserId)
{
$sql = "SELECT
b.blog_id
FROM
".Config::Get('db.table.blog')." as b
" . Config::Get('db.table.blog') . " as b
WHERE
b.user_owner_id = ?
AND
b.blog_type<>'personal'
";
$aBlogs=array();
if ($aRows=$this->oDb->select($sql,$sUserId)) {
foreach ($aRows as $aBlog) {
$aBlogs[]=$aBlog['blog_id'];
}
}
return $aBlogs;
}
/**
* Возвращает список всех не персональных блогов
*
* @return array
*/
public function GetBlogs() {
$sql = "SELECT
$aBlogs = array();
if ($aRows = $this->oDb->select($sql, $sUserId)) {
foreach ($aRows as $aBlog) {
$aBlogs[] = $aBlog['blog_id'];
}
}
return $aBlogs;
}
/**
* Возвращает список всех не персональных блогов
*
* @return array
*/
public function GetBlogs()
{
$sql = "SELECT
b.blog_id
FROM
".Config::Get('db.table.blog')." as b
" . Config::Get('db.table.blog') . " as b
WHERE
b.blog_type<>'personal'
";
$aBlogs=array();
if ($aRows=$this->oDb->select($sql)) {
foreach ($aRows as $aBlog) {
$aBlogs[]=$aBlog['blog_id'];
}
}
return $aBlogs;
}
/**
* Возвращает список не персональных блогов с сортировкой по рейтингу
*
* @param int $iCount Возвращает общее количество элементов
* @param int $iCurrPage Номер текущей страницы
* @param int $iPerPage Количество элементов на одну страницу
* @return array
*/
public function GetBlogsRating(&$iCount,$iCurrPage,$iPerPage) {
$sql = "SELECT
$aBlogs = array();
if ($aRows = $this->oDb->select($sql)) {
foreach ($aRows as $aBlog) {
$aBlogs[] = $aBlog['blog_id'];
}
}
return $aBlogs;
}
/**
* Возвращает список не персональных блогов с сортировкой по рейтингу
*
* @param int $iCount Возвращает общее количество элементов
* @param int $iCurrPage Номер текущей страницы
* @param int $iPerPage Количество элементов на одну страницу
* @return array
*/
public function GetBlogsRating(&$iCount, $iCurrPage, $iPerPage)
{
$sql = "SELECT
b.blog_id
FROM
".Config::Get('db.table.blog')." as b
" . Config::Get('db.table.blog') . " as b
WHERE
b.blog_type<>'personal'
ORDER by b.blog_rating desc
LIMIT ?d, ?d ";
$aReturn=array();
if ($aRows=$this->oDb->selectPage($iCount,$sql,($iCurrPage-1)*$iPerPage, $iPerPage)) {
foreach ($aRows as $aRow) {
$aReturn[]=$aRow['blog_id'];
}
}
return $aReturn;
}
/**
* Получает список блогов в которых состоит пользователь
*
* @param int $sUserId ID пользователя
* @param int $iLimit Ограничение на выборку элементов
* @return array
*/
public function GetBlogsRatingJoin($sUserId,$iLimit) {
$sql = "SELECT
$aReturn = array();
if ($aRows = $this->oDb->selectPage($iCount, $sql, ($iCurrPage - 1) * $iPerPage, $iPerPage)) {
foreach ($aRows as $aRow) {
$aReturn[] = $aRow['blog_id'];
}
}
return $aReturn;
}
/**
* Получает список блогов в которых состоит пользователь
*
* @param int $sUserId ID пользователя
* @param int $iLimit Ограничение на выборку элементов
* @return array
*/
public function GetBlogsRatingJoin($sUserId, $iLimit)
{
$sql = "SELECT
b.*
FROM
".Config::Get('db.table.blog_user')." as bu,
".Config::Get('db.table.blog')." as b
" . Config::Get('db.table.blog_user') . " as bu,
" . Config::Get('db.table.blog') . " as b
WHERE
bu.user_id = ?d
AND
@ -385,26 +428,28 @@ class ModuleBlog_MapperBlog extends Mapper {
LIMIT 0, ?d
;
";
$aReturn=array();
if ($aRows=$this->oDb->select($sql,$sUserId,$iLimit)) {
foreach ($aRows as $aRow) {
$aReturn[]=Engine::GetEntity('Blog',$aRow);
}
}
return $aReturn;
}
/**
* Получает список блогов, которые создал пользователь
*
* @param int $sUserId ID пользователя
* @param int $iLimit Ограничение на выборку элементов
* @return array
*/
public function GetBlogsRatingSelf($sUserId,$iLimit) {
$sql = "SELECT
$aReturn = array();
if ($aRows = $this->oDb->select($sql, $sUserId, $iLimit)) {
foreach ($aRows as $aRow) {
$aReturn[] = Engine::GetEntity('Blog', $aRow);
}
}
return $aReturn;
}
/**
* Получает список блогов, которые создал пользователь
*
* @param int $sUserId ID пользователя
* @param int $iLimit Ограничение на выборку элементов
* @return array
*/
public function GetBlogsRatingSelf($sUserId, $iLimit)
{
$sql = "SELECT
b.*
FROM
".Config::Get('db.table.blog')." as b
" . Config::Get('db.table.blog') . " as b
WHERE
b.user_owner_id = ?d
AND
@ -412,72 +457,80 @@ class ModuleBlog_MapperBlog extends Mapper {
ORDER by b.blog_rating desc
LIMIT 0, ?d
;";
$aReturn=array();
if ($aRows=$this->oDb->select($sql,$sUserId,$iLimit)) {
foreach ($aRows as $aRow) {
$aReturn[]=Engine::GetEntity('Blog',$aRow);
}
}
return $aReturn;
}
/**
* Возвращает полный список закрытых блогов
*
* @return array
*/
public function GetCloseBlogs() {
$sql = "SELECT b.blog_id
FROM ".Config::Get('db.table.blog')." as b
$aReturn = array();
if ($aRows = $this->oDb->select($sql, $sUserId, $iLimit)) {
foreach ($aRows as $aRow) {
$aReturn[] = Engine::GetEntity('Blog', $aRow);
}
}
return $aReturn;
}
/**
* Возвращает полный список закрытых блогов
*
* @return array
*/
public function GetCloseBlogs()
{
$sql = "SELECT b.blog_id
FROM " . Config::Get('db.table.blog') . " as b
WHERE b.blog_type='close'
;";
$aReturn=array();
if ($aRows=$this->oDb->select($sql)) {
foreach ($aRows as $aRow) {
$aReturn[]=$aRow['blog_id'];
}
}
return $aReturn;
}
/**
* Удаление блога из базы данных
*
* @param int $iBlogId ID блога
* @return bool
*/
public function DeleteBlog($iBlogId) {
$sql = "
DELETE FROM ".Config::Get('db.table.blog')."
$aReturn = array();
if ($aRows = $this->oDb->select($sql)) {
foreach ($aRows as $aRow) {
$aReturn[] = $aRow['blog_id'];
}
}
return $aReturn;
}
/**
* Удаление блога из базы данных
*
* @param int $iBlogId ID блога
* @return bool
*/
public function DeleteBlog($iBlogId)
{
$sql = "
DELETE FROM " . Config::Get('db.table.blog') . "
WHERE blog_id = ?d
";
$res=$this->oDb->query($sql,$iBlogId);
return $this->IsSuccessful($res);
}
/**
* Удалить пользователей блога по идентификатору блога
*
* @param int $iBlogId ID блога
* @return bool
*/
public function DeleteBlogUsersByBlogId($iBlogId) {
$sql = "
DELETE FROM ".Config::Get('db.table.blog_user')."
$res = $this->oDb->query($sql, $iBlogId);
return $this->IsSuccessful($res);
}
/**
* Удалить пользователей блога по идентификатору блога
*
* @param int $iBlogId ID блога
* @return bool
*/
public function DeleteBlogUsersByBlogId($iBlogId)
{
$sql = "
DELETE FROM " . Config::Get('db.table.blog_user') . "
WHERE blog_id = ?d
";
$res=$this->oDb->query($sql,$iBlogId);
return $this->IsSuccessful($res);
}
/**
* Пересчитывает число топиков в блогах
*
* @param int|null $iBlogId ID блога
* @return bool
*/
public function RecalculateCountTopic($iBlogId=null) {
$sql = "
UPDATE ".Config::Get('db.table.blog')." b
$res = $this->oDb->query($sql, $iBlogId);
return $this->IsSuccessful($res);
}
/**
* Пересчитывает число топиков в блогах
*
* @param int|null $iBlogId ID блога
* @return bool
*/
public function RecalculateCountTopic($iBlogId = null)
{
$sql = "
UPDATE " . Config::Get('db.table.blog') . " b
SET b.blog_count_topic = (
SELECT count(*)
FROM ".Config::Get('db.table.topic')." t
FROM " . Config::Get('db.table.topic') . " t
WHERE
t.blog_id = b.blog_id
AND
@ -486,48 +539,50 @@ class ModuleBlog_MapperBlog extends Mapper {
WHERE 1=1
{ and b.blog_id = ?d }
";
$res=$this->oDb->query($sql,is_null($iBlogId) ? DBSIMPLE_SKIP : $iBlogId);
return $this->IsSuccessful($res);
}
/**
* Получает список блогов по фильтру
*
* @param array $aFilter Фильтр выборки
* @param array $aOrder Сортировка
* @param int $iCount Возвращает общее количество элментов
* @param int $iCurrPage Номер текущей страницы
* @param int $iPerPage Количество элементов на одну страницу
* @return array
*/
public function GetBlogsByFilter($aFilter,$aOrder,&$iCount,$iCurrPage,$iPerPage) {
$aOrderAllow=array('blog_id','blog_title','blog_rating','blog_count_user','blog_count_topic');
$sOrder='';
foreach ($aOrder as $key=>$value) {
if (!in_array($key,$aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value,array('asc','desc'))) {
$sOrder.=" {$key} {$value},";
}
}
$sOrder=trim($sOrder,',');
if ($sOrder=='') {
$sOrder=' blog_id desc ';
}
$res = $this->oDb->query($sql, is_null($iBlogId) ? DBSIMPLE_SKIP : $iBlogId);
return $this->IsSuccessful($res);
}
if (isset($aFilter['exclude_type']) and !is_array($aFilter['exclude_type'])) {
$aFilter['exclude_type']=array($aFilter['exclude_type']);
}
if (isset($aFilter['type']) and !is_array($aFilter['type'])) {
$aFilter['type']=array($aFilter['type']);
}
if (isset($aFilter['id']) and !is_array($aFilter['id'])) {
$aFilter['id']=array($aFilter['id']);
}
/**
* Получает список блогов по фильтру
*
* @param array $aFilter Фильтр выборки
* @param array $aOrder Сортировка
* @param int $iCount Возвращает общее количество элментов
* @param int $iCurrPage Номер текущей страницы
* @param int $iPerPage Количество элементов на одну страницу
* @return array
*/
public function GetBlogsByFilter($aFilter, $aOrder, &$iCount, $iCurrPage, $iPerPage)
{
$aOrderAllow = array('blog_id', 'blog_title', 'blog_rating', 'blog_count_user', 'blog_count_topic');
$sOrder = '';
foreach ($aOrder as $key => $value) {
if (!in_array($key, $aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value, array('asc', 'desc'))) {
$sOrder .= " {$key} {$value},";
}
}
$sOrder = trim($sOrder, ',');
if ($sOrder == '') {
$sOrder = ' blog_id desc ';
}
$sql = "SELECT
if (isset($aFilter['exclude_type']) and !is_array($aFilter['exclude_type'])) {
$aFilter['exclude_type'] = array($aFilter['exclude_type']);
}
if (isset($aFilter['type']) and !is_array($aFilter['type'])) {
$aFilter['type'] = array($aFilter['type']);
}
if (isset($aFilter['id']) and !is_array($aFilter['id'])) {
$aFilter['id'] = array($aFilter['id']);
}
$sql = "SELECT
blog_id
FROM
".Config::Get('db.table.blog')."
" . Config::Get('db.table.blog') . "
WHERE
1 = 1
{ AND blog_id IN (?a) }
@ -539,20 +594,21 @@ class ModuleBlog_MapperBlog extends Mapper {
ORDER by {$sOrder}
LIMIT ?d, ?d ;
";
$aResult=array();
if ($aRows=$this->oDb->selectPage($iCount,$sql,
(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,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aRow) {
$aResult[]=$aRow['blog_id'];
}
}
return $aResult;
}
$aResult = array();
if ($aRows = $this->oDb->selectPage($iCount, $sql,
(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,
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aRow) {
$aResult[] = $aRow['blog_id'];
}
}
return $aResult;
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,192 +25,212 @@
* @package application.modules.category
* @since 2.0
*/
class ModuleCategory_BehaviorEntity extends Behavior {
/**
* Дефолтные параметры
*
* @var array
*/
protected $aParams=array(
// Уникальный код
'target_type'=>'',
// Имя инпута (select) на форме, который содержит список категорий
'form_field'=>'categories',
// Автоматически брать текущую категорию из реквеста
'form_fill_current_from_request'=>true,
// Возможность выбирать несколько категорий
'multiple'=>false,
class ModuleCategory_BehaviorEntity extends Behavior
{
/**
* Дефолтные параметры
*
* @var array
*/
protected $aParams = array(
// Уникальный код
'target_type' => '',
// Имя инпута (select) на форме, который содержит список категорий
'form_field' => 'categories',
// Автоматически брать текущую категорию из реквеста
'form_fill_current_from_request' => true,
// Возможность выбирать несколько категорий
'multiple' => false,
// Автоматическая валидация категорий (актуально при ORM)
'validate_enable' => true,
// Поле сущности, в котором хранятся категории. Если null, то используется имя из form_field
'validate_field' => null,
// Обязательное заполнение категории
'validate_require' => false,
// Получать значение валидации не из сущности, а из реквеста (используется поле form_field)
'validate_from_request' => false,
// Минимальное количество категорий, доступное для выбора
'validate_min' => 1,
// Максимальное количество категорий, доступное для выбора
'validate_max' => 5,
// Возможность выбрать только те категории, у которых нет дочерних
'validate_only_without_children' => false,
// Колбек для подсчета количества объектов у категории. Необходим, например, если необходимо учитывать объекты только с определенным статусом (доступен для публикации).
// Указывать можно строкой с полным вызовом метода модуля, например, "PluginArticle_Main_GetCountArticle"
// В качестве параметров передается список ID категорий и тип
'callback_count_target' => null,
);
/**
* Список хуков
*
* @var array
*/
protected $aHooks = array(
'validate_after' => 'CallbackValidateAfter',
'after_save' => 'CallbackAfterSave',
'after_delete' => 'CallbackAfterDelete',
);
// Автоматическая валидация категорий (актуально при ORM)
'validate_enable'=>true,
// Поле сущности, в котором хранятся категории. Если null, то используется имя из form_field
'validate_field'=>null,
// Обязательное заполнение категории
'validate_require'=>false,
// Получать значение валидации не из сущности, а из реквеста (используется поле form_field)
'validate_from_request'=>false,
// Минимальное количество категорий, доступное для выбора
'validate_min'=>1,
// Максимальное количество категорий, доступное для выбора
'validate_max'=>5,
// Возможность выбрать только те категории, у которых нет дочерних
'validate_only_without_children'=>false,
/**
* Инициализация
*/
protected function Init()
{
parent::Init();
if (!$this->getParam('validate_field')) {
$this->aParams['validate_field'] = $this->getParam('form_field');
}
}
// Колбек для подсчета количества объектов у категории. Необходим, например, если необходимо учитывать объекты только с определенным статусом (доступен для публикации).
// Указывать можно строкой с полным вызовом метода модуля, например, "PluginArticle_Main_GetCountArticle"
// В качестве параметров передается список ID категорий и тип
'callback_count_target'=>null,
);
/**
* Список хуков
*
* @var array
*/
protected $aHooks=array(
'validate_after'=>'CallbackValidateAfter',
'after_save'=>'CallbackAfterSave',
'after_delete'=>'CallbackAfterDelete',
);
/**
* Инициализация
*/
protected function Init() {
parent::Init();
if (!$this->getParam('validate_field')) {
$this->aParams['validate_field']=$this->getParam('form_field');
}
}
/**
* Коллбэк
* Выполняется при инициализации сущности
*
* @param $aParams
*/
public function CallbackValidateAfter($aParams) {
if ($aParams['bResult'] and $this->getParam('validate_enable')) {
$aFields=$aParams['aFields'];
if (is_null($aFields) or in_array($this->getParam('validate_field'),$aFields)) {
$oValidator=$this->Validate_CreateValidator('categories_check',$this,$this->getParam('validate_field'));
$oValidator->validateEntity($this->oObject,$aFields);
$aParams['bResult']=!$this->oObject->_hasValidateErrors();
}
}
}
/**
* Коллбэк
* Выполняется после сохранения сущности
*/
public function CallbackAfterSave() {
$this->Category_SaveCategories($this->oObject,$this->getParam('target_type'),$this->getParam('callback_count_target'));
}
/**
* Коллбэк
* Выполняется после удаления сущности
*/
public function CallbackAfterDelete() {
$this->Category_RemoveCategories($this->oObject,$this->getParam('target_type'),$this->getParam('callback_count_target'));
}
/**
* Дополнительный метод для сущности
* Запускает валидацию дополнительных полей
*
* @param $mValue
*
* @return bool|string
*/
public function ValidateCategoriesCheck($mValue) {
/**
* Проверяем тип категрий
*/
if (!$oTypeCategory=$this->Category_GetTypeByTargetType($this->getParam('target_type'))) {
return 'Неверный тип категорий';
}
/**
* Коллбэк
* Выполняется при инициализации сущности
*
* @param $aParams
*/
public function CallbackValidateAfter($aParams)
{
if ($aParams['bResult'] and $this->getParam('validate_enable')) {
$aFields = $aParams['aFields'];
if (is_null($aFields) or in_array($this->getParam('validate_field'), $aFields)) {
$oValidator = $this->Validate_CreateValidator('categories_check', $this,
$this->getParam('validate_field'));
$oValidator->validateEntity($this->oObject, $aFields);
$aParams['bResult'] = !$this->oObject->_hasValidateErrors();
}
}
}
if ($this->getParam('validate_from_request')) {
$mValue=getRequest($this->getParam('form_field'));
}
/**
* Значение может быть числом, массивом, строкой с разделением через запятую
*/
if (!is_array($mValue)) {
if ($this->getParam('multiple')) {
$mValue=explode(',',$mValue);
} else {
$mValue=array($mValue);
}
}
/**
* Проверяем наличие категорий в БД
*/
$aCategories=$this->Category_ValidateCategoryArray($mValue,$oTypeCategory->getId(),true);
if (!$aCategories) {
$aCategories=array();
}
/**
* Коллбэк
* Выполняется после сохранения сущности
*/
public function CallbackAfterSave()
{
$this->Category_SaveCategories($this->oObject, $this->getParam('target_type'),
$this->getParam('callback_count_target'));
}
if ($this->getParam('validate_require') and !$aCategories) {
return 'Необходимо выбрать категорию';
}
if (!$this->getParam('multiple') and count($aCategories)>1) {
$aCategories=array_slice($aCategories,0,1);
}
if ($this->getParam('multiple') and $aCategories and ( count($aCategories)<$this->getParam('validate_min') or count($aCategories)>$this->getParam('validate_max'))) {
return 'Количество категорий должно быть от '.$this->getParam('validate_min').' до '.$this->getParam('validate_max');
}
if ($this->getParam('validate_only_without_children')) {
foreach($aCategories as $oCategory) {
if ($oCategory->getChildren()) {
return 'Для выбора доступны только конечные категории';
}
}
}
/**
* Сохраняем необходимый список категорий для последующего сохранения в БД
*/
$this->oObject->_setData(array('_categories_for_save'=>array_keys($aCategories)));
return true;
}
/**
* Возвращает список категорий сущности
*
* @return array
*/
public function getCategories() {
return $this->Category_GetEntityCategories($this->oObject,$this->getCategoryTargetType());
}
/**
* Возвращает количество категорий
*
* @return array
*/
public function getCountCategories() {
return count($this->getCategories());
}
/**
* Возвращает одну категорию сущности
* Если объект может иметь несколько категорий, то вернется первая
*
* @return ModuleCategory_EntityCategory|null
*/
public function getCategory() {
$aCategories=$this->getCategories();
$oCategory=reset($aCategories);
return $oCategory ? $oCategory : null;
}
/**
* Возвращает тип объекта для категорий
*
* @return string
*/
public function getCategoryTargetType() {
if ($sType=$this->getParam('target_type')) {
return $sType;
}
/**
* Иначе дополнительно смотрим на наличие данного метода у сущности
* Это необходимо, если тип вычисляется динамически по какой-то своей логике
*/
if (func_method_exists($this->oObject,'getCategoryTargetType','public')) {
return call_user_func(array($this->oObject,'getCategoryTargetType'));
}
}
/**
* Коллбэк
* Выполняется после удаления сущности
*/
public function CallbackAfterDelete()
{
$this->Category_RemoveCategories($this->oObject, $this->getParam('target_type'),
$this->getParam('callback_count_target'));
}
/**
* Дополнительный метод для сущности
* Запускает валидацию дополнительных полей
*
* @param $mValue
*
* @return bool|string
*/
public function ValidateCategoriesCheck($mValue)
{
/**
* Проверяем тип категрий
*/
if (!$oTypeCategory = $this->Category_GetTypeByTargetType($this->getParam('target_type'))) {
return 'Неверный тип категорий';
}
if ($this->getParam('validate_from_request')) {
$mValue = getRequest($this->getParam('form_field'));
}
/**
* Значение может быть числом, массивом, строкой с разделением через запятую
*/
if (!is_array($mValue)) {
if ($this->getParam('multiple')) {
$mValue = explode(',', $mValue);
} else {
$mValue = array($mValue);
}
}
/**
* Проверяем наличие категорий в БД
*/
$aCategories = $this->Category_ValidateCategoryArray($mValue, $oTypeCategory->getId(), true);
if (!$aCategories) {
$aCategories = array();
}
if ($this->getParam('validate_require') and !$aCategories) {
return 'Необходимо выбрать категорию';
}
if (!$this->getParam('multiple') and count($aCategories) > 1) {
$aCategories = array_slice($aCategories, 0, 1);
}
if ($this->getParam('multiple') and $aCategories and (count($aCategories) < $this->getParam('validate_min') or count($aCategories) > $this->getParam('validate_max'))) {
return 'Количество категорий должно быть от ' . $this->getParam('validate_min') . ' до ' . $this->getParam('validate_max');
}
if ($this->getParam('validate_only_without_children')) {
foreach ($aCategories as $oCategory) {
if ($oCategory->getChildren()) {
return 'Для выбора доступны только конечные категории';
}
}
}
/**
* Сохраняем необходимый список категорий для последующего сохранения в БД
*/
$this->oObject->_setData(array('_categories_for_save' => array_keys($aCategories)));
return true;
}
/**
* Возвращает список категорий сущности
*
* @return array
*/
public function getCategories()
{
return $this->Category_GetEntityCategories($this->oObject, $this->getCategoryTargetType());
}
/**
* Возвращает количество категорий
*
* @return array
*/
public function getCountCategories()
{
return count($this->getCategories());
}
/**
* Возвращает одну категорию сущности
* Если объект может иметь несколько категорий, то вернется первая
*
* @return ModuleCategory_EntityCategory|null
*/
public function getCategory()
{
$aCategories = $this->getCategories();
$oCategory = reset($aCategories);
return $oCategory ? $oCategory : null;
}
/**
* Возвращает тип объекта для категорий
*
* @return string
*/
public function getCategoryTargetType()
{
if ($sType = $this->getParam('target_type')) {
return $sType;
}
/**
* Иначе дополнительно смотрим на наличие данного метода у сущности
* Это необходимо, если тип вычисляется динамически по какой-то своей логике
*/
if (func_method_exists($this->oObject, 'getCategoryTargetType', 'public')) {
return call_user_func(array($this->oObject, 'getCategoryTargetType'));
}
}
}

View file

@ -25,70 +25,83 @@
* @package application.modules.category
* @since 2.0
*/
class ModuleCategory_BehaviorModule extends Behavior {
/**
* Дефолтные параметры
*
* @var array
*/
protected $aParams=array(
'target_type'=>'',
);
/**
* Список хуков
*
* @var array
*/
protected $aHooks=array(
'module_orm_GetItemsByFilter_after'=>array(
'CallbackGetItemsByFilterAfter',1000
),
'module_orm_GetItemsByFilter_before'=>array(
'CallbackGetItemsByFilterBefore',1000
),
'module_orm_GetByFilter_before'=>array(
'CallbackGetItemsByFilterBefore',1000
),
);
class ModuleCategory_BehaviorModule extends Behavior
{
/**
* Дефолтные параметры
*
* @var array
*/
protected $aParams = array(
'target_type' => '',
);
/**
* Список хуков
*
* @var array
*/
protected $aHooks = array(
'module_orm_GetItemsByFilter_after' => array(
'CallbackGetItemsByFilterAfter',
1000
),
'module_orm_GetItemsByFilter_before' => array(
'CallbackGetItemsByFilterBefore',
1000
),
'module_orm_GetByFilter_before' => array(
'CallbackGetItemsByFilterBefore',
1000
),
);
/**
* Модифицирует фильтр в ORM запросе
*
* @param $aParams
*/
public function CallbackGetItemsByFilterAfter($aParams) {
$aEntities=$aParams['aEntities'];
$aFilter=$aParams['aFilter'];
$this->Category_RewriteGetItemsByFilter($aEntities,$aFilter,$this->getParam('target_type'));
}
/**
* Модифицирует результат ORM запроса
*
* @param $aParams
*/
public function CallbackGetItemsByFilterBefore($aParams) {
$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);
}
/**
* Модифицирует фильтр в ORM запросе
*
* @param $aParams
*/
public function CallbackGetItemsByFilterAfter($aParams)
{
$aEntities = $aParams['aEntities'];
$aFilter = $aParams['aFilter'];
$this->Category_RewriteGetItemsByFilter($aEntities, $aFilter, $this->getParam('target_type'));
}
/**
* Модифицирует результат ORM запроса
*
* @param $aParams
*/
public function CallbackGetItemsByFilterBefore($aParams)
{
$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);
}
}

View file

@ -25,226 +25,256 @@
* @package application.modules.category
* @since 2.0
*/
class ModuleCategory_EntityCategory extends EntityORM {
class ModuleCategory_EntityCategory extends EntityORM
{
/**
* Определяем правила валидации
*
* @var array
*/
protected $aValidateRules=array(
array('title','string','max'=>200,'min'=>1,'allowEmpty'=>false),
array('description','string','max'=>5000,'min'=>1,'allowEmpty'=>true),
array('url','regexp','pattern'=>'/^[\w\-_]+$/i','allowEmpty'=>false),
array('order','number','integerOnly'=>true),
array('pid','parent_category'),
array('order','order_check'),
);
/**
* Определяем правила валидации
*
* @var array
*/
protected $aValidateRules = array(
array('title', 'string', 'max' => 200, 'min' => 1, 'allowEmpty' => false),
array('description', 'string', 'max' => 5000, 'min' => 1, 'allowEmpty' => true),
array('url', 'regexp', 'pattern' => '/^[\w\-_]+$/i', 'allowEmpty' => false),
array('order', 'number', 'integerOnly' => true),
array('pid', 'parent_category'),
array('order', 'order_check'),
);
protected $aRelations=array(
'type' => array(self::RELATION_TYPE_BELONGS_TO,'ModuleCategory_EntityType','type_id'),
self::RELATION_TYPE_TREE
);
protected $aRelations = array(
'type' => array(self::RELATION_TYPE_BELONGS_TO, 'ModuleCategory_EntityType', 'type_id'),
self::RELATION_TYPE_TREE
);
/**
* Проверка родительской категории
*
* @param string $sValue Валидируемое значение
* @param array $aParams Параметры
* @return bool
*/
public function ValidateParentCategory($sValue,$aParams) {
if ($this->getPid()) {
if ($oCategory=$this->Category_GetCategoryById($this->getPid())) {
if ($oCategory->getId()==$this->getId()) {
return 'Попытка вложить категорию в саму себя';
}
if ($oCategory->getTypeId()!=$this->getTypeId()) {
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 ValidateOrderCheck($sValue,$aParams) {
if (!$this->getSort()) {
$this->setSort(100);
}
return true;
}
/**
* Выполняется перед удалением
*
* @return bool
*/
protected function beforeDelete() {
if ($bResult=parent::beforeDelete()) {
/**
* Запускаем удаление дочерних категорий
*/
if ($aCildren=$this->getChildren()) {
foreach($aCildren as $oChildren) {
$oChildren->Delete();
}
}
/**
* Удаляем связь с таргетом
*/
if ($aTargets=$this->Category_GetTargetItemsByCategoryId($this->getId())) {
foreach($aTargets as $oTarget) {
$oTarget->Delete();
/**
* TODO: Нужно запустить хук, что мы удалили такую-то связь
*/
}
}
}
return $bResult;
}
/**
* Переопределяем имя поля с родителем
* Т.к. по дефолту в деревьях используется поле parent_id
*
* @return string
*/
public function _getTreeParentKey() {
return 'pid';
}
/**
* Выполняется перед сохранением
*
* @return bool
*/
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
/**
* Возвращает URL категории
* Этот метод необходимо переопределить из плагина и возвращать свой URL для нужного типа категорий
*
* @return string
*/
public function getWebUrl() {
return null;
}
/**
* Возвращает объект типа категории с использованием кеширования на время сессии
*
* @return ModuleCategory_EntityType
*/
public function getTypeByCacheLife() {
$sKey='category_type_'.(string)$this->getTypeId();
if (false===($oType=$this->Cache_GetLife($sKey))) {
$oType=$this->getType();
$this->Cache_SetLife($oType,$sKey);
}
return $oType;
}
/**
* Возвращает URL админки для редактирования
*
* @return string
*/
public function getUrlAdminUpdate() {
return Router::GetPath('admin/categories/'.$this->getTypeByCacheLife()->getTargetType().'/update/'.$this->getId());
}
/**
* Возвращает URL админки для удаления
*
* @return string
*/
public function getUrlAdminRemove() {
return Router::GetPath('admin/categories/'.$this->getTypeByCacheLife()->getTargetType().'/remove/'.$this->getId());
}
/**
* Возвращает список дополнительных данных
*
* @return array|mixed
*/
public function getData() {
$aData=@unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData=array();
}
return $aData;
}
/**
* Устанавливает список дополнительня данных
*
* @param $aRules
*/
public function setData($aRules) {
$this->_aData['data']=@serialize($aRules);
}
/**
* Возвращает данные по конкретному ключу
*
* @param $sKey
*
* @return null
*/
public function getDataOne($sKey) {
$aData=$this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
/**
* Устанваливает данные для конкретного ключа
*
* @param $sKey
* @param $mValue
*/
public function setDataOne($sKey,$mValue) {
$aData=$this->getData();
$aData[$sKey]=$mValue;
$this->setData($aData);
}
/**
* Возвращает сумму значений по ключу для всех потомков, включая себя
*
* @param $sKey
*
* @return null
*/
public function getDataOneSumDescendants($sKey) {
$iResult=$this->getDataOne($sKey);
$aChildren=$this->getDescendants();
foreach($aChildren as $oItem) {
$iResult+=$oItem->getDataOne($sKey);
}
return $iResult;
}
/**
* Возвращает количество таргетов (объектов) для всех потомков, включая себя
*
* @return mixed
*/
public function getCountTargetOfDescendants() {
$iCount=$this->getCountTarget();
$aChildren=$this->getDescendants();
foreach($aChildren as $oItem) {
$iCount+=$oItem->getCountTarget();
}
return $iCount;
}
/**
* Проверка родительской категории
*
* @param string $sValue Валидируемое значение
* @param array $aParams Параметры
* @return bool
*/
public function ValidateParentCategory($sValue, $aParams)
{
if ($this->getPid()) {
if ($oCategory = $this->Category_GetCategoryById($this->getPid())) {
if ($oCategory->getId() == $this->getId()) {
return 'Попытка вложить категорию в саму себя';
}
if ($oCategory->getTypeId() != $this->getTypeId()) {
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 ValidateOrderCheck($sValue, $aParams)
{
if (!$this->getSort()) {
$this->setSort(100);
}
return true;
}
/**
* Выполняется перед удалением
*
* @return bool
*/
protected function beforeDelete()
{
if ($bResult = parent::beforeDelete()) {
/**
* Запускаем удаление дочерних категорий
*/
if ($aCildren = $this->getChildren()) {
foreach ($aCildren as $oChildren) {
$oChildren->Delete();
}
}
/**
* Удаляем связь с таргетом
*/
if ($aTargets = $this->Category_GetTargetItemsByCategoryId($this->getId())) {
foreach ($aTargets as $oTarget) {
$oTarget->Delete();
/**
* TODO: Нужно запустить хук, что мы удалили такую-то связь
*/
}
}
}
return $bResult;
}
/**
* Переопределяем имя поля с родителем
* Т.к. по дефолту в деревьях используется поле parent_id
*
* @return string
*/
public function _getTreeParentKey()
{
return 'pid';
}
/**
* Выполняется перед сохранением
*
* @return bool
*/
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
/**
* Возвращает URL категории
* Этот метод необходимо переопределить из плагина и возвращать свой URL для нужного типа категорий
*
* @return string
*/
public function getWebUrl()
{
return null;
}
/**
* Возвращает объект типа категории с использованием кеширования на время сессии
*
* @return ModuleCategory_EntityType
*/
public function getTypeByCacheLife()
{
$sKey = 'category_type_' . (string)$this->getTypeId();
if (false === ($oType = $this->Cache_GetLife($sKey))) {
$oType = $this->getType();
$this->Cache_SetLife($oType, $sKey);
}
return $oType;
}
/**
* Возвращает URL админки для редактирования
*
* @return string
*/
public function getUrlAdminUpdate()
{
return Router::GetPath('admin/categories/' . $this->getTypeByCacheLife()->getTargetType() . '/update/' . $this->getId());
}
/**
* Возвращает URL админки для удаления
*
* @return string
*/
public function getUrlAdminRemove()
{
return Router::GetPath('admin/categories/' . $this->getTypeByCacheLife()->getTargetType() . '/remove/' . $this->getId());
}
/**
* Возвращает список дополнительных данных
*
* @return array|mixed
*/
public function getData()
{
$aData = @unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData = array();
}
return $aData;
}
/**
* Устанавливает список дополнительня данных
*
* @param $aRules
*/
public function setData($aRules)
{
$this->_aData['data'] = @serialize($aRules);
}
/**
* Возвращает данные по конкретному ключу
*
* @param $sKey
*
* @return null
*/
public function getDataOne($sKey)
{
$aData = $this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
/**
* Устанваливает данные для конкретного ключа
*
* @param $sKey
* @param $mValue
*/
public function setDataOne($sKey, $mValue)
{
$aData = $this->getData();
$aData[$sKey] = $mValue;
$this->setData($aData);
}
/**
* Возвращает сумму значений по ключу для всех потомков, включая себя
*
* @param $sKey
*
* @return null
*/
public function getDataOneSumDescendants($sKey)
{
$iResult = $this->getDataOne($sKey);
$aChildren = $this->getDescendants();
foreach ($aChildren as $oItem) {
$iResult += $oItem->getDataOne($sKey);
}
return $iResult;
}
/**
* Возвращает количество таргетов (объектов) для всех потомков, включая себя
*
* @return mixed
*/
public function getCountTargetOfDescendants()
{
$iCount = $this->getCountTarget();
$aChildren = $this->getDescendants();
foreach ($aChildren as $oItem) {
$iCount += $oItem->getCountTarget();
}
return $iCount;
}
}

View file

@ -25,23 +25,23 @@
* @package application.modules.category
* @since 2.0
*/
class ModuleCategory_EntityTarget extends EntityORM {
class ModuleCategory_EntityTarget extends EntityORM
{
protected $aRelations=array(
);
protected $aRelations = array();
/**
* Выполняется перед сохранением
*
* @return bool
*/
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
/**
* Выполняется перед сохранением
*
* @return bool
*/
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
}

View file

@ -25,56 +25,62 @@
* @package application.modules.category
* @since 2.0
*/
class ModuleCategory_EntityType extends EntityORM {
class ModuleCategory_EntityType extends EntityORM
{
protected $aRelations=array(
protected $aRelations = array();
);
/**
* Выполняется перед сохранением
*
* @return bool
*/
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
} else {
$this->setDateUpdate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
/**
* Выполняется перед сохранением
*
* @return bool
*/
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
} else {
$this->setDateUpdate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
/**
* Возвращает список дополнительных параметров
*
* @return array|mixed
*/
public function getParams() {
$aData=@unserialize($this->_getDataOne('params'));
if (!$aData) {
$aData=array();
}
return $aData;
}
/**
* Устанавливает список дополнительных параметров
*
* @param $aParams
*/
public function setParams($aParams) {
$this->_aData['params']=@serialize($aParams);
}
/**
* Возвращает конкретный параметр
*
* @param $sName
*
* @return null
*/
public function getParam($sName) {
$aParams=$this->getParams();
return isset($aParams[$sName]) ? $aParams[$sName] : null;
}
/**
* Возвращает список дополнительных параметров
*
* @return array|mixed
*/
public function getParams()
{
$aData = @unserialize($this->_getDataOne('params'));
if (!$aData) {
$aData = array();
}
return $aData;
}
/**
* Устанавливает список дополнительных параметров
*
* @param $aParams
*/
public function setParams($aParams)
{
$this->_aData['params'] = @serialize($aParams);
}
/**
* Возвращает конкретный параметр
*
* @param $sName
*
* @return null
*/
public function getParam($sName)
{
$aParams = $this->getParams();
return isset($aParams[$sName]) ? $aParams[$sName] : null;
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,449 +25,554 @@
* @package application.modules.comment
* @since 1.0
*/
class ModuleComment_EntityComment extends Entity {
/**
* Возвращает ID коммента
*
* @return int|null
*/
public function getId() {
return $this->_getDataOne('comment_id');
}
/**
* Возвращает ID родительского коммента
*
* @return int|null
*/
public function getPid() {
return $this->_getDataOne('comment_pid');
}
/**
* Возвращает значение left для дерева nested set
*
* @return int|null
*/
public function getLeft() {
return $this->_getDataOne('comment_left');
}
/**
* Возвращает значение right для дерева nested set
*
* @return int|null
*/
public function getRight() {
return $this->_getDataOne('comment_right');
}
/**
* Возвращает ID владельца
*
* @return int|null
*/
public function getTargetId() {
return $this->_getDataOne('target_id');
}
/**
* Возвращает тип владельца
*
* @return string|null
*/
public function getTargetType() {
return $this->_getDataOne('target_type');
}
/**
* Возвращет ID родителя владельца
*
* @return int|null
*/
public function getTargetParentId() {
return $this->_getDataOne('target_parent_id') ? $this->_getDataOne('target_parent_id') : 0;
}
/**
* Возвращает ID пользователя, автора комментария
*
* @return int|null
*/
public function getUserId() {
return $this->_getDataOne('user_id');
}
/**
* Возвращает текст комментария
*
* @return string|null
*/
public function getText() {
return $this->_getDataOne('comment_text');
}
/**
* Возвращает исходный текст комментария
*
* @return string|null
*/
public function getTextSource() {
return $this->_getDataOne('comment_text_source') ? $this->_getDataOne('comment_text_source') : '';
}
/**
* Возвращает дату комментария
*
* @return string|null
*/
public function getDate() {
return $this->_getDataOne('comment_date');
}
/**
* Возвращает дату последнего редактирования комментария
*
* @return string|null
*/
public function getDateEdit() {
return $this->_getDataOne('comment_date_edit');
}
/**
* Возвращает IP пользователя
*
* @return string|null
*/
public function getUserIp() {
return $this->_getDataOne('comment_user_ip');
}
/**
* Возвращает рейтинг комментария
*
* @return string
*/
public function getRating() {
return number_format(round($this->_getDataOne('comment_rating'),2), 0, '.', '');
}
/**
* Возвращает количество проголосовавших
*
* @return int|null
*/
public function getCountVote() {
return $this->_getDataOne('comment_count_vote');
}
/**
* Возвращает количество редактирований комментария
*
* @return int|null
*/
public function getCountEdit() {
return $this->_getDataOne('comment_count_edit');
}
/**
* Возвращает флаг удаленного комментария
*
* @return int|null
*/
public function getDelete() {
return $this->_getDataOne('comment_delete');
}
/**
* Возвращает флаг опубликованного комментария
*
* @return int
*/
public function getPublish() {
return $this->_getDataOne('comment_publish') ? 1 : 0;
}
/**
* Возвращает хеш комментария
*
* @return string|null
*/
public function getTextHash() {
return $this->_getDataOne('comment_text_hash');
}
class ModuleComment_EntityComment extends Entity
{
/**
* Возвращает ID коммента
*
* @return int|null
*/
public function getId()
{
return $this->_getDataOne('comment_id');
}
/**
* Возвращает уровень вложенности комментария
*
* @return int|null
*/
public function getLevel() {
return $this->_getDataOne('comment_level');
}
/**
* Проверяет является ли комментарий плохим
*
* @return bool
*/
public function isBad() {
if ($this->getRating()<=Config::Get('module.comment.bad')) {
return true;
}
return false;
}
/**
* Возвращает объект пользователя
*
* @return ModuleUser_EntityUser|null
*/
public function getUser() {
return $this->_getDataOne('user');
}
/**
* Возвращает объект владельца
*
* @return mixed|null
*/
public function getTarget() {
return $this->_getDataOne('target');
}
/**
* Возвращает объект голосования
*
* @return ModuleVote_EntityVote|null
*/
public function getVote() {
return $this->_getDataOne('vote');
}
/**
* Проверяет является ли комментарий избранным у текущего пользователя
*
* @return bool|null
*/
public function getIsFavourite() {
return $this->_getDataOne('comment_is_favourite');
}
/**
* Возвращает количество избранного
*
* @return int|null
*/
public function getCountFavourite() {
return $this->_getDataOne('comment_count_favourite');
}
/**
* Проверка на разрешение редактировать комментарий
*
* @return mixed
*/
public function isAllowEdit() {
return $this->ACL_IsAllowEditComment($this,$this->User_GetUserCurrent());
}
/**
* Возвращает количество секунд в течении которых возможно редактирование
*
* @return int
*/
public function getEditTimeRemaining() {
$oUser=$this->User_GetUserCurrent();
if (($oUser and $oUser->isAdministrator()) or !Config::Get('acl.update.comment.limit_time')) {
return 0;
}
$iTime=Config::Get('acl.update.comment.limit_time')-(time()-strtotime($this->getDate()));
return $iTime>0 ? $iTime : 0;
}
/**
* Проверка на разрешение удалить комментарий
*
* @return mixed
*/
public function isAllowDelete() {
return $this->ACL_IsAllowDeleteComment($this,$this->User_GetUserCurrent());
}
/**
* Возвращает ID родительского коммента
*
* @return int|null
*/
public function getPid()
{
return $this->_getDataOne('comment_pid');
}
/**
* Возвращает значение left для дерева nested set
*
* @return int|null
*/
public function getLeft()
{
return $this->_getDataOne('comment_left');
}
/**
* Возвращает значение right для дерева nested set
*
* @return int|null
*/
public function getRight()
{
return $this->_getDataOne('comment_right');
}
/**
* Возвращает ID владельца
*
* @return int|null
*/
public function getTargetId()
{
return $this->_getDataOne('target_id');
}
/**
* Возвращает тип владельца
*
* @return string|null
*/
public function getTargetType()
{
return $this->_getDataOne('target_type');
}
/**
* Возвращет ID родителя владельца
*
* @return int|null
*/
public function getTargetParentId()
{
return $this->_getDataOne('target_parent_id') ? $this->_getDataOne('target_parent_id') : 0;
}
/**
* Возвращает ID пользователя, автора комментария
*
* @return int|null
*/
public function getUserId()
{
return $this->_getDataOne('user_id');
}
/**
* Возвращает текст комментария
*
* @return string|null
*/
public function getText()
{
return $this->_getDataOne('comment_text');
}
/**
* Возвращает исходный текст комментария
*
* @return string|null
*/
public function getTextSource()
{
return $this->_getDataOne('comment_text_source') ? $this->_getDataOne('comment_text_source') : '';
}
/**
* Возвращает дату комментария
*
* @return string|null
*/
public function getDate()
{
return $this->_getDataOne('comment_date');
}
/**
* Возвращает дату последнего редактирования комментария
*
* @return string|null
*/
public function getDateEdit()
{
return $this->_getDataOne('comment_date_edit');
}
/**
* Возвращает IP пользователя
*
* @return string|null
*/
public function getUserIp()
{
return $this->_getDataOne('comment_user_ip');
}
/**
* Возвращает рейтинг комментария
*
* @return string
*/
public function getRating()
{
return number_format(round($this->_getDataOne('comment_rating'), 2), 0, '.', '');
}
/**
* Возвращает количество проголосовавших
*
* @return int|null
*/
public function getCountVote()
{
return $this->_getDataOne('comment_count_vote');
}
/**
* Возвращает количество редактирований комментария
*
* @return int|null
*/
public function getCountEdit()
{
return $this->_getDataOne('comment_count_edit');
}
/**
* Возвращает флаг удаленного комментария
*
* @return int|null
*/
public function getDelete()
{
return $this->_getDataOne('comment_delete');
}
/**
* Возвращает флаг опубликованного комментария
*
* @return int
*/
public function getPublish()
{
return $this->_getDataOne('comment_publish') ? 1 : 0;
}
/**
* Возвращает хеш комментария
*
* @return string|null
*/
public function getTextHash()
{
return $this->_getDataOne('comment_text_hash');
}
/**
* Возвращает уровень вложенности комментария
*
* @return int|null
*/
public function getLevel()
{
return $this->_getDataOne('comment_level');
}
/**
* Проверяет является ли комментарий плохим
*
* @return bool
*/
public function isBad()
{
if ($this->getRating() <= Config::Get('module.comment.bad')) {
return true;
}
return false;
}
/**
* Возвращает объект пользователя
*
* @return ModuleUser_EntityUser|null
*/
public function getUser()
{
return $this->_getDataOne('user');
}
/**
* Возвращает объект владельца
*
* @return mixed|null
*/
public function getTarget()
{
return $this->_getDataOne('target');
}
/**
* Возвращает объект голосования
*
* @return ModuleVote_EntityVote|null
*/
public function getVote()
{
return $this->_getDataOne('vote');
}
/**
* Проверяет является ли комментарий избранным у текущего пользователя
*
* @return bool|null
*/
public function getIsFavourite()
{
return $this->_getDataOne('comment_is_favourite');
}
/**
* Возвращает количество избранного
*
* @return int|null
*/
public function getCountFavourite()
{
return $this->_getDataOne('comment_count_favourite');
}
/**
* Проверка на разрешение редактировать комментарий
*
* @return mixed
*/
public function isAllowEdit()
{
return $this->ACL_IsAllowEditComment($this, $this->User_GetUserCurrent());
}
/**
* Возвращает количество секунд в течении которых возможно редактирование
*
* @return int
*/
public function getEditTimeRemaining()
{
$oUser = $this->User_GetUserCurrent();
if (($oUser and $oUser->isAdministrator()) or !Config::Get('acl.update.comment.limit_time')) {
return 0;
}
$iTime = Config::Get('acl.update.comment.limit_time') - (time() - strtotime($this->getDate()));
return $iTime > 0 ? $iTime : 0;
}
/**
* Проверка на разрешение удалить комментарий
*
* @return mixed
*/
public function isAllowDelete()
{
return $this->ACL_IsAllowDeleteComment($this, $this->User_GetUserCurrent());
}
/**
* Устанавливает ID комментария
*
* @param int $data
*/
public function setId($data) {
$this->_aData['comment_id']=$data;
}
/**
* Устанавливает ID родительского комментария
*
* @param int $data
*/
public function setPid($data) {
$this->_aData['comment_pid']=$data;
}
/**
* Устанавливает значени left для дерева nested set
*
* @param int $data
*/
public function setLeft($data) {
$this->_aData['comment_left']=$data;
}
/**
* Устанавливает значени right для дерева nested set
*
* @param int $data
*/
public function setRight($data) {
$this->_aData['comment_right']=$data;
}
/**
* Устанавливает ID владельца
*
* @param int $data
*/
public function setTargetId($data) {
$this->_aData['target_id']=$data;
}
/**
* Устанавливает тип владельца
*
* @param string $data
*/
public function setTargetType($data) {
$this->_aData['target_type']=$data;
}
/**
* Устанавливает ID родителя владельца
*
* @param int $data
*/
public function setTargetParentId($data) {
$this->_aData['target_parent_id']=$data;
}
/**
* Устанавливает ID пользователя
*
* @param int $data
*/
public function setUserId($data) {
$this->_aData['user_id']=$data;
}
/**
* Устанавливает текст комментария
*
* @param string $data
*/
public function setText($data) {
$this->_aData['comment_text']=$data;
}
/**
* Устанавливает исходный текст комментария
*
* @param string $data
*/
public function setTextSource($data) {
$this->_aData['comment_text_source']=$data;
}
/**
* Устанавливает дату комментария
*
* @param string $data
*/
public function setDate($data) {
$this->_aData['comment_date']=$data;
}
/**
* Устанавливает дату последнего редактирования комментария
*
* @param string $data
*/
public function setDateEdit($data) {
$this->_aData['comment_date_edit']=$data;
}
/**
* Устанавливает IP пользователя
*
* @param string $data
*/
public function setUserIp($data) {
$this->_aData['comment_user_ip']=$data;
}
/**
* Устанавливает рейтинг комментария
*
* @param float $data
*/
public function setRating($data) {
$this->_aData['comment_rating']=$data;
}
/**
* Устанавливает количество проголосавших
*
* @param int $data
*/
public function setCountVote($data) {
$this->_aData['comment_count_vote']=$data;
}
/**
* Устанавливает количество редактирований комментария
*
* @param int $data
*/
public function setCountEdit($data) {
$this->_aData['comment_count_edit']=$data;
}
/**
* Устанавливает флаг удаленности комментария
*
* @param int $data
*/
public function setDelete($data) {
$this->_aData['comment_delete']=$data;
}
/**
* Устанавливает флаг публикации
*
* @param int $data
*/
public function setPublish($data) {
$this->_aData['comment_publish']=$data;
}
/**
* Устанавливает хеш комментария
*
* @param strign $data
*/
public function setTextHash($data) {
$this->_aData['comment_text_hash']=$data;
}
/**
* Устанавливает ID комментария
*
* @param int $data
*/
public function setId($data)
{
$this->_aData['comment_id'] = $data;
}
/**
* Устанавливает уровень вложенности комментария
*
* @param int $data
*/
public function setLevel($data) {
$this->_aData['comment_level']=$data;
}
/**
* Устаналвает объект пользователя
*
* @param ModuleUser_EntityUser $data
*/
public function setUser($data) {
$this->_aData['user']=$data;
}
/**
* Устанавливает объект владельца
*
* @param mixed $data
*/
public function setTarget($data) {
$this->_aData['target']=$data;
}
/**
* Устанавливает объект голосования
*
* @param ModuleVote_EntityVote $data
*/
public function setVote($data) {
$this->_aData['vote']=$data;
}
/**
* Устанавливает факт нахождения комментария в избранном у текущего пользователя
*
* @param bool $data
*/
public function setIsFavourite($data) {
$this->_aData['comment_is_favourite']=$data;
}
/**
* Устанавливает количество избранного
*
* @param int $data
*/
public function setCountFavourite($data) {
$this->_aData['comment_count_favourite']=$data;
}
/**
* Устанавливает ID родительского комментария
*
* @param int $data
*/
public function setPid($data)
{
$this->_aData['comment_pid'] = $data;
}
/**
* Устанавливает значени left для дерева nested set
*
* @param int $data
*/
public function setLeft($data)
{
$this->_aData['comment_left'] = $data;
}
/**
* Устанавливает значени right для дерева nested set
*
* @param int $data
*/
public function setRight($data)
{
$this->_aData['comment_right'] = $data;
}
/**
* Устанавливает ID владельца
*
* @param int $data
*/
public function setTargetId($data)
{
$this->_aData['target_id'] = $data;
}
/**
* Устанавливает тип владельца
*
* @param string $data
*/
public function setTargetType($data)
{
$this->_aData['target_type'] = $data;
}
/**
* Устанавливает ID родителя владельца
*
* @param int $data
*/
public function setTargetParentId($data)
{
$this->_aData['target_parent_id'] = $data;
}
/**
* Устанавливает ID пользователя
*
* @param int $data
*/
public function setUserId($data)
{
$this->_aData['user_id'] = $data;
}
/**
* Устанавливает текст комментария
*
* @param string $data
*/
public function setText($data)
{
$this->_aData['comment_text'] = $data;
}
/**
* Устанавливает исходный текст комментария
*
* @param string $data
*/
public function setTextSource($data)
{
$this->_aData['comment_text_source'] = $data;
}
/**
* Устанавливает дату комментария
*
* @param string $data
*/
public function setDate($data)
{
$this->_aData['comment_date'] = $data;
}
/**
* Устанавливает дату последнего редактирования комментария
*
* @param string $data
*/
public function setDateEdit($data)
{
$this->_aData['comment_date_edit'] = $data;
}
/**
* Устанавливает IP пользователя
*
* @param string $data
*/
public function setUserIp($data)
{
$this->_aData['comment_user_ip'] = $data;
}
/**
* Устанавливает рейтинг комментария
*
* @param float $data
*/
public function setRating($data)
{
$this->_aData['comment_rating'] = $data;
}
/**
* Устанавливает количество проголосавших
*
* @param int $data
*/
public function setCountVote($data)
{
$this->_aData['comment_count_vote'] = $data;
}
/**
* Устанавливает количество редактирований комментария
*
* @param int $data
*/
public function setCountEdit($data)
{
$this->_aData['comment_count_edit'] = $data;
}
/**
* Устанавливает флаг удаленности комментария
*
* @param int $data
*/
public function setDelete($data)
{
$this->_aData['comment_delete'] = $data;
}
/**
* Устанавливает флаг публикации
*
* @param int $data
*/
public function setPublish($data)
{
$this->_aData['comment_publish'] = $data;
}
/**
* Устанавливает хеш комментария
*
* @param strign $data
*/
public function setTextHash($data)
{
$this->_aData['comment_text_hash'] = $data;
}
/**
* Устанавливает уровень вложенности комментария
*
* @param int $data
*/
public function setLevel($data)
{
$this->_aData['comment_level'] = $data;
}
/**
* Устаналвает объект пользователя
*
* @param ModuleUser_EntityUser $data
*/
public function setUser($data)
{
$this->_aData['user'] = $data;
}
/**
* Устанавливает объект владельца
*
* @param mixed $data
*/
public function setTarget($data)
{
$this->_aData['target'] = $data;
}
/**
* Устанавливает объект голосования
*
* @param ModuleVote_EntityVote $data
*/
public function setVote($data)
{
$this->_aData['vote'] = $data;
}
/**
* Устанавливает факт нахождения комментария в избранном у текущего пользователя
*
* @param bool $data
*/
public function setIsFavourite($data)
{
$this->_aData['comment_is_favourite'] = $data;
}
/**
* Устанавливает количество избранного
*
* @param int $data
*/
public function setCountFavourite($data)
{
$this->_aData['comment_count_favourite'] = $data;
}
}

View file

@ -25,70 +25,85 @@
* @package application.modules.comment
* @since 1.0
*/
class ModuleComment_EntityCommentOnline extends Entity {
/**
* Возвращает ID владельца
*
* @return int|null
*/
public function getTargetId() {
return $this->_getDataOne('target_id');
}
/**
* Возвращает тип владельца
*
* @return string|null
*/
public function getTargetType() {
return $this->_getDataOne('target_type');
}
/**
* Возвращает ID комментария
*
* @return int|null
*/
public function getCommentId() {
return $this->_getDataOne('comment_id');
}
/**
* Возвращает ID родителя владельца
*
* @return int
*/
public function getTargetParentId() {
return $this->_getDataOne('target_parent_id') ? $this->_getDataOne('target_parent_id') : 0;
}
class ModuleComment_EntityCommentOnline extends Entity
{
/**
* Возвращает ID владельца
*
* @return int|null
*/
public function getTargetId()
{
return $this->_getDataOne('target_id');
}
/**
* Устанавливает ID владельца
*
* @param int $data
*/
public function setTargetId($data) {
$this->_aData['target_id']=$data;
}
/**
* Устанавливает тип владельца
*
* @param string $data
*/
public function setTargetType($data) {
$this->_aData['target_type']=$data;
}
/**
* Устанавливает ID комментария
*
* @param int $data
*/
public function setCommentId($data) {
$this->_aData['comment_id']=$data;
}
/**
* Устанавливает ID родителя владельца
*
* @param int $data
*/
public function setTargetParentId($data) {
$this->_aData['target_parent_id']=$data;
}
/**
* Возвращает тип владельца
*
* @return string|null
*/
public function getTargetType()
{
return $this->_getDataOne('target_type');
}
/**
* Возвращает ID комментария
*
* @return int|null
*/
public function getCommentId()
{
return $this->_getDataOne('comment_id');
}
/**
* Возвращает ID родителя владельца
*
* @return int
*/
public function getTargetParentId()
{
return $this->_getDataOne('target_parent_id') ? $this->_getDataOne('target_parent_id') : 0;
}
/**
* Устанавливает ID владельца
*
* @param int $data
*/
public function setTargetId($data)
{
$this->_aData['target_id'] = $data;
}
/**
* Устанавливает тип владельца
*
* @param string $data
*/
public function setTargetType($data)
{
$this->_aData['target_type'] = $data;
}
/**
* Устанавливает ID комментария
*
* @param int $data
*/
public function setCommentId($data)
{
$this->_aData['comment_id'] = $data;
}
/**
* Устанавливает ID родителя владельца
*
* @param int $data
*/
public function setTargetParentId($data)
{
$this->_aData['target_parent_id'] = $data;
}
}

View file

@ -25,452 +25,510 @@
* @package application.modules.favourite
* @since 1.0
*/
class ModuleFavourite extends Module {
/**
* Объект маппера
*
* @var ModuleFavourite_MapperFavourite
*/
protected $oMapper;
class ModuleFavourite extends Module
{
/**
* Объект маппера
*
* @var ModuleFavourite_MapperFavourite
*/
protected $oMapper;
/**
* Инициализация
*
*/
public function Init() {
$this->oMapper=Engine::GetMapper(__CLASS__);
}
/**
* Получает информацию о том, найден ли таргет в избранном или нет
*
* @param int $sTargetId ID владельца
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return ModuleFavourite_EntityFavourite|null
*/
public function GetFavourite($sTargetId,$sTargetType,$sUserId) {
if (!is_numeric($sTargetId) or !is_string($sTargetType)) {
return null;
}
$data=$this->GetFavouritesByArray($sTargetId,$sTargetType,$sUserId);
return (isset($data[$sTargetId]))
? $data[$sTargetId]
: null;
}
/**
* Получить список избранного по списку айдишников
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return array
*/
public function GetFavouritesByArray($aTargetId,$sTargetType,$sUserId) {
if (!$aTargetId) {
return array();
}
if (Config::Get('sys.cache.solid')) {
return $this->GetFavouritesByArraySolid($aTargetId,$sTargetType,$sUserId);
}
if (!is_array($aTargetId)) {
$aTargetId=array($aTargetId);
}
$aTargetId=array_unique($aTargetId);
$aFavourite=array();
$aIdNotNeedQuery=array();
/**
* Делаем мульти-запрос к кешу
*/
$aCacheKeys=func_build_cache_keys($aTargetId,"favourite_{$sTargetType}_",'_'.$sUserId);
if (false !== ($data = $this->Cache_Get($aCacheKeys))) {
/**
* проверяем что досталось из кеша
*/
foreach ($aCacheKeys as $sValue => $sKey ) {
if (array_key_exists($sKey,$data)) {
if ($data[$sKey]) {
$aFavourite[$data[$sKey]->getTargetId()]=$data[$sKey];
} else {
$aIdNotNeedQuery[]=$sValue;
}
}
}
}
/**
* Смотрим чего не было в кеше и делаем запрос в БД
*/
$aIdNeedQuery=array_diff($aTargetId,array_keys($aFavourite));
$aIdNeedQuery=array_diff($aIdNeedQuery,$aIdNotNeedQuery);
$aIdNeedStore=$aIdNeedQuery;
if ($data = $this->oMapper->GetFavouritesByArray($aIdNeedQuery,$sTargetType,$sUserId)) {
foreach ($data as $oFavourite) {
/**
* Добавляем к результату и сохраняем в кеш
*/
$aFavourite[$oFavourite->getTargetId()]=$oFavourite;
$this->Cache_Set($oFavourite, "favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$sUserId}", array(), 60*60*24*7);
$aIdNeedStore=array_diff($aIdNeedStore,array($oFavourite->getTargetId()));
}
}
/**
* Сохраняем в кеш запросы не вернувшие результата
*/
foreach ($aIdNeedStore as $sId) {
$this->Cache_Set(null, "favourite_{$sTargetType}_{$sId}_{$sUserId}", array(), 60*60*24*7);
}
/**
* Сортируем результат согласно входящему массиву
*/
$aFavourite=func_array_sort_by_keys($aFavourite,$aTargetId);
return $aFavourite;
}
/**
* Получить список избранного по списку айдишников, но используя единый кеш
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return array
*/
public function GetFavouritesByArraySolid($aTargetId,$sTargetType,$sUserId) {
if (!is_array($aTargetId)) {
$aTargetId=array($aTargetId);
}
$aTargetId=array_unique($aTargetId);
$aFavourites=array();
$s=join(',',$aTargetId);
if (false === ($data = $this->Cache_Get("favourite_{$sTargetType}_{$sUserId}_id_{$s}"))) {
$data = $this->oMapper->GetFavouritesByArray($aTargetId,$sTargetType,$sUserId);
foreach ($data as $oFavourite) {
$aFavourites[$oFavourite->getTargetId()]=$oFavourite;
}
$this->Cache_Set($aFavourites, "favourite_{$sTargetType}_{$sUserId}_id_{$s}", array("favourite_{$sTargetType}_change_user_{$sUserId}"), 60*60*24*1);
return $aFavourites;
}
return $data;
}
/**
* Получает список таргетов из избранного
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetFavouritesByUserId($sUserId,$sTargetType,$iCurrPage,$iPerPage,$aExcludeTarget=array()) {
$s=serialize($aExcludeTarget);
if (false === ($data = $this->Cache_Get("{$sTargetType}_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_{$s}"))) {
$data = array(
'collection' => $this->oMapper->GetFavouritesByUserId($sUserId,$sTargetType,$iCount,$iCurrPage,$iPerPage,$aExcludeTarget),
'count' => $iCount
);
$this->Cache_Set(
$data,
"{$sTargetType}_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_{$s}",
array(
"favourite_{$sTargetType}_change",
"favourite_{$sTargetType}_change_user_{$sUserId}"
),
60*60*24*1
);
}
return $data;
}
/**
* Возвращает число таргетов определенного типа в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetCountFavouritesByUserId($sUserId,$sTargetType,$aExcludeTarget=array()) {
$s=serialize($aExcludeTarget);
if (false === ($data = $this->Cache_Get("{$sTargetType}_count_favourite_user_{$sUserId}_{$s}"))) {
$data = $this->oMapper->GetCountFavouritesByUserId($sUserId,$sTargetType,$aExcludeTarget);
$this->Cache_Set(
$data,
"{$sTargetType}_count_favourite_user_{$sUserId}_{$s}",
array(
"favourite_{$sTargetType}_change",
"favourite_{$sTargetType}_change_user_{$sUserId}"
),
60*60*24*1
);
}
return $data;
}
/**
* Получает список комментариев к записям открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenCommentsByUserId($sUserId,$iCurrPage,$iPerPage) {
if (false === ($data = $this->Cache_Get("comment_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open"))) {
$data = array(
'collection' => $this->oMapper->GetFavouriteOpenCommentsByUserId($sUserId,$iCount,$iCurrPage,$iPerPage),
'count' => $iCount
);
$this->Cache_Set(
$data,
"comment_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open",
array(
"favourite_comment_change",
"favourite_comment_change_user_{$sUserId}"
),
60*60*24*1
);
}
return $data;
}
/**
* Возвращает число комментариев к открытым блогам в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenCommentsByUserId($sUserId) {
if (false === ($data = $this->Cache_Get("comment_count_favourite_user_{$sUserId}_open"))) {
$data = $this->oMapper->GetCountFavouriteOpenCommentsByUserId($sUserId);
$this->Cache_Set(
$data,
"comment_count_favourite_user_{$sUserId}_open",
array(
"favourite_comment_change",
"favourite_comment_change_user_{$sUserId}"
),
60*60*24*1
);
}
return $data;
}
/**
* Получает список топиков из открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenTopicsByUserId($sUserId,$iCurrPage,$iPerPage) {
if (false === ($data = $this->Cache_Get("topic_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open"))) {
$data = array(
'collection' => $this->oMapper->GetFavouriteOpenTopicsByUserId($sUserId,$iCount,$iCurrPage,$iPerPage),
'count' => $iCount
);
$this->Cache_Set(
$data,
"topic_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open",
array(
"favourite_topic_change",
"favourite_topic_change_user_{$sUserId}"
),
60*60*24*1
);
}
return $data;
}
/**
* Возвращает число топиков в открытых блогах из избранного по ID пользователя
*
* @param string $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenTopicsByUserId($sUserId) {
if (false === ($data = $this->Cache_Get("topic_count_favourite_user_{$sUserId}_open"))) {
$data = $this->oMapper->GetCountFavouriteOpenTopicsByUserId($sUserId);
$this->Cache_Set(
$data,
"topic_count_favourite_user_{$sUserId}_open",
array(
"favourite_topic_change",
"favourite_topic_change_user_{$sUserId}"
),
60*60*24*1
);
}
return $data;
}
/**
* Добавляет таргет в избранное
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function AddFavourite(ModuleFavourite_EntityFavourite $oFavourite) {
if (!$oFavourite->getTags()) {
$oFavourite->setTags('');
}
$this->SetFavouriteTags($oFavourite);
//чистим зависимые кеши
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("favourite_{$oFavourite->getTargetType()}_change_user_{$oFavourite->getUserId()}"));
$this->Cache_Delete("favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$oFavourite->getUserId()}");
return $this->oMapper->AddFavourite($oFavourite);
}
/**
* Обновляет запись об избранном
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function UpdateFavourite(ModuleFavourite_EntityFavourite $oFavourite) {
if (!$oFavourite->getTags()) {
$oFavourite->setTags('');
}
$this->SetFavouriteTags($oFavourite);
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("favourite_{$oFavourite->getTargetType()}_change_user_{$oFavourite->getUserId()}"));
$this->Cache_Delete("favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$oFavourite->getUserId()}");
return $this->oMapper->UpdateFavourite($oFavourite);
}
/**
* Устанавливает список тегов для избранного
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @param bool $bAddNew Добавлять новые теги или нет
*/
public function SetFavouriteTags($oFavourite,$bAddNew=true) {
/**
* Удаляем все теги
*/
$this->oMapper->DeleteTags($oFavourite);
/**
* Добавляем новые
*/
if ($bAddNew) {
/**
* Добавляем теги объекта избранного, если есть
*/
if ($aTags=$this->GetTagsTarget($oFavourite->getTargetType(),$oFavourite->getTargetId())) {
foreach($aTags as $sTag) {
$oTag=Engine::GetEntity('ModuleFavourite_EntityTag',$oFavourite->_getData());
$oTag->setText(htmlspecialchars($sTag));
$oTag->setIsUser(0);
$this->oMapper->AddTag($oTag);
}
}
if ($oFavourite->getTags()) {
/**
* Добавляем пользовательские теги
*/
$aTags = $oFavourite->getTagsArray();
foreach ($aTags as $sTag) {
$oTag = Engine::GetEntity('ModuleFavourite_EntityTag', $oFavourite->_getData());
$oTag->setText($sTag); // htmlspecialchars уже используется при установке тегов
$oTag->setIsUser(1);
$this->oMapper->AddTag($oTag);
}
}
}
}
/**
* Удаляет таргет из избранного
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function DeleteFavourite(ModuleFavourite_EntityFavourite $oFavourite) {
$this->SetFavouriteTags($oFavourite,false);
//чистим зависимые кеши
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("favourite_{$oFavourite->getTargetType()}_change_user_{$oFavourite->getUserId()}"));
$this->Cache_Delete("favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$oFavourite->getUserId()}");
return $this->oMapper->DeleteFavourite($oFavourite);
}
/**
* Меняет параметры публикации у таргета
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $iPublish Флаг публикации
* @return bool
*/
public function SetFavouriteTargetPublish($aTargetId,$sTargetType,$iPublish) {
if(!is_array($aTargetId)) $aTargetId = array($aTargetId);
/**
* Инициализация
*
*/
public function Init()
{
$this->oMapper = Engine::GetMapper(__CLASS__);
}
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("favourite_{$sTargetType}_change"));
return $this->oMapper->SetFavouriteTargetPublish($aTargetId,$sTargetType,$iPublish);
}
/**
* Удаляет избранное по списку идентификаторов таргетов
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteFavouriteByTargetId($aTargetId, $sTargetType) {
if(!is_array($aTargetId)) $aTargetId = array($aTargetId);
/**
* Чистим зависимые кеши
*/
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,array("favourite_{$sTargetType}_change"));
$this->DeleteTagByTarget($aTargetId,$sTargetType);
return $this->oMapper->DeleteFavouriteByTargetId($aTargetId,$sTargetType);
}
/**
* Удаление тегов по таргету
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteTagByTarget($aTargetId,$sTargetType) {
return $this->oMapper->DeleteTagByTarget($aTargetId,$sTargetType);
}
/**
* Возвращает список тегов для объекта избранного
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool|array
*/
public function GetTagsTarget($sTargetType,$iTargetId) {
$sMethod = 'GetTagsTarget'.func_camelize($sTargetType);
if (method_exists($this,$sMethod)) {
return $this->$sMethod($iTargetId);
}
return false;
}
/**
* Возвращает наиболее часто используемые теги
*
* @param int $iUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param bool $bIsUser Возвращает все теги ли только пользовательские
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupTags($iUserId,$sTargetType,$bIsUser,$iLimit) {
return $this->oMapper->GetGroupTags($iUserId,$sTargetType,$bIsUser,$iLimit);
}
/**
* Возвращает список тегов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetTags($aFilter,$aOrder,$iCurrPage,$iPerPage) {
return array('collection'=>$this->oMapper->GetTags($aFilter,$aOrder,$iCount,$iCurrPage,$iPerPage),'count'=>$iCount);
}
/**
* Возвращает список тегов для топика, название метода формируется автоматически из GetTagsTarget()
* @see GetTagsTarget
*
* @param int $iTargetId ID владельца
* @return bool|array
*/
public function GetTagsTargetTopic($iTargetId) {
if ($oTopic=$this->Topic_GetTopicById($iTargetId)) {
return $oTopic->getTagsArray();
}
return false;
}
/**
* Получает информацию о том, найден ли таргет в избранном или нет
*
* @param int $sTargetId ID владельца
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return ModuleFavourite_EntityFavourite|null
*/
public function GetFavourite($sTargetId, $sTargetType, $sUserId)
{
if (!is_numeric($sTargetId) or !is_string($sTargetType)) {
return null;
}
$data = $this->GetFavouritesByArray($sTargetId, $sTargetType, $sUserId);
return (isset($data[$sTargetId]))
? $data[$sTargetId]
: null;
}
/**
* Получить список избранного по списку айдишников
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return array
*/
public function GetFavouritesByArray($aTargetId, $sTargetType, $sUserId)
{
if (!$aTargetId) {
return array();
}
if (Config::Get('sys.cache.solid')) {
return $this->GetFavouritesByArraySolid($aTargetId, $sTargetType, $sUserId);
}
if (!is_array($aTargetId)) {
$aTargetId = array($aTargetId);
}
$aTargetId = array_unique($aTargetId);
$aFavourite = array();
$aIdNotNeedQuery = array();
/**
* Делаем мульти-запрос к кешу
*/
$aCacheKeys = func_build_cache_keys($aTargetId, "favourite_{$sTargetType}_", '_' . $sUserId);
if (false !== ($data = $this->Cache_Get($aCacheKeys))) {
/**
* проверяем что досталось из кеша
*/
foreach ($aCacheKeys as $sValue => $sKey) {
if (array_key_exists($sKey, $data)) {
if ($data[$sKey]) {
$aFavourite[$data[$sKey]->getTargetId()] = $data[$sKey];
} else {
$aIdNotNeedQuery[] = $sValue;
}
}
}
}
/**
* Смотрим чего не было в кеше и делаем запрос в БД
*/
$aIdNeedQuery = array_diff($aTargetId, array_keys($aFavourite));
$aIdNeedQuery = array_diff($aIdNeedQuery, $aIdNotNeedQuery);
$aIdNeedStore = $aIdNeedQuery;
if ($data = $this->oMapper->GetFavouritesByArray($aIdNeedQuery, $sTargetType, $sUserId)) {
foreach ($data as $oFavourite) {
/**
* Добавляем к результату и сохраняем в кеш
*/
$aFavourite[$oFavourite->getTargetId()] = $oFavourite;
$this->Cache_Set($oFavourite,
"favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$sUserId}", array(),
60 * 60 * 24 * 7);
$aIdNeedStore = array_diff($aIdNeedStore, array($oFavourite->getTargetId()));
}
}
/**
* Сохраняем в кеш запросы не вернувшие результата
*/
foreach ($aIdNeedStore as $sId) {
$this->Cache_Set(null, "favourite_{$sTargetType}_{$sId}_{$sUserId}", array(), 60 * 60 * 24 * 7);
}
/**
* Сортируем результат согласно входящему массиву
*/
$aFavourite = func_array_sort_by_keys($aFavourite, $aTargetId);
return $aFavourite;
}
/**
* Получить список избранного по списку айдишников, но используя единый кеш
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return array
*/
public function GetFavouritesByArraySolid($aTargetId, $sTargetType, $sUserId)
{
if (!is_array($aTargetId)) {
$aTargetId = array($aTargetId);
}
$aTargetId = array_unique($aTargetId);
$aFavourites = array();
$s = join(',', $aTargetId);
if (false === ($data = $this->Cache_Get("favourite_{$sTargetType}_{$sUserId}_id_{$s}"))) {
$data = $this->oMapper->GetFavouritesByArray($aTargetId, $sTargetType, $sUserId);
foreach ($data as $oFavourite) {
$aFavourites[$oFavourite->getTargetId()] = $oFavourite;
}
$this->Cache_Set($aFavourites, "favourite_{$sTargetType}_{$sUserId}_id_{$s}",
array("favourite_{$sTargetType}_change_user_{$sUserId}"), 60 * 60 * 24 * 1);
return $aFavourites;
}
return $data;
}
/**
* Получает список таргетов из избранного
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetFavouritesByUserId($sUserId, $sTargetType, $iCurrPage, $iPerPage, $aExcludeTarget = array())
{
$s = serialize($aExcludeTarget);
if (false === ($data = $this->Cache_Get("{$sTargetType}_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_{$s}"))) {
$data = array(
'collection' => $this->oMapper->GetFavouritesByUserId($sUserId, $sTargetType, $iCount, $iCurrPage,
$iPerPage, $aExcludeTarget),
'count' => $iCount
);
$this->Cache_Set(
$data,
"{$sTargetType}_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_{$s}",
array(
"favourite_{$sTargetType}_change",
"favourite_{$sTargetType}_change_user_{$sUserId}"
),
60 * 60 * 24 * 1
);
}
return $data;
}
/**
* Возвращает число таргетов определенного типа в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetCountFavouritesByUserId($sUserId, $sTargetType, $aExcludeTarget = array())
{
$s = serialize($aExcludeTarget);
if (false === ($data = $this->Cache_Get("{$sTargetType}_count_favourite_user_{$sUserId}_{$s}"))) {
$data = $this->oMapper->GetCountFavouritesByUserId($sUserId, $sTargetType, $aExcludeTarget);
$this->Cache_Set(
$data,
"{$sTargetType}_count_favourite_user_{$sUserId}_{$s}",
array(
"favourite_{$sTargetType}_change",
"favourite_{$sTargetType}_change_user_{$sUserId}"
),
60 * 60 * 24 * 1
);
}
return $data;
}
/**
* Получает список комментариев к записям открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenCommentsByUserId($sUserId, $iCurrPage, $iPerPage)
{
if (false === ($data = $this->Cache_Get("comment_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open"))) {
$data = array(
'collection' => $this->oMapper->GetFavouriteOpenCommentsByUserId($sUserId, $iCount, $iCurrPage,
$iPerPage),
'count' => $iCount
);
$this->Cache_Set(
$data,
"comment_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open",
array(
"favourite_comment_change",
"favourite_comment_change_user_{$sUserId}"
),
60 * 60 * 24 * 1
);
}
return $data;
}
/**
* Возвращает число комментариев к открытым блогам в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenCommentsByUserId($sUserId)
{
if (false === ($data = $this->Cache_Get("comment_count_favourite_user_{$sUserId}_open"))) {
$data = $this->oMapper->GetCountFavouriteOpenCommentsByUserId($sUserId);
$this->Cache_Set(
$data,
"comment_count_favourite_user_{$sUserId}_open",
array(
"favourite_comment_change",
"favourite_comment_change_user_{$sUserId}"
),
60 * 60 * 24 * 1
);
}
return $data;
}
/**
* Получает список топиков из открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenTopicsByUserId($sUserId, $iCurrPage, $iPerPage)
{
if (false === ($data = $this->Cache_Get("topic_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open"))) {
$data = array(
'collection' => $this->oMapper->GetFavouriteOpenTopicsByUserId($sUserId, $iCount, $iCurrPage,
$iPerPage),
'count' => $iCount
);
$this->Cache_Set(
$data,
"topic_favourite_user_{$sUserId}_{$iCurrPage}_{$iPerPage}_open",
array(
"favourite_topic_change",
"favourite_topic_change_user_{$sUserId}"
),
60 * 60 * 24 * 1
);
}
return $data;
}
/**
* Возвращает число топиков в открытых блогах из избранного по ID пользователя
*
* @param string $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenTopicsByUserId($sUserId)
{
if (false === ($data = $this->Cache_Get("topic_count_favourite_user_{$sUserId}_open"))) {
$data = $this->oMapper->GetCountFavouriteOpenTopicsByUserId($sUserId);
$this->Cache_Set(
$data,
"topic_count_favourite_user_{$sUserId}_open",
array(
"favourite_topic_change",
"favourite_topic_change_user_{$sUserId}"
),
60 * 60 * 24 * 1
);
}
return $data;
}
/**
* Добавляет таргет в избранное
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function AddFavourite(ModuleFavourite_EntityFavourite $oFavourite)
{
if (!$oFavourite->getTags()) {
$oFavourite->setTags('');
}
$this->SetFavouriteTags($oFavourite);
//чистим зависимые кеши
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,
array("favourite_{$oFavourite->getTargetType()}_change_user_{$oFavourite->getUserId()}"));
$this->Cache_Delete("favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$oFavourite->getUserId()}");
return $this->oMapper->AddFavourite($oFavourite);
}
/**
* Обновляет запись об избранном
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function UpdateFavourite(ModuleFavourite_EntityFavourite $oFavourite)
{
if (!$oFavourite->getTags()) {
$oFavourite->setTags('');
}
$this->SetFavouriteTags($oFavourite);
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,
array("favourite_{$oFavourite->getTargetType()}_change_user_{$oFavourite->getUserId()}"));
$this->Cache_Delete("favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$oFavourite->getUserId()}");
return $this->oMapper->UpdateFavourite($oFavourite);
}
/**
* Устанавливает список тегов для избранного
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @param bool $bAddNew Добавлять новые теги или нет
*/
public function SetFavouriteTags($oFavourite, $bAddNew = true)
{
/**
* Удаляем все теги
*/
$this->oMapper->DeleteTags($oFavourite);
/**
* Добавляем новые
*/
if ($bAddNew) {
/**
* Добавляем теги объекта избранного, если есть
*/
if ($aTags = $this->GetTagsTarget($oFavourite->getTargetType(), $oFavourite->getTargetId())) {
foreach ($aTags as $sTag) {
$oTag = Engine::GetEntity('ModuleFavourite_EntityTag', $oFavourite->_getData());
$oTag->setText(htmlspecialchars($sTag));
$oTag->setIsUser(0);
$this->oMapper->AddTag($oTag);
}
}
if ($oFavourite->getTags()) {
/**
* Добавляем пользовательские теги
*/
$aTags = $oFavourite->getTagsArray();
foreach ($aTags as $sTag) {
$oTag = Engine::GetEntity('ModuleFavourite_EntityTag', $oFavourite->_getData());
$oTag->setText($sTag); // htmlspecialchars уже используется при установке тегов
$oTag->setIsUser(1);
$this->oMapper->AddTag($oTag);
}
}
}
}
/**
* Удаляет таргет из избранного
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function DeleteFavourite(ModuleFavourite_EntityFavourite $oFavourite)
{
$this->SetFavouriteTags($oFavourite, false);
//чистим зависимые кеши
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,
array("favourite_{$oFavourite->getTargetType()}_change_user_{$oFavourite->getUserId()}"));
$this->Cache_Delete("favourite_{$oFavourite->getTargetType()}_{$oFavourite->getTargetId()}_{$oFavourite->getUserId()}");
return $this->oMapper->DeleteFavourite($oFavourite);
}
/**
* Меняет параметры публикации у таргета
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $iPublish Флаг публикации
* @return bool
*/
public function SetFavouriteTargetPublish($aTargetId, $sTargetType, $iPublish)
{
if (!is_array($aTargetId)) {
$aTargetId = array($aTargetId);
}
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("favourite_{$sTargetType}_change"));
return $this->oMapper->SetFavouriteTargetPublish($aTargetId, $sTargetType, $iPublish);
}
/**
* Удаляет избранное по списку идентификаторов таргетов
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteFavouriteByTargetId($aTargetId, $sTargetType)
{
if (!is_array($aTargetId)) {
$aTargetId = array($aTargetId);
}
/**
* Чистим зависимые кеши
*/
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("favourite_{$sTargetType}_change"));
$this->DeleteTagByTarget($aTargetId, $sTargetType);
return $this->oMapper->DeleteFavouriteByTargetId($aTargetId, $sTargetType);
}
/**
* Удаление тегов по таргету
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteTagByTarget($aTargetId, $sTargetType)
{
return $this->oMapper->DeleteTagByTarget($aTargetId, $sTargetType);
}
/**
* Возвращает список тегов для объекта избранного
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool|array
*/
public function GetTagsTarget($sTargetType, $iTargetId)
{
$sMethod = 'GetTagsTarget' . func_camelize($sTargetType);
if (method_exists($this, $sMethod)) {
return $this->$sMethod($iTargetId);
}
return false;
}
/**
* Возвращает наиболее часто используемые теги
*
* @param int $iUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param bool $bIsUser Возвращает все теги ли только пользовательские
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupTags($iUserId, $sTargetType, $bIsUser, $iLimit)
{
return $this->oMapper->GetGroupTags($iUserId, $sTargetType, $bIsUser, $iLimit);
}
/**
* Возвращает список тегов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetTags($aFilter, $aOrder, $iCurrPage, $iPerPage)
{
return array(
'collection' => $this->oMapper->GetTags($aFilter, $aOrder, $iCount, $iCurrPage, $iPerPage),
'count' => $iCount
);
}
/**
* Возвращает список тегов для топика, название метода формируется автоматически из GetTagsTarget()
* @see GetTagsTarget
*
* @param int $iTargetId ID владельца
* @return bool|array
*/
public function GetTagsTargetTopic($iTargetId)
{
if ($oTopic = $this->Topic_GetTopicById($iTargetId)) {
return $oTopic->getTagsArray();
}
return false;
}
}

View file

@ -25,81 +25,98 @@
* @package application.modules.favourite
* @since 1.0
*/
class ModuleFavourite_EntityFavourite extends Entity {
/**
* Возвращает ID владельца
*
* @return int|null
*/
public function getTargetId() {
return $this->_getDataOne('target_id');
}
/**
* Возвращает ID пользователя
*
* @return int|null
*/
public function getUserId() {
return $this->_getDataOne('user_id');
}
/**
* Возвращает флаг публикации владельца
*
* @return int|null
*/
public function getTargetPublish() {
return $this->_getDataOne('target_publish');
}
/**
* Возвращает тип владельца
*
* @return string|null
*/
public function getTargetType() {
return $this->_getDataOne('target_type');
}
/**
* Возващает список тегов
*
* @return array
*/
public function getTagsArray() {
if ($this->getTags()) {
return explode(',',$this->getTags());
}
return array();
}
class ModuleFavourite_EntityFavourite extends Entity
{
/**
* Возвращает ID владельца
*
* @return int|null
*/
public function getTargetId()
{
return $this->_getDataOne('target_id');
}
/**
* Устанавливает ID владельца
*
* @param int $data
*/
public function setTargetId($data) {
$this->_aData['target_id']=$data;
}
/**
* Устанавливает ID пользователя
*
* @param int $data
*/
public function setUserId($data) {
$this->_aData['user_id']=$data;
}
/**
* Устанавливает статус публикации для владельца
*
* @param int $data
*/
public function setTargetPublish($data) {
$this->_aData['target_publish']=$data;
}
/**
* Устанавливает тип владельца
*
* @param string $data
*/
public function setTargetType($data) {
$this->_aData['target_type']=$data;
}
/**
* Возвращает ID пользователя
*
* @return int|null
*/
public function getUserId()
{
return $this->_getDataOne('user_id');
}
/**
* Возвращает флаг публикации владельца
*
* @return int|null
*/
public function getTargetPublish()
{
return $this->_getDataOne('target_publish');
}
/**
* Возвращает тип владельца
*
* @return string|null
*/
public function getTargetType()
{
return $this->_getDataOne('target_type');
}
/**
* Возващает список тегов
*
* @return array
*/
public function getTagsArray()
{
if ($this->getTags()) {
return explode(',', $this->getTags());
}
return array();
}
/**
* Устанавливает ID владельца
*
* @param int $data
*/
public function setTargetId($data)
{
$this->_aData['target_id'] = $data;
}
/**
* Устанавливает ID пользователя
*
* @param int $data
*/
public function setUserId($data)
{
$this->_aData['user_id'] = $data;
}
/**
* Устанавливает статус публикации для владельца
*
* @param int $data
*/
public function setTargetPublish($data)
{
$this->_aData['target_publish'] = $data;
}
/**
* Устанавливает тип владельца
*
* @param string $data
*/
public function setTargetType($data)
{
$this->_aData['target_type'] = $data;
}
}

View file

@ -25,6 +25,7 @@
* @package application.modules.favourite
* @since 1.0
*/
class ModuleFavourite_EntityTag extends Entity {
class ModuleFavourite_EntityTag extends Entity
{
}

View file

@ -25,90 +25,100 @@
* @package application.modules.favourite
* @since 1.0
*/
class ModuleFavourite_MapperFavourite extends Mapper {
/**
* Добавляет таргет в избранное
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function AddFavourite(ModuleFavourite_EntityFavourite $oFavourite) {
$sql = "
INSERT INTO ".Config::Get('db.table.favourite')."
class ModuleFavourite_MapperFavourite extends Mapper
{
/**
* Добавляет таргет в избранное
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function AddFavourite(ModuleFavourite_EntityFavourite $oFavourite)
{
$sql = "
INSERT INTO " . Config::Get('db.table.favourite') . "
( target_id, target_type, user_id, tags )
VALUES
(?d, ?, ?d, ?)
";
if ($this->oDb->query(
$sql,
$oFavourite->getTargetId(),
$oFavourite->getTargetType(),
$oFavourite->getUserId(),
$oFavourite->getTags()
)===0) {
return true;
}
return false;
}
/**
* Обновляет запись об избранном
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function UpdateFavourite(ModuleFavourite_EntityFavourite $oFavourite) {
$sql = "
UPDATE ".Config::Get('db.table.favourite')."
if ($this->oDb->query(
$sql,
$oFavourite->getTargetId(),
$oFavourite->getTargetType(),
$oFavourite->getUserId(),
$oFavourite->getTags()
) === 0
) {
return true;
}
return false;
}
/**
* Обновляет запись об избранном
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function UpdateFavourite(ModuleFavourite_EntityFavourite $oFavourite)
{
$sql = "
UPDATE " . Config::Get('db.table.favourite') . "
SET tags = ? WHERE user_id = ?d and target_id = ?d and target_type = ?
";
if ($this->oDb->query(
$sql,
$oFavourite->getTags(),
$oFavourite->getUserId(),
$oFavourite->getTargetId(),
$oFavourite->getTargetType()
)!==false) {
return true;
}
return false;
}
/**
* Получить список избранного по списку айдишников
*
* @param array $aArrayId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return array
*/
public function GetFavouritesByArray($aArrayId,$sTargetType,$sUserId) {
if (!is_array($aArrayId) or count($aArrayId)==0) {
return array();
}
$sql = "SELECT *
FROM ".Config::Get('db.table.favourite')."
if ($this->oDb->query(
$sql,
$oFavourite->getTags(),
$oFavourite->getUserId(),
$oFavourite->getTargetId(),
$oFavourite->getTargetType()
) !== false
) {
return true;
}
return false;
}
/**
* Получить список избранного по списку айдишников
*
* @param array $aArrayId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $sUserId ID пользователя
* @return array
*/
public function GetFavouritesByArray($aArrayId, $sTargetType, $sUserId)
{
if (!is_array($aArrayId) or count($aArrayId) == 0) {
return array();
}
$sql = "SELECT *
FROM " . Config::Get('db.table.favourite') . "
WHERE
user_id = ?d
AND
target_id IN(?a)
AND
target_type = ? ";
$aFavourites=array();
if ($aRows=$this->oDb->select($sql,$sUserId,$aArrayId,$sTargetType)) {
foreach ($aRows as $aRow) {
$aFavourites[]=Engine::GetEntity('Favourite',$aRow);
}
}
return $aFavourites;
}
/**
* Удаляет таргет из избранного
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function DeleteFavourite(ModuleFavourite_EntityFavourite $oFavourite) {
$sql = "
DELETE FROM ".Config::Get('db.table.favourite')."
$aFavourites = array();
if ($aRows = $this->oDb->select($sql, $sUserId, $aArrayId, $sTargetType)) {
foreach ($aRows as $aRow) {
$aFavourites[] = Engine::GetEntity('Favourite', $aRow);
}
}
return $aFavourites;
}
/**
* Удаляет таргет из избранного
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function DeleteFavourite(ModuleFavourite_EntityFavourite $oFavourite)
{
$sql = "
DELETE FROM " . Config::Get('db.table.favourite') . "
WHERE
user_id = ?d
AND
@ -116,23 +126,25 @@ class ModuleFavourite_MapperFavourite extends Mapper {
AND
target_type = ?
";
$res=$this->oDb->query(
$sql,
$oFavourite->getUserId(),
$oFavourite->getTargetId(),
$oFavourite->getTargetType()
);
return $this->IsSuccessful($res);
}
/**
* Удаляет теги
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function DeleteTags($oFavourite) {
$sql = "
DELETE FROM ".Config::Get('db.table.favourite_tag')."
$res = $this->oDb->query(
$sql,
$oFavourite->getUserId(),
$oFavourite->getTargetId(),
$oFavourite->getTargetType()
);
return $this->IsSuccessful($res);
}
/**
* Удаляет теги
*
* @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного
* @return bool
*/
public function DeleteTags($oFavourite)
{
$sql = "
DELETE FROM " . Config::Get('db.table.favourite_tag') . "
WHERE
user_id = ?d
AND
@ -140,48 +152,53 @@ class ModuleFavourite_MapperFavourite extends Mapper {
AND
target_id = ?d
";
$res=$this->oDb->query(
$sql,
$oFavourite->getUserId(),
$oFavourite->getTargetType(),
$oFavourite->getTargetId()
);
return $this->IsSuccessful($res);
}
/**
* Добавляет тег
*
* @param ModuleFavourite_EntityTag $oTag Объект тега
* @return bool
*/
public function AddTag($oTag) {
$sql = "
INSERT INTO ".Config::Get('db.table.favourite_tag')."
$res = $this->oDb->query(
$sql,
$oFavourite->getUserId(),
$oFavourite->getTargetType(),
$oFavourite->getTargetId()
);
return $this->IsSuccessful($res);
}
/**
* Добавляет тег
*
* @param ModuleFavourite_EntityTag $oTag Объект тега
* @return bool
*/
public function AddTag($oTag)
{
$sql = "
INSERT INTO " . Config::Get('db.table.favourite_tag') . "
SET target_id = ?d, target_type = ?, user_id = ?d, is_user = ?d, text =?
";
if ($this->oDb->query(
$sql,
$oTag->getTargetId(),
$oTag->getTargetType(),
$oTag->getUserId(),
$oTag->getIsUser(),
$oTag->getText()
)===0) {
return true;
}
return false;
}
/**
* Меняет параметры публикации у таргета
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $iPublish Флаг публикации
* @return bool
*/
public function SetFavouriteTargetPublish($aTargetId,$sTargetType,$iPublish) {
$sql = "
UPDATE ".Config::Get('db.table.favourite')."
if ($this->oDb->query(
$sql,
$oTag->getTargetId(),
$oTag->getTargetType(),
$oTag->getUserId(),
$oTag->getIsUser(),
$oTag->getText()
) === 0
) {
return true;
}
return false;
}
/**
* Меняет параметры публикации у таргета
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @param int $iPublish Флаг публикации
* @return bool
*/
public function SetFavouriteTargetPublish($aTargetId, $sTargetType, $iPublish)
{
$sql = "
UPDATE " . Config::Get('db.table.favourite') . "
SET
target_publish = ?d
WHERE
@ -189,24 +206,32 @@ class ModuleFavourite_MapperFavourite extends Mapper {
AND
target_type = ?
";
$res=$this->oDb->query($sql,$iPublish,$aTargetId,$sTargetType);
return $this->IsSuccessful($res);
}
/**
* Получает список таргетов из избранного
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetFavouritesByUserId($sUserId,$sTargetType,&$iCount,$iCurrPage,$iPerPage,$aExcludeTarget=array()) {
$sql = "
$res = $this->oDb->query($sql, $iPublish, $aTargetId, $sTargetType);
return $this->IsSuccessful($res);
}
/**
* Получает список таргетов из избранного
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetFavouritesByUserId(
$sUserId,
$sTargetType,
&$iCount,
$iCurrPage,
$iPerPage,
$aExcludeTarget = array()
) {
$sql = "
SELECT target_id
FROM ".Config::Get('db.table.favourite')."
FROM " . Config::Get('db.table.favourite') . "
WHERE
user_id = ?
AND
@ -217,35 +242,38 @@ class ModuleFavourite_MapperFavourite extends Mapper {
ORDER BY target_id DESC
LIMIT ?d, ?d ";
$aFavourites=array();
if ($aRows=$this->oDb->selectPage(
$iCount,
$sql,
$sUserId,
$sTargetType,
(count($aExcludeTarget) ? $aExcludeTarget : DBSIMPLE_SKIP),
($iCurrPage-1)*$iPerPage,
$iPerPage
)) {
foreach ($aRows as $aFavourite) {
$aFavourites[]=$aFavourite['target_id'];
}
}
return $aFavourites;
}
/**
* Возвращает число таргетов определенного типа в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetCountFavouritesByUserId($sUserId,$sTargetType,$aExcludeTarget) {
$sql = "SELECT
$aFavourites = array();
if ($aRows = $this->oDb->selectPage(
$iCount,
$sql,
$sUserId,
$sTargetType,
(count($aExcludeTarget) ? $aExcludeTarget : DBSIMPLE_SKIP),
($iCurrPage - 1) * $iPerPage,
$iPerPage
)
) {
foreach ($aRows as $aFavourite) {
$aFavourites[] = $aFavourite['target_id'];
}
}
return $aFavourites;
}
/**
* Возвращает число таргетов определенного типа в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param array $aExcludeTarget Список ID владельцев для исклчения
* @return array
*/
public function GetCountFavouritesByUserId($sUserId, $sTargetType, $aExcludeTarget)
{
$sql = "SELECT
count(target_id) as count
FROM
".Config::Get('db.table.favourite')."
" . Config::Get('db.table.favourite') . "
WHERE
user_id = ?
AND
@ -254,33 +282,35 @@ class ModuleFavourite_MapperFavourite extends Mapper {
target_type = ?
{ AND target_id NOT IN (?a) }
;";
return ( $aRow=$this->oDb->selectRow(
$sql,$sUserId,
$sTargetType,
(count($aExcludeTarget) ? $aExcludeTarget : DBSIMPLE_SKIP)
)
)
? $aRow['count']
: false;
}
/**
* Получает список комментариев к записям открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenCommentsByUserId($sUserId,&$iCount,$iCurrPage,$iPerPage) {
$sql = "
return ($aRow = $this->oDb->selectRow(
$sql, $sUserId,
$sTargetType,
(count($aExcludeTarget) ? $aExcludeTarget : DBSIMPLE_SKIP)
)
)
? $aRow['count']
: false;
}
/**
* Получает список комментариев к записям открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenCommentsByUserId($sUserId, &$iCount, $iCurrPage, $iPerPage)
{
$sql = "
SELECT f.target_id
FROM
".Config::Get('db.table.favourite')." AS f,
".Config::Get('db.table.comment')." AS c,
".Config::Get('db.table.topic')." AS t,
".Config::Get('db.table.blog')." AS b
" . Config::Get('db.table.favourite') . " AS f,
" . Config::Get('db.table.comment') . " AS c,
" . Config::Get('db.table.topic') . " AS t,
" . Config::Get('db.table.blog') . " AS b
WHERE
f.user_id = ?d
AND
@ -298,31 +328,34 @@ class ModuleFavourite_MapperFavourite extends Mapper {
ORDER BY target_id DESC
LIMIT ?d, ?d ";
$aFavourites=array();
if ($aRows=$this->oDb->selectPage(
$iCount, $sql, $sUserId,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aFavourite) {
$aFavourites[]=$aFavourite['target_id'];
}
}
return $aFavourites;
}
/**
* Возвращает число комментариев к открытым блогам в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenCommentsByUserId($sUserId) {
$sql = "SELECT
$aFavourites = array();
if ($aRows = $this->oDb->selectPage(
$iCount, $sql, $sUserId,
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aFavourite) {
$aFavourites[] = $aFavourite['target_id'];
}
}
return $aFavourites;
}
/**
* Возвращает число комментариев к открытым блогам в избранном по ID пользователя
*
* @param int $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenCommentsByUserId($sUserId)
{
$sql = "SELECT
count(f.target_id) as count
FROM
".Config::Get('db.table.favourite')." AS f,
".Config::Get('db.table.comment')." AS c,
".Config::Get('db.table.topic')." AS t,
".Config::Get('db.table.blog')." AS b
" . Config::Get('db.table.favourite') . " AS f,
" . Config::Get('db.table.comment') . " AS c,
" . Config::Get('db.table.topic') . " AS t,
" . Config::Get('db.table.blog') . " AS b
WHERE
f.user_id = ?d
AND
@ -338,27 +371,29 @@ class ModuleFavourite_MapperFavourite extends Mapper {
AND
b.blog_type IN ('open', 'personal')
;";
return ( $aRow=$this->oDb->selectRow($sql,$sUserId) )
? $aRow['count']
: false;
}
/**
* Получает список топиков из открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenTopicsByUserId($sUserId,&$iCount,$iCurrPage,$iPerPage) {
$sql = "
return ($aRow = $this->oDb->selectRow($sql, $sUserId))
? $aRow['count']
: false;
}
/**
* Получает список топиков из открытых блогов
* из избранного указанного пользователя
*
* @param int $sUserId ID пользователя
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetFavouriteOpenTopicsByUserId($sUserId, &$iCount, $iCurrPage, $iPerPage)
{
$sql = "
SELECT f.target_id
FROM
".Config::Get('db.table.favourite')." AS f,
".Config::Get('db.table.topic')." AS t,
".Config::Get('db.table.blog')." AS b
" . Config::Get('db.table.favourite') . " AS f,
" . Config::Get('db.table.topic') . " AS t,
" . Config::Get('db.table.blog') . " AS b
WHERE
f.user_id = ?d
AND
@ -374,30 +409,33 @@ class ModuleFavourite_MapperFavourite extends Mapper {
ORDER BY target_id DESC
LIMIT ?d, ?d ";
$aFavourites=array();
if ($aRows=$this->oDb->selectPage(
$iCount, $sql, $sUserId,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aFavourite) {
$aFavourites[]=$aFavourite['target_id'];
}
}
return $aFavourites;
}
/**
* Возвращает число топиков в открытых блогах из избранного по ID пользователя
*
* @param string $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenTopicsByUserId($sUserId) {
$sql = "SELECT
$aFavourites = array();
if ($aRows = $this->oDb->selectPage(
$iCount, $sql, $sUserId,
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aFavourite) {
$aFavourites[] = $aFavourite['target_id'];
}
}
return $aFavourites;
}
/**
* Возвращает число топиков в открытых блогах из избранного по ID пользователя
*
* @param string $sUserId ID пользователя
* @return array
*/
public function GetCountFavouriteOpenTopicsByUserId($sUserId)
{
$sql = "SELECT
count(f.target_id) as count
FROM
".Config::Get('db.table.favourite')." AS f,
".Config::Get('db.table.topic')." AS t,
".Config::Get('db.table.blog')." AS b
" . Config::Get('db.table.favourite') . " AS f,
" . Config::Get('db.table.topic') . " AS t,
" . Config::Get('db.table.blog') . " AS b
WHERE
f.user_id = ?d
AND
@ -411,60 +449,66 @@ class ModuleFavourite_MapperFavourite extends Mapper {
AND
b.blog_type IN ('open', 'personal')
;";
return ( $aRow=$this->oDb->selectRow($sql,$sUserId) )
? $aRow['count']
: false;
}
/**
* Удаляет избранное по списку идентификаторов таргетов
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteFavouriteByTargetId($aTargetId,$sTargetType) {
$sql = "
DELETE FROM ".Config::Get('db.table.favourite')."
return ($aRow = $this->oDb->selectRow($sql, $sUserId))
? $aRow['count']
: false;
}
/**
* Удаляет избранное по списку идентификаторов таргетов
*
* @param array|int $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteFavouriteByTargetId($aTargetId, $sTargetType)
{
$sql = "
DELETE FROM " . Config::Get('db.table.favourite') . "
WHERE
target_id IN(?a)
AND
target_type = ? ";
$res=$this->oDb->query($sql,$aTargetId,$sTargetType);
return $this->IsSuccessful($res);
}
/**
* Удаление тегов по таргету
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteTagByTarget($aTargetId,$sTargetType) {
$sql = "
DELETE FROM ".Config::Get('db.table.favourite_tag')."
$res = $this->oDb->query($sql, $aTargetId, $sTargetType);
return $this->IsSuccessful($res);
}
/**
* Удаление тегов по таргету
*
* @param array $aTargetId Список ID владельцев
* @param string $sTargetType Тип владельца
* @return bool
*/
public function DeleteTagByTarget($aTargetId, $sTargetType)
{
$sql = "
DELETE FROM " . Config::Get('db.table.favourite_tag') . "
WHERE
target_type = ?
AND
target_id IN(?a)
";
$res=$this->oDb->query($sql,$sTargetType,$aTargetId);
return $this->IsSuccessful($res);
}
/**
* Возвращает наиболее часто используемые теги
*
* @param int $iUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param bool $bIsUser Возвращает все теги ли только пользовательские
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupTags($iUserId,$sTargetType,$bIsUser,$iLimit) {
$sql = "SELECT
$res = $this->oDb->query($sql, $sTargetType, $aTargetId);
return $this->IsSuccessful($res);
}
/**
* Возвращает наиболее часто используемые теги
*
* @param int $iUserId ID пользователя
* @param string $sTargetType Тип владельца
* @param bool $bIsUser Возвращает все теги ли только пользовательские
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupTags($iUserId, $sTargetType, $bIsUser, $iLimit)
{
$sql = "SELECT
text,
count(text) as count
FROM
".Config::Get('db.table.favourite_tag')."
" . Config::Get('db.table.favourite_tag') . "
WHERE
1=1
{AND user_id = ?d }
@ -476,48 +520,52 @@ class ModuleFavourite_MapperFavourite extends Mapper {
count desc
LIMIT 0, ?d
";
$aReturn=array();
$aReturnSort=array();
if ($aRows=$this->oDb->select($sql,$iUserId,$sTargetType,is_null($bIsUser) ? DBSIMPLE_SKIP : $bIsUser,$iLimit)) {
foreach ($aRows as $aRow) {
$aReturn[mb_strtolower($aRow['text'],'UTF-8')]=$aRow;
}
ksort($aReturn);
foreach ($aReturn as $aRow) {
$aReturnSort[]=Engine::GetEntity('ModuleFavourite_EntityTag',$aRow);
}
}
return $aReturnSort;
}
/**
* Возвращает список тегов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetTags($aFilter,$aOrder,&$iCount,$iCurrPage,$iPerPage) {
$aOrderAllow=array('target_id','user_id','is_user');
$sOrder='';
foreach ($aOrder as $key=>$value) {
if (!in_array($key,$aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value,array('asc','desc'))) {
$sOrder.=" {$key} {$value},";
}
}
$sOrder=trim($sOrder,',');
if ($sOrder=='') {
$sOrder=' target_id desc ';
}
$aReturn = array();
$aReturnSort = array();
if ($aRows = $this->oDb->select($sql, $iUserId, $sTargetType, is_null($bIsUser) ? DBSIMPLE_SKIP : $bIsUser,
$iLimit)
) {
foreach ($aRows as $aRow) {
$aReturn[mb_strtolower($aRow['text'], 'UTF-8')] = $aRow;
}
ksort($aReturn);
foreach ($aReturn as $aRow) {
$aReturnSort[] = Engine::GetEntity('ModuleFavourite_EntityTag', $aRow);
}
}
return $aReturnSort;
}
$sql = "SELECT
/**
* Возвращает список тегов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetTags($aFilter, $aOrder, &$iCount, $iCurrPage, $iPerPage)
{
$aOrderAllow = array('target_id', 'user_id', 'is_user');
$sOrder = '';
foreach ($aOrder as $key => $value) {
if (!in_array($key, $aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value, array('asc', 'desc'))) {
$sOrder .= " {$key} {$value},";
}
}
$sOrder = trim($sOrder, ',');
if ($sOrder == '') {
$sOrder = ' target_id desc ';
}
$sql = "SELECT
*
FROM
".Config::Get('db.table.favourite_tag')."
" . Config::Get('db.table.favourite_tag') . "
WHERE
1 = 1
{ AND user_id = ?d }
@ -528,19 +576,20 @@ class ModuleFavourite_MapperFavourite extends Mapper {
ORDER by {$sOrder}
LIMIT ?d, ?d ;
";
$aResult=array();
if ($aRows=$this->oDb->selectPage($iCount,$sql,
isset($aFilter['user_id']) ? $aFilter['user_id'] : DBSIMPLE_SKIP,
isset($aFilter['target_type']) ? $aFilter['target_type'] : DBSIMPLE_SKIP,
isset($aFilter['target_id']) ? $aFilter['target_id'] : DBSIMPLE_SKIP,
isset($aFilter['is_user']) ? $aFilter['is_user'] : DBSIMPLE_SKIP,
isset($aFilter['text']) ? $aFilter['text'] : DBSIMPLE_SKIP,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aRow) {
$aResult[]=Engine::GetEntity('ModuleFavourite_EntityTag',$aRow);
}
}
return $aResult;
}
$aResult = array();
if ($aRows = $this->oDb->selectPage($iCount, $sql,
isset($aFilter['user_id']) ? $aFilter['user_id'] : DBSIMPLE_SKIP,
isset($aFilter['target_type']) ? $aFilter['target_type'] : DBSIMPLE_SKIP,
isset($aFilter['target_id']) ? $aFilter['target_id'] : DBSIMPLE_SKIP,
isset($aFilter['is_user']) ? $aFilter['is_user'] : DBSIMPLE_SKIP,
isset($aFilter['text']) ? $aFilter['text'] : DBSIMPLE_SKIP,
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aRow) {
$aResult[] = Engine::GetEntity('ModuleFavourite_EntityTag', $aRow);
}
}
return $aResult;
}
}

View file

@ -22,405 +22,473 @@
/**
* Модуль Geo - привязка объектов к географии (страна/регион/город)
* Терминология:
* объект - который привязываем к гео-объекту
* гео-объект - географический объект(страна/регион/город)
* объект - который привязываем к гео-объекту
* гео-объект - географический объект(страна/регион/город)
*
* @package application.modules.geo
* @since 1.0
*/
class ModuleGeo extends Module {
/**
* Объект маппера
*
* @var ModuleGeo_MapperGeo
*/
protected $oMapper;
/**
* Объект текущего пользователя
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
/**
* Список доступных типов объектов
* На данный момент доступен параметр allow_multi=>1 - указывает на возможность создавать несколько связей для одного объекта
*
* @var array
*/
protected $aTargetTypes=array(
'user'=>array(),
);
/**
* Список доступных типов гео-объектов
*
* @var array
*/
protected $aGeoTypes=array(
'country',
'region',
'city',
);
class ModuleGeo extends Module
{
/**
* Объект маппера
*
* @var ModuleGeo_MapperGeo
*/
protected $oMapper;
/**
* Объект текущего пользователя
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
/**
* Список доступных типов объектов
* На данный момент доступен параметр allow_multi=>1 - указывает на возможность создавать несколько связей для одного объекта
*
* @var array
*/
protected $aTargetTypes = array(
'user' => array(),
);
/**
* Список доступных типов гео-объектов
*
* @var array
*/
protected $aGeoTypes = array(
'country',
'region',
'city',
);
/**
* Инициализация
*
*/
public function Init() {
$this->oMapper=Engine::GetMapper(__CLASS__);
$this->oUserCurrent=$this->User_GetUserCurrent();
}
/**
* Возвращает список типов объектов
*
* @return array
*/
public function GetTargetTypes() {
return $this->aTargetTypes;
}
/**
* Добавляет в разрешенные новый тип
* @param string $sTargetType Тип владельца
* @param array $aParams Параметры
* @return bool
*/
public function AddTargetType($sTargetType,$aParams=array()) {
if (!array_key_exists($sTargetType,$this->aTargetTypes)) {
$this->aTargetTypes[$sTargetType]=$aParams;
return true;
}
return false;
}
/**
* Проверяет разрешен ли данный тип
*
* @param string $sTargetType Тип владельца
* @return bool
*/
public function IsAllowTargetType($sTargetType) {
return in_array($sTargetType,array_keys($this->aTargetTypes));
}
/**
* Проверяет разрешен ли данный гео-тип
*
* @param string $sGeoType Тип владельца
* @return bool
*/
public function IsAllowGeoType($sGeoType) {
return in_array($sGeoType,$this->aGeoTypes);
}
/**
* Проверка объекта
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool
*/
public function CheckTarget($sTargetType,$iTargetId) {
if (!$this->IsAllowTargetType($sTargetType)) {
return false;
}
$sMethod = 'CheckTarget'.func_camelize($sTargetType);
if (method_exists($this,$sMethod)) {
return $this->$sMethod($iTargetId);
}
return false;
}
/**
* Проверка на возможность нескольких связей
*
* @param string $sTargetType Тип владельца
* @return bool
*/
public function IsAllowTargetMulti($sTargetType) {
if ($this->IsAllowTargetType($sTargetType)) {
if (isset($this->aTargetTypes[$sTargetType]['allow_multi']) and $this->aTargetTypes[$sTargetType]['allow_multi']) {
return true;
}
}
return false;
}
/**
* Добавляет связь объекта с гео-объектом в БД
*
* @param ModuleGeo_EntityTarget $oTarget Объект связи с владельцем
* @return ModuleGeo_EntityTarget|bool
*/
public function AddTarget($oTarget) {
if ($this->oMapper->AddTarget($oTarget)) {
return $oTarget;
}
return false;
}
/**
* Создание связи
*
* @param ModuleGeo_EntityGeo $oGeoObject
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool|ModuleGeo_EntityTarget
*/
public function CreateTarget($oGeoObject,$sTargetType,$iTargetId) {
/**
* Проверяем объект на валидность
*/
if (!$this->CheckTarget($sTargetType,$iTargetId)) {
return false;
}
/**
* Проверяем есть ли уже у этого объекта другие связи
*/
$aTargets=$this->GetTargets(array('target_type'=>$sTargetType,'target_id'=>$iTargetId),1,1);
if ($aTargets['count']) {
if ($this->IsAllowTargetMulti($sTargetType)) {
/**
* Разрешено несколько связей
* Проверяем есть ли уже связь с данным гео-объектом, если есть то возвращаем его
*/
$aTargetSelf=$this->GetTargets(array('target_type'=>$sTargetType,'target_id'=>$iTargetId,'geo_type'=>$oGeoObject->getType(),'geo_id'=>$oGeoObject->getId()),1,1);
if (isset($aTargetSelf['collection'][0])) {
return $aTargetSelf['collection'][0];
}
} else {
/**
* Есть другие связи и несколько связей запрещено - удаляем имеющиеся связи
*/
$this->DeleteTargets(array('target_type'=>$sTargetType,'target_id'=>$iTargetId));
}
}
/**
* Создаем связь
*/
$oTarget=Engine::GetEntity('ModuleGeo_EntityTarget');
$oTarget->setGeoType($oGeoObject->getType());
$oTarget->setGeoId($oGeoObject->getId());
$oTarget->setTargetType($sTargetType);
$oTarget->setTargetId($iTargetId);
if ($oGeoObject->getType()=='city') {
$oTarget->setCountryId($oGeoObject->getCountryId());
$oTarget->setRegionId($oGeoObject->getRegionId());
$oTarget->setCityId($oGeoObject->getId());
} elseif ($oGeoObject->getType()=='region') {
$oTarget->setCountryId($oGeoObject->getCountryId());
$oTarget->setRegionId($oGeoObject->getId());
} elseif ($oGeoObject->getType()=='country') {
$oTarget->setCountryId($oGeoObject->getId());
}
return $this->AddTarget($oTarget);
}
/**
* Возвращает список связей по фильтру
*
* @param array $aFilter Фильтр
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetTargets($aFilter,$iCurrPage,$iPerPage) {
return array('collection'=>$this->oMapper->GetTargets($aFilter,$iCount,$iCurrPage,$iPerPage),'count'=>$iCount);
}
/**
* Возвращает первый объект связи по объекту
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return null|ModuleGeo_EntityTarget
*/
public function GetTargetByTarget($sTargetType,$iTargetId) {
$aTargets=$this->GetTargets(array('target_type'=>$sTargetType,'target_id'=>$iTargetId),1,1);
if (isset($aTargets['collection'][0])) {
return $aTargets['collection'][0];
}
return null;
}
/**
* Возвращает список связей для списка объектов одного типа.
*
* @param string $sTargetType Тип владельца
* @param array $aTargetId Список ID владельцев
* @return array В качестве ключей используется ID объекта, в качестве значений массив связей этого объекта
*/
public function GetTargetsByTargetArray($sTargetType,$aTargetId) {
if (!is_array($aTargetId)) {
$aTargetId=array($aTargetId);
}
if (!count($aTargetId)) {
return array();
}
$aResult=array();
$aTargets=$this->GetTargets(array('target_type'=>$sTargetType,'target_id'=>$aTargetId),1,count($aTargetId));
if ($aTargets['count']) {
foreach($aTargets['collection'] as $oTarget) {
$aResult[$oTarget->getTargetId()][]=$oTarget;
}
}
return $aResult;
}
/**
* Удаляет связи по фильтру
*
* @param array $aFilter Фильтр
* @return bool|int
*/
public function DeleteTargets($aFilter) {
return $this->oMapper->DeleteTargets($aFilter);
}
/**
* Удаление всех связей объекта
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool|int
*/
public function DeleteTargetsByTarget($sTargetType,$iTargetId) {
return $this->DeleteTargets(array('target_type'=>$sTargetType,'target_id'=>$iTargetId));
}
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetCountries($aFilter,$aOrder,$iCurrPage,$iPerPage) {
return array('collection'=>$this->oMapper->GetCountries($aFilter,$aOrder,$iCount,$iCurrPage,$iPerPage),'count'=>$iCount);
}
/**
* Возвращает список регионов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetRegions($aFilter,$aOrder,$iCurrPage,$iPerPage) {
return array('collection'=>$this->oMapper->GetRegions($aFilter,$aOrder,$iCount,$iCurrPage,$iPerPage),'count'=>$iCount);
}
/**
* Возвращает список городов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetCities($aFilter,$aOrder,$iCurrPage,$iPerPage) {
return array('collection'=>$this->oMapper->GetCities($aFilter,$aOrder,$iCount,$iCurrPage,$iPerPage),'count'=>$iCount);
}
/**
* Возвращает страну по ID
*
* @param int $iId ID страны
* @return ModuleGeo_EntityCountry|null
*/
public function GetCountryById($iId) {
$aRes=$this->GetCountries(array('id'=>$iId),array(),1,1);
if (isset($aRes['collection'][0])) {
return $aRes['collection'][0];
}
return null;
}
/**
* Возвращает регион по ID
*
* @param int $iId ID региона
* @return ModuleGeo_EntityRegion|null
*/
public function GetRegionById($iId) {
$aRes=$this->GetRegions(array('id'=>$iId),array(),1,1);
if (isset($aRes['collection'][0])) {
return $aRes['collection'][0];
}
return null;
}
/**
* Возвращает регион по ID
*
* @param int $iId ID города
* @return ModuleGeo_EntityCity|null
*/
public function GetCityById($iId) {
$aRes=$this->GetCities(array('id'=>$iId),array(),1,1);
if (isset($aRes['collection'][0])) {
return $aRes['collection'][0];
}
return null;
}
/**
* Возвращает гео-объект
*
* @param string $sType Тип гео-объекта
* @param int $iId ID гео-объекта
* @return ModuleGeo_EntityGeo|null
*/
public function GetGeoObject($sType,$iId) {
$sType=strtolower($sType);
if (!$this->IsAllowGeoType($sType)) {
return null;
}
switch($sType) {
case 'country':
return $this->GetCountryById($iId);
break;
case 'region':
return $this->GetRegionById($iId);
break;
case 'city':
return $this->GetCityById($iId);
break;
default:
return null;
}
}
/**
* Возвращает первый гео-объект для объекта
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return ModuleGeo_EntityCity|ModuleGeo_EntityCountry|ModuleGeo_EntityRegion|null
*/
public function GetGeoObjectByTarget($sTargetType,$iTargetId) {
$aTargets=$this->GetTargets(array('target_type'=>$sTargetType,'target_id'=>$iTargetId),1,1);
if (isset($aTargets['collection'][0])) {
$oTarget=$aTargets['collection'][0];
return $this->GetGeoObject($oTarget->getGeoType(),$oTarget->getGeoId());
}
return null;
}
/**
* Возвращает список стран сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCountriesByTargetType($sTargetType,$iLimit) {
return $this->oMapper->GetGroupCountriesByTargetType($sTargetType,$iLimit);
}
/**
* Возвращает список городов сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCitiesByTargetType($sTargetType,$iLimit) {
return $this->oMapper->GetGroupCitiesByTargetType($sTargetType,$iLimit);
}
/**
* Проверка объекта с типом "user"
* Название метода формируется автоматически
*
* @param int $iTargetId ID пользователя
* @return bool
*/
public function CheckTargetUser($iTargetId) {
if ($oUser=$this->User_GetUserById($iTargetId)) {
return true;
}
return false;
}
/**
* Инициализация
*
*/
public function Init()
{
$this->oMapper = Engine::GetMapper(__CLASS__);
$this->oUserCurrent = $this->User_GetUserCurrent();
}
/**
* Возвращает список типов объектов
*
* @return array
*/
public function GetTargetTypes()
{
return $this->aTargetTypes;
}
/**
* Добавляет в разрешенные новый тип
* @param string $sTargetType Тип владельца
* @param array $aParams Параметры
* @return bool
*/
public function AddTargetType($sTargetType, $aParams = array())
{
if (!array_key_exists($sTargetType, $this->aTargetTypes)) {
$this->aTargetTypes[$sTargetType] = $aParams;
return true;
}
return false;
}
/**
* Проверяет разрешен ли данный тип
*
* @param string $sTargetType Тип владельца
* @return bool
*/
public function IsAllowTargetType($sTargetType)
{
return in_array($sTargetType, array_keys($this->aTargetTypes));
}
/**
* Проверяет разрешен ли данный гео-тип
*
* @param string $sGeoType Тип владельца
* @return bool
*/
public function IsAllowGeoType($sGeoType)
{
return in_array($sGeoType, $this->aGeoTypes);
}
/**
* Проверка объекта
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool
*/
public function CheckTarget($sTargetType, $iTargetId)
{
if (!$this->IsAllowTargetType($sTargetType)) {
return false;
}
$sMethod = 'CheckTarget' . func_camelize($sTargetType);
if (method_exists($this, $sMethod)) {
return $this->$sMethod($iTargetId);
}
return false;
}
/**
* Проверка на возможность нескольких связей
*
* @param string $sTargetType Тип владельца
* @return bool
*/
public function IsAllowTargetMulti($sTargetType)
{
if ($this->IsAllowTargetType($sTargetType)) {
if (isset($this->aTargetTypes[$sTargetType]['allow_multi']) and $this->aTargetTypes[$sTargetType]['allow_multi']) {
return true;
}
}
return false;
}
/**
* Добавляет связь объекта с гео-объектом в БД
*
* @param ModuleGeo_EntityTarget $oTarget Объект связи с владельцем
* @return ModuleGeo_EntityTarget|bool
*/
public function AddTarget($oTarget)
{
if ($this->oMapper->AddTarget($oTarget)) {
return $oTarget;
}
return false;
}
/**
* Создание связи
*
* @param ModuleGeo_EntityGeo $oGeoObject
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool|ModuleGeo_EntityTarget
*/
public function CreateTarget($oGeoObject, $sTargetType, $iTargetId)
{
/**
* Проверяем объект на валидность
*/
if (!$this->CheckTarget($sTargetType, $iTargetId)) {
return false;
}
/**
* Проверяем есть ли уже у этого объекта другие связи
*/
$aTargets = $this->GetTargets(array('target_type' => $sTargetType, 'target_id' => $iTargetId), 1, 1);
if ($aTargets['count']) {
if ($this->IsAllowTargetMulti($sTargetType)) {
/**
* Разрешено несколько связей
* Проверяем есть ли уже связь с данным гео-объектом, если есть то возвращаем его
*/
$aTargetSelf = $this->GetTargets(array(
'target_type' => $sTargetType,
'target_id' => $iTargetId,
'geo_type' => $oGeoObject->getType(),
'geo_id' => $oGeoObject->getId()
), 1, 1);
if (isset($aTargetSelf['collection'][0])) {
return $aTargetSelf['collection'][0];
}
} else {
/**
* Есть другие связи и несколько связей запрещено - удаляем имеющиеся связи
*/
$this->DeleteTargets(array('target_type' => $sTargetType, 'target_id' => $iTargetId));
}
}
/**
* Создаем связь
*/
$oTarget = Engine::GetEntity('ModuleGeo_EntityTarget');
$oTarget->setGeoType($oGeoObject->getType());
$oTarget->setGeoId($oGeoObject->getId());
$oTarget->setTargetType($sTargetType);
$oTarget->setTargetId($iTargetId);
if ($oGeoObject->getType() == 'city') {
$oTarget->setCountryId($oGeoObject->getCountryId());
$oTarget->setRegionId($oGeoObject->getRegionId());
$oTarget->setCityId($oGeoObject->getId());
} elseif ($oGeoObject->getType() == 'region') {
$oTarget->setCountryId($oGeoObject->getCountryId());
$oTarget->setRegionId($oGeoObject->getId());
} elseif ($oGeoObject->getType() == 'country') {
$oTarget->setCountryId($oGeoObject->getId());
}
return $this->AddTarget($oTarget);
}
/**
* Возвращает список связей по фильтру
*
* @param array $aFilter Фильтр
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetTargets($aFilter, $iCurrPage, $iPerPage)
{
return array(
'collection' => $this->oMapper->GetTargets($aFilter, $iCount, $iCurrPage, $iPerPage),
'count' => $iCount
);
}
/**
* Возвращает первый объект связи по объекту
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return null|ModuleGeo_EntityTarget
*/
public function GetTargetByTarget($sTargetType, $iTargetId)
{
$aTargets = $this->GetTargets(array('target_type' => $sTargetType, 'target_id' => $iTargetId), 1, 1);
if (isset($aTargets['collection'][0])) {
return $aTargets['collection'][0];
}
return null;
}
/**
* Возвращает список связей для списка объектов одного типа.
*
* @param string $sTargetType Тип владельца
* @param array $aTargetId Список ID владельцев
* @return array В качестве ключей используется ID объекта, в качестве значений массив связей этого объекта
*/
public function GetTargetsByTargetArray($sTargetType, $aTargetId)
{
if (!is_array($aTargetId)) {
$aTargetId = array($aTargetId);
}
if (!count($aTargetId)) {
return array();
}
$aResult = array();
$aTargets = $this->GetTargets(array('target_type' => $sTargetType, 'target_id' => $aTargetId), 1,
count($aTargetId));
if ($aTargets['count']) {
foreach ($aTargets['collection'] as $oTarget) {
$aResult[$oTarget->getTargetId()][] = $oTarget;
}
}
return $aResult;
}
/**
* Удаляет связи по фильтру
*
* @param array $aFilter Фильтр
* @return bool|int
*/
public function DeleteTargets($aFilter)
{
return $this->oMapper->DeleteTargets($aFilter);
}
/**
* Удаление всех связей объекта
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return bool|int
*/
public function DeleteTargetsByTarget($sTargetType, $iTargetId)
{
return $this->DeleteTargets(array('target_type' => $sTargetType, 'target_id' => $iTargetId));
}
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetCountries($aFilter, $aOrder, $iCurrPage, $iPerPage)
{
return array(
'collection' => $this->oMapper->GetCountries($aFilter, $aOrder, $iCount, $iCurrPage, $iPerPage),
'count' => $iCount
);
}
/**
* Возвращает список регионов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetRegions($aFilter, $aOrder, $iCurrPage, $iPerPage)
{
return array(
'collection' => $this->oMapper->GetRegions($aFilter, $aOrder, $iCount, $iCurrPage, $iPerPage),
'count' => $iCount
);
}
/**
* Возвращает список городов по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array('collection'=>array,'count'=>int)
*/
public function GetCities($aFilter, $aOrder, $iCurrPage, $iPerPage)
{
return array(
'collection' => $this->oMapper->GetCities($aFilter, $aOrder, $iCount, $iCurrPage, $iPerPage),
'count' => $iCount
);
}
/**
* Возвращает страну по ID
*
* @param int $iId ID страны
* @return ModuleGeo_EntityCountry|null
*/
public function GetCountryById($iId)
{
$aRes = $this->GetCountries(array('id' => $iId), array(), 1, 1);
if (isset($aRes['collection'][0])) {
return $aRes['collection'][0];
}
return null;
}
/**
* Возвращает регион по ID
*
* @param int $iId ID региона
* @return ModuleGeo_EntityRegion|null
*/
public function GetRegionById($iId)
{
$aRes = $this->GetRegions(array('id' => $iId), array(), 1, 1);
if (isset($aRes['collection'][0])) {
return $aRes['collection'][0];
}
return null;
}
/**
* Возвращает регион по ID
*
* @param int $iId ID города
* @return ModuleGeo_EntityCity|null
*/
public function GetCityById($iId)
{
$aRes = $this->GetCities(array('id' => $iId), array(), 1, 1);
if (isset($aRes['collection'][0])) {
return $aRes['collection'][0];
}
return null;
}
/**
* Возвращает гео-объект
*
* @param string $sType Тип гео-объекта
* @param int $iId ID гео-объекта
* @return ModuleGeo_EntityGeo|null
*/
public function GetGeoObject($sType, $iId)
{
$sType = strtolower($sType);
if (!$this->IsAllowGeoType($sType)) {
return null;
}
switch ($sType) {
case 'country':
return $this->GetCountryById($iId);
break;
case 'region':
return $this->GetRegionById($iId);
break;
case 'city':
return $this->GetCityById($iId);
break;
default:
return null;
}
}
/**
* Возвращает первый гео-объект для объекта
*
* @param string $sTargetType Тип владельца
* @param int $iTargetId ID владельца
* @return ModuleGeo_EntityCity|ModuleGeo_EntityCountry|ModuleGeo_EntityRegion|null
*/
public function GetGeoObjectByTarget($sTargetType, $iTargetId)
{
$aTargets = $this->GetTargets(array('target_type' => $sTargetType, 'target_id' => $iTargetId), 1, 1);
if (isset($aTargets['collection'][0])) {
$oTarget = $aTargets['collection'][0];
return $this->GetGeoObject($oTarget->getGeoType(), $oTarget->getGeoId());
}
return null;
}
/**
* Возвращает список стран сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCountriesByTargetType($sTargetType, $iLimit)
{
return $this->oMapper->GetGroupCountriesByTargetType($sTargetType, $iLimit);
}
/**
* Возвращает список городов сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCitiesByTargetType($sTargetType, $iLimit)
{
return $this->oMapper->GetGroupCitiesByTargetType($sTargetType, $iLimit);
}
/**
* Проверка объекта с типом "user"
* Название метода формируется автоматически
*
* @param int $iTargetId ID пользователя
* @return bool
*/
public function CheckTargetUser($iTargetId)
{
if ($oUser = $this->User_GetUserById($iTargetId)) {
return true;
}
return false;
}
}

View file

@ -25,6 +25,7 @@
* @package application.modules.geo
* @since 1.0
*/
class ModuleGeo_EntityCity extends ModuleGeo_EntityGeo {
class ModuleGeo_EntityCity extends ModuleGeo_EntityGeo
{
}

View file

@ -25,6 +25,7 @@
* @package application.modules.geo
* @since 1.0
*/
class ModuleGeo_EntityCountry extends ModuleGeo_EntityGeo {
class ModuleGeo_EntityCountry extends ModuleGeo_EntityGeo
{
}

View file

@ -25,97 +25,107 @@
* @package application.modules.geo
* @since 1.0
*/
class ModuleGeo_EntityGeo extends Entity {
class ModuleGeo_EntityGeo extends Entity
{
/**
* Возвращает имя гео-объекта в зависимости от языка
*
* @return string
*/
public function getName() {
$sName='';
$sLangDef=Config::get('lang.default');
if ($sLangDef=='ru') {
$sName=$this->getNameRu();
} elseif ($sLangDef=='en') {
$sName=$this->getNameEn();
}
/**
* Возвращает имя гео-объекта в зависимости от языка
*
* @return string
*/
public function getName()
{
$sName = '';
$sLangDef = Config::get('lang.default');
if ($sLangDef == 'ru') {
$sName = $this->getNameRu();
} elseif ($sLangDef == 'en') {
$sName = $this->getNameEn();
}
$sLang=Config::get('lang.current');
if ($sLang=='ru' and $this->getNameRu()) {
$sName=$this->getNameRu();
} elseif ($sLang=='en' and $this->getNameEn()) {
$sName=$this->getNameEn();
}
return $sName;
}
/**
* Возвращает тип гео-объекта
*
* @return null|string
*/
public function getType() {
if ($this instanceof ModuleGeo_EntityCity) {
return 'city';
} elseif ($this instanceof ModuleGeo_EntityRegion) {
return 'region';
} elseif ($this instanceof ModuleGeo_EntityCountry) {
return 'country';
}
return null;
}
/**
* Возвращает гео-объект страны
*
* @return ModuleGeo_EntityGeo|null
*/
public function getCountry() {
if ($this->getType()=='country') {
return $this;
}
if ($oCountry=$this->_getDataOne('country')) {
return $oCountry;
}
if ($this->getCountryId()) {
$oCountry=$this->Geo_GetCountryById($this->getCountryId());
return $this->_aData['country']=$oCountry;
}
return null;
}
/**
* Возвращает гео-объект региона
*
* @return ModuleGeo_EntityGeo|null
*/
public function getRegion() {
if ($this->getType()=='region') {
return $this;
}
if ($oRegion=$this->_getDataOne('region')) {
return $oRegion;
}
if ($this->getRegionId()) {
$oRegion=$this->Geo_GetRegionById($this->getRegionId());
return $this->_aData['region']=$oRegion;
}
return null;
}
/**
* Возвращает гео-объект города
*
* @return ModuleGeo_EntityGeo|null
*/
public function getCity() {
if ($this->getType()=='city') {
return $this;
}
if ($oCity=$this->_getDataOne('city')) {
return $oCity;
}
if ($this->getCityId()) {
$oCity=$this->Geo_GetCityById($this->getCityId());
return $this->_aData['city']=$oCity;
}
return null;
}
$sLang = Config::get('lang.current');
if ($sLang == 'ru' and $this->getNameRu()) {
$sName = $this->getNameRu();
} elseif ($sLang == 'en' and $this->getNameEn()) {
$sName = $this->getNameEn();
}
return $sName;
}
/**
* Возвращает тип гео-объекта
*
* @return null|string
*/
public function getType()
{
if ($this instanceof ModuleGeo_EntityCity) {
return 'city';
} elseif ($this instanceof ModuleGeo_EntityRegion) {
return 'region';
} elseif ($this instanceof ModuleGeo_EntityCountry) {
return 'country';
}
return null;
}
/**
* Возвращает гео-объект страны
*
* @return ModuleGeo_EntityGeo|null
*/
public function getCountry()
{
if ($this->getType() == 'country') {
return $this;
}
if ($oCountry = $this->_getDataOne('country')) {
return $oCountry;
}
if ($this->getCountryId()) {
$oCountry = $this->Geo_GetCountryById($this->getCountryId());
return $this->_aData['country'] = $oCountry;
}
return null;
}
/**
* Возвращает гео-объект региона
*
* @return ModuleGeo_EntityGeo|null
*/
public function getRegion()
{
if ($this->getType() == 'region') {
return $this;
}
if ($oRegion = $this->_getDataOne('region')) {
return $oRegion;
}
if ($this->getRegionId()) {
$oRegion = $this->Geo_GetRegionById($this->getRegionId());
return $this->_aData['region'] = $oRegion;
}
return null;
}
/**
* Возвращает гео-объект города
*
* @return ModuleGeo_EntityGeo|null
*/
public function getCity()
{
if ($this->getType() == 'city') {
return $this;
}
if ($oCity = $this->_getDataOne('city')) {
return $oCity;
}
if ($this->getCityId()) {
$oCity = $this->Geo_GetCityById($this->getCityId());
return $this->_aData['city'] = $oCity;
}
return null;
}
}

View file

@ -25,6 +25,7 @@
* @package application.modules.geo
* @since 1.0
*/
class ModuleGeo_EntityRegion extends ModuleGeo_EntityGeo {
class ModuleGeo_EntityRegion extends ModuleGeo_EntityGeo
{
}

View file

@ -25,6 +25,7 @@
* @package application.modules.geo
* @since 1.0
*/
class ModuleGeo_EntityTarget extends Entity {
class ModuleGeo_EntityTarget extends Entity
{
}

View file

@ -25,38 +25,42 @@
* @package application.modules.geo
* @since 1.0
*/
class ModuleGeo_MapperGeo extends Mapper {
/**
* Добавляет связь объекта с гео-объектом в БД
*
* @param ModuleGeo_EntityTarget $oTarget Объект связи с владельцем
* @return ModuleGeo_EntityTarget|bool
*/
public function AddTarget($oTarget) {
$sql = "INSERT INTO ".Config::Get('db.table.geo_target')." SET ?a ";
if ($this->oDb->query($sql,$oTarget->_getData())) {
return true;
}
return false;
}
/**
* Возвращает список связей по фильтру
*
* @param array $aFilter Фильтр
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetTargets($aFilter,&$iCount,$iCurrPage,$iPerPage) {
if (isset($aFilter['target_id']) and !is_array($aFilter['target_id'])) {
$aFilter['target_id']=array($aFilter['target_id']);
}
class ModuleGeo_MapperGeo extends Mapper
{
/**
* Добавляет связь объекта с гео-объектом в БД
*
* @param ModuleGeo_EntityTarget $oTarget Объект связи с владельцем
* @return ModuleGeo_EntityTarget|bool
*/
public function AddTarget($oTarget)
{
$sql = "INSERT INTO " . Config::Get('db.table.geo_target') . " SET ?a ";
if ($this->oDb->query($sql, $oTarget->_getData())) {
return true;
}
return false;
}
$sql = "SELECT
/**
* Возвращает список связей по фильтру
*
* @param array $aFilter Фильтр
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetTargets($aFilter, &$iCount, $iCurrPage, $iPerPage)
{
if (isset($aFilter['target_id']) and !is_array($aFilter['target_id'])) {
$aFilter['target_id'] = array($aFilter['target_id']);
}
$sql = "SELECT
*
FROM
".Config::Get('db.table.geo_target')."
" . Config::Get('db.table.geo_target') . "
WHERE
1 = 1
{ AND geo_type = ? }
@ -69,33 +73,36 @@ class ModuleGeo_MapperGeo extends Mapper {
ORDER BY target_id DESC
LIMIT ?d, ?d ;
";
$aResult=array();
if ($aRows=$this->oDb->selectPage($iCount,$sql,
isset($aFilter['geo_type']) ? $aFilter['geo_type'] : DBSIMPLE_SKIP,
isset($aFilter['geo_id']) ? $aFilter['geo_id'] : DBSIMPLE_SKIP,
isset($aFilter['target_type']) ? $aFilter['target_type'] : DBSIMPLE_SKIP,
(isset($aFilter['target_id']) and count($aFilter['target_id'])) ? $aFilter['target_id'] : DBSIMPLE_SKIP,
isset($aFilter['country_id']) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
isset($aFilter['region_id']) ? $aFilter['region_id'] : DBSIMPLE_SKIP,
isset($aFilter['city_id']) ? $aFilter['city_id'] : DBSIMPLE_SKIP,
$aResult = array();
if ($aRows = $this->oDb->selectPage($iCount, $sql,
isset($aFilter['geo_type']) ? $aFilter['geo_type'] : DBSIMPLE_SKIP,
isset($aFilter['geo_id']) ? $aFilter['geo_id'] : DBSIMPLE_SKIP,
isset($aFilter['target_type']) ? $aFilter['target_type'] : DBSIMPLE_SKIP,
(isset($aFilter['target_id']) and count($aFilter['target_id'])) ? $aFilter['target_id'] : DBSIMPLE_SKIP,
isset($aFilter['country_id']) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
isset($aFilter['region_id']) ? $aFilter['region_id'] : DBSIMPLE_SKIP,
isset($aFilter['city_id']) ? $aFilter['city_id'] : DBSIMPLE_SKIP,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aRow) {
$aResult[]=Engine::GetEntity('ModuleGeo_EntityTarget',$aRow);
}
}
return $aResult;
}
/**
* Возвращает список стран сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCountriesByTargetType($sTargetType,$iLimit) {
$sql = "
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aRow) {
$aResult[] = Engine::GetEntity('ModuleGeo_EntityTarget', $aRow);
}
}
return $aResult;
}
/**
* Возвращает список стран сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCountriesByTargetType($sTargetType, $iLimit)
{
$sql = "
SELECT
t.count,
g.*
@ -104,30 +111,32 @@ class ModuleGeo_MapperGeo extends Mapper {
count(*) as count,
country_id
FROM
".Config::Get('db.table.geo_target')."
" . Config::Get('db.table.geo_target') . "
WHERE target_type = ? and country_id IS NOT NULL
GROUP BY country_id ORDER BY count DESC LIMIT 0, ?d
) as t
JOIN ".Config::Get('db.table.geo_country')." as g on t.country_id=g.id
JOIN " . Config::Get('db.table.geo_country') . " as g on t.country_id=g.id
ORDER BY g.name_ru
";
$aResult=array();
if ($aRows=$this->oDb->select($sql,$sTargetType,$iLimit)) {
foreach ($aRows as $aRow) {
$aResult[]=Engine::GetEntity('ModuleGeo_EntityCountry',$aRow);
}
}
return $aResult;
}
/**
* Возвращает список городов сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCitiesByTargetType($sTargetType,$iLimit) {
$sql = "
$aResult = array();
if ($aRows = $this->oDb->select($sql, $sTargetType, $iLimit)) {
foreach ($aRows as $aRow) {
$aResult[] = Engine::GetEntity('ModuleGeo_EntityCountry', $aRow);
}
}
return $aResult;
}
/**
* Возвращает список городов сгруппированных по количеству использований в данном типе объектов
*
* @param string $sTargetType Тип владельца
* @param int $iLimit Количество элементов
* @return array
*/
public function GetGroupCitiesByTargetType($sTargetType, $iLimit)
{
$sql = "
SELECT
t.count,
g.*
@ -136,34 +145,36 @@ class ModuleGeo_MapperGeo extends Mapper {
count(*) as count,
city_id
FROM
".Config::Get('db.table.geo_target')."
" . Config::Get('db.table.geo_target') . "
WHERE target_type = ? and city_id IS NOT NULL
GROUP BY city_id ORDER BY count DESC LIMIT 0, ?d
) as t
JOIN ".Config::Get('db.table.geo_city')." as g on t.city_id=g.id
JOIN " . Config::Get('db.table.geo_city') . " as g on t.city_id=g.id
ORDER BY g.name_ru
";
$aResult=array();
if ($aRows=$this->oDb->select($sql,$sTargetType,$iLimit)) {
foreach ($aRows as $aRow) {
$aResult[]=Engine::GetEntity('ModuleGeo_EntityCity',$aRow);
}
}
return $aResult;
}
/**
* Удаляет связи по фильтру
*
* @param array $aFilter Фильтр
* @return bool|int
*/
public function DeleteTargets($aFilter) {
if (!$aFilter) {
return false;
}
$sql = "DELETE
$aResult = array();
if ($aRows = $this->oDb->select($sql, $sTargetType, $iLimit)) {
foreach ($aRows as $aRow) {
$aResult[] = Engine::GetEntity('ModuleGeo_EntityCity', $aRow);
}
}
return $aResult;
}
/**
* Удаляет связи по фильтру
*
* @param array $aFilter Фильтр
* @return bool|int
*/
public function DeleteTargets($aFilter)
{
if (!$aFilter) {
return false;
}
$sql = "DELETE
FROM
".Config::Get('db.table.geo_target')."
" . Config::Get('db.table.geo_target') . "
WHERE
1 = 1
{ AND geo_type = ? }
@ -174,46 +185,48 @@ class ModuleGeo_MapperGeo extends Mapper {
{ AND region_id = ?d }
{ AND city_id = ?d }
";
$res=$this->oDb->query($sql,
isset($aFilter['geo_type']) ? $aFilter['geo_type'] : DBSIMPLE_SKIP,
isset($aFilter['geo_id']) ? $aFilter['geo_id'] : DBSIMPLE_SKIP,
isset($aFilter['target_type']) ? $aFilter['target_type'] : DBSIMPLE_SKIP,
isset($aFilter['target_id']) ? $aFilter['target_id'] : DBSIMPLE_SKIP,
isset($aFilter['country_id']) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
isset($aFilter['region_id']) ? $aFilter['region_id'] : DBSIMPLE_SKIP,
isset($aFilter['city_id']) ? $aFilter['city_id'] : DBSIMPLE_SKIP
);
return $this->IsSuccessful($res);
}
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetCountries($aFilter,$aOrder,&$iCount,$iCurrPage,$iPerPage) {
$aOrderAllow=array('id','name_ru','name_en','sort');
$sOrder='';
foreach ($aOrder as $key=>$value) {
if (!in_array($key,$aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value,array('asc','desc'))) {
$sOrder.=" {$key} {$value},";
}
}
$sOrder=trim($sOrder,',');
if ($sOrder=='') {
$sOrder=' id desc ';
}
$res = $this->oDb->query($sql,
isset($aFilter['geo_type']) ? $aFilter['geo_type'] : DBSIMPLE_SKIP,
isset($aFilter['geo_id']) ? $aFilter['geo_id'] : DBSIMPLE_SKIP,
isset($aFilter['target_type']) ? $aFilter['target_type'] : DBSIMPLE_SKIP,
isset($aFilter['target_id']) ? $aFilter['target_id'] : DBSIMPLE_SKIP,
isset($aFilter['country_id']) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
isset($aFilter['region_id']) ? $aFilter['region_id'] : DBSIMPLE_SKIP,
isset($aFilter['city_id']) ? $aFilter['city_id'] : DBSIMPLE_SKIP
);
return $this->IsSuccessful($res);
}
$sql = "SELECT
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetCountries($aFilter, $aOrder, &$iCount, $iCurrPage, $iPerPage)
{
$aOrderAllow = array('id', 'name_ru', 'name_en', 'sort');
$sOrder = '';
foreach ($aOrder as $key => $value) {
if (!in_array($key, $aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value, array('asc', 'desc'))) {
$sOrder .= " {$key} {$value},";
}
}
$sOrder = trim($sOrder, ',');
if ($sOrder == '') {
$sOrder = ' id desc ';
}
$sql = "SELECT
*
FROM
".Config::Get('db.table.geo_country')."
" . Config::Get('db.table.geo_country') . "
WHERE
1 = 1
{ AND id = ?d }
@ -226,55 +239,58 @@ class ModuleGeo_MapperGeo extends Mapper {
ORDER by {$sOrder}
LIMIT ?d, ?d ;
";
$aResult=array();
if ($aRows=$this->oDb->selectPage($iCount,$sql,
isset($aFilter['id']) ? $aFilter['id'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru']) ? $aFilter['name_ru'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru_like']) ? $aFilter['name_ru_like'] : DBSIMPLE_SKIP,
isset($aFilter['name_en']) ? $aFilter['name_en'] : DBSIMPLE_SKIP,
isset($aFilter['name_en_like']) ? $aFilter['name_en_like'] : DBSIMPLE_SKIP,
isset($aFilter['code']) ? $aFilter['code'] : DBSIMPLE_SKIP,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aRow) {
$aResult[]=Engine::GetEntity('ModuleGeo_EntityCountry',$aRow);
}
}
return $aResult;
}
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetRegions($aFilter,$aOrder,&$iCount,$iCurrPage,$iPerPage) {
$aOrderAllow=array('id','name_ru','name_en','sort','country_id');
$sOrder='';
foreach ($aOrder as $key=>$value) {
if (!in_array($key,$aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value,array('asc','desc'))) {
$sOrder.=" {$key} {$value},";
}
}
$sOrder=trim($sOrder,',');
if ($sOrder=='') {
$sOrder=' id desc ';
}
$aResult = array();
if ($aRows = $this->oDb->selectPage($iCount, $sql,
isset($aFilter['id']) ? $aFilter['id'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru']) ? $aFilter['name_ru'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru_like']) ? $aFilter['name_ru_like'] : DBSIMPLE_SKIP,
isset($aFilter['name_en']) ? $aFilter['name_en'] : DBSIMPLE_SKIP,
isset($aFilter['name_en_like']) ? $aFilter['name_en_like'] : DBSIMPLE_SKIP,
isset($aFilter['code']) ? $aFilter['code'] : DBSIMPLE_SKIP,
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aRow) {
$aResult[] = Engine::GetEntity('ModuleGeo_EntityCountry', $aRow);
}
}
return $aResult;
}
if (isset($aFilter['country_id']) and !is_array($aFilter['country_id'])) {
$aFilter['country_id']=array($aFilter['country_id']);
}
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetRegions($aFilter, $aOrder, &$iCount, $iCurrPage, $iPerPage)
{
$aOrderAllow = array('id', 'name_ru', 'name_en', 'sort', 'country_id');
$sOrder = '';
foreach ($aOrder as $key => $value) {
if (!in_array($key, $aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value, array('asc', 'desc'))) {
$sOrder .= " {$key} {$value},";
}
}
$sOrder = trim($sOrder, ',');
if ($sOrder == '') {
$sOrder = ' id desc ';
}
$sql = "SELECT
if (isset($aFilter['country_id']) and !is_array($aFilter['country_id'])) {
$aFilter['country_id'] = array($aFilter['country_id']);
}
$sql = "SELECT
*
FROM
".Config::Get('db.table.geo_region')."
" . Config::Get('db.table.geo_region') . "
WHERE
1 = 1
{ AND id = ?d }
@ -287,58 +303,61 @@ class ModuleGeo_MapperGeo extends Mapper {
ORDER by {$sOrder}
LIMIT ?d, ?d ;
";
$aResult=array();
if ($aRows=$this->oDb->selectPage($iCount,$sql,
isset($aFilter['id']) ? $aFilter['id'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru']) ? $aFilter['name_ru'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru_like']) ? $aFilter['name_ru_like'] : DBSIMPLE_SKIP,
isset($aFilter['name_en']) ? $aFilter['name_en'] : DBSIMPLE_SKIP,
isset($aFilter['name_en_like']) ? $aFilter['name_en_like'] : DBSIMPLE_SKIP,
(isset($aFilter['country_id']) && count($aFilter['country_id'])) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aRow) {
$aResult[]=Engine::GetEntity('ModuleGeo_EntityRegion',$aRow);
}
}
return $aResult;
}
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetCities($aFilter,$aOrder,&$iCount,$iCurrPage,$iPerPage) {
$aOrderAllow=array('id','name_ru','name_en','sort','country_id','region_id');
$sOrder='';
foreach ($aOrder as $key=>$value) {
if (!in_array($key,$aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value,array('asc','desc'))) {
$sOrder.=" {$key} {$value},";
}
}
$sOrder=trim($sOrder,',');
if ($sOrder=='') {
$sOrder=' id desc ';
}
$aResult = array();
if ($aRows = $this->oDb->selectPage($iCount, $sql,
isset($aFilter['id']) ? $aFilter['id'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru']) ? $aFilter['name_ru'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru_like']) ? $aFilter['name_ru_like'] : DBSIMPLE_SKIP,
isset($aFilter['name_en']) ? $aFilter['name_en'] : DBSIMPLE_SKIP,
isset($aFilter['name_en_like']) ? $aFilter['name_en_like'] : DBSIMPLE_SKIP,
(isset($aFilter['country_id']) && count($aFilter['country_id'])) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aRow) {
$aResult[] = Engine::GetEntity('ModuleGeo_EntityRegion', $aRow);
}
}
return $aResult;
}
if (isset($aFilter['country_id']) and !is_array($aFilter['country_id'])) {
$aFilter['country_id']=array($aFilter['country_id']);
}
if (isset($aFilter['region_id']) and !is_array($aFilter['region_id'])) {
$aFilter['region_id']=array($aFilter['region_id']);
}
/**
* Возвращает список стран по фильтру
*
* @param array $aFilter Фильтр
* @param array $aOrder Сортировка
* @param int $iCount Возвращает количество элементов
* @param int $iCurrPage Номер страницы
* @param int $iPerPage Количество элементов на страницу
* @return array
*/
public function GetCities($aFilter, $aOrder, &$iCount, $iCurrPage, $iPerPage)
{
$aOrderAllow = array('id', 'name_ru', 'name_en', 'sort', 'country_id', 'region_id');
$sOrder = '';
foreach ($aOrder as $key => $value) {
if (!in_array($key, $aOrderAllow)) {
unset($aOrder[$key]);
} elseif (in_array($value, array('asc', 'desc'))) {
$sOrder .= " {$key} {$value},";
}
}
$sOrder = trim($sOrder, ',');
if ($sOrder == '') {
$sOrder = ' id desc ';
}
$sql = "SELECT
if (isset($aFilter['country_id']) and !is_array($aFilter['country_id'])) {
$aFilter['country_id'] = array($aFilter['country_id']);
}
if (isset($aFilter['region_id']) and !is_array($aFilter['region_id'])) {
$aFilter['region_id'] = array($aFilter['region_id']);
}
$sql = "SELECT
*
FROM
".Config::Get('db.table.geo_city')."
" . Config::Get('db.table.geo_city') . "
WHERE
1 = 1
{ AND id = ?d }
@ -352,21 +371,22 @@ class ModuleGeo_MapperGeo extends Mapper {
ORDER by {$sOrder}
LIMIT ?d, ?d ;
";
$aResult=array();
if ($aRows=$this->oDb->selectPage($iCount,$sql,
isset($aFilter['id']) ? $aFilter['id'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru']) ? $aFilter['name_ru'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru_like']) ? $aFilter['name_ru_like'] : DBSIMPLE_SKIP,
isset($aFilter['name_en']) ? $aFilter['name_en'] : DBSIMPLE_SKIP,
isset($aFilter['name_en_like']) ? $aFilter['name_en_like'] : DBSIMPLE_SKIP,
(isset($aFilter['country_id']) && count($aFilter['country_id'])) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
(isset($aFilter['region_id']) && count($aFilter['region_id'])) ? $aFilter['region_id'] : DBSIMPLE_SKIP,
($iCurrPage-1)*$iPerPage, $iPerPage
)) {
foreach ($aRows as $aRow) {
$aResult[]=Engine::GetEntity('ModuleGeo_EntityCity',$aRow);
}
}
return $aResult;
}
$aResult = array();
if ($aRows = $this->oDb->selectPage($iCount, $sql,
isset($aFilter['id']) ? $aFilter['id'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru']) ? $aFilter['name_ru'] : DBSIMPLE_SKIP,
isset($aFilter['name_ru_like']) ? $aFilter['name_ru_like'] : DBSIMPLE_SKIP,
isset($aFilter['name_en']) ? $aFilter['name_en'] : DBSIMPLE_SKIP,
isset($aFilter['name_en_like']) ? $aFilter['name_en_like'] : DBSIMPLE_SKIP,
(isset($aFilter['country_id']) && count($aFilter['country_id'])) ? $aFilter['country_id'] : DBSIMPLE_SKIP,
(isset($aFilter['region_id']) && count($aFilter['region_id'])) ? $aFilter['region_id'] : DBSIMPLE_SKIP,
($iCurrPage - 1) * $iPerPage, $iPerPage
)
) {
foreach ($aRows as $aRow) {
$aResult[] = Engine::GetEntity('ModuleGeo_EntityCity', $aRow);
}
}
return $aResult;
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,84 +25,91 @@
* @package application.modules.media
* @since 2.0
*/
class ModuleMedia_EntityMedia extends EntityORM {
class ModuleMedia_EntityMedia extends EntityORM
{
protected $aValidateRules=array(
protected $aValidateRules = array();
);
protected $aRelations = array(
'targets' => array(self::RELATION_TYPE_HAS_MANY, 'ModuleMedia_EntityTarget', 'media_id'),
);
protected $aRelations=array(
'targets' => array(self::RELATION_TYPE_HAS_MANY,'ModuleMedia_EntityTarget','media_id'),
);
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateAdd(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateAdd(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function beforeDelete()
{
if ($bResult = parent::beforeDelete()) {
/**
* Удаляем все связи
*/
$aTargets = $this->getTargets();
foreach ($aTargets as $oTarget) {
$oTarget->Delete();
}
/**
* Удаляем все файлы медиа
*/
$this->Media_DeleteFiles($this);
}
return $bResult;
}
protected function beforeDelete() {
if ($bResult=parent::beforeDelete()) {
/**
* Удаляем все связи
*/
$aTargets=$this->getTargets();
foreach($aTargets as $oTarget) {
$oTarget->Delete();
}
/**
* Удаляем все файлы медиа
*/
$this->Media_DeleteFiles($this);
}
return $bResult;
}
/**
* Возвращает URL до файла нужного размера, в основном используется для изображений
*
* @param null $sSize
*
* @return null
*/
public function getFileWebPath($sSize = null)
{
if ($this->getFilePath()) {
return $this->Media_GetFileWebPath($this, $sSize);
} else {
return null;
}
}
/**
* Возвращает URL до файла нужного размера, в основном используется для изображений
*
* @param null $sSize
*
* @return null
*/
public function getFileWebPath($sSize=null) {
if ($this->getFilePath()) {
return $this->Media_GetFileWebPath($this,$sSize);
} else {
return null;
}
}
public function getData()
{
$aData = @unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData = array();
}
return $aData;
}
public function getData() {
$aData=@unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData=array();
}
return $aData;
}
public function setData($aRules)
{
$this->_aData['data'] = @serialize($aRules);
}
public function setData($aRules) {
$this->_aData['data']=@serialize($aRules);
}
public function getDataOne($sKey)
{
$aData = $this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
public function getDataOne($sKey) {
$aData=$this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
public function setDataOne($sKey, $mValue)
{
$aData = $this->getData();
$aData[$sKey] = $mValue;
$this->setData($aData);
}
public function setDataOne($sKey,$mValue) {
$aData=$this->getData();
$aData[$sKey]=$mValue;
$this->setData($aData);
}
public function getRelationTarget() {
return $this->_getDataOne('_relation_entity');
}
public function getRelationTarget()
{
return $this->_getDataOne('_relation_entity');
}
}

View file

@ -25,61 +25,66 @@
* @package application.modules.media
* @since 2.0
*/
class ModuleMedia_EntityTarget extends EntityORM {
class ModuleMedia_EntityTarget extends EntityORM
{
protected $aValidateRules=array(
protected $aValidateRules = array();
);
protected $aRelations = array(
'media' => array(self::RELATION_TYPE_BELONGS_TO, 'ModuleMedia_EntityMedia', 'media_id'),
);
protected $aRelations=array(
'media' => array(self::RELATION_TYPE_BELONGS_TO,'ModuleMedia_EntityMedia','media_id'),
);
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateAdd(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateAdd(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
public function getData() {
$aData=@unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData=array();
}
return $aData;
}
public function getData()
{
$aData = @unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData = array();
}
return $aData;
}
public function setData($aRules) {
$this->_aData['data']=@serialize($aRules);
}
public function setData($aRules)
{
$this->_aData['data'] = @serialize($aRules);
}
public function getDataOne($sKey) {
$aData=$this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
public function getDataOne($sKey)
{
$aData = $this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
public function setDataOne($sKey,$mValue) {
$aData=$this->getData();
$aData[$sKey]=$mValue;
$this->setData($aData);
}
public function setDataOne($sKey, $mValue)
{
$aData = $this->getData();
$aData[$sKey] = $mValue;
$this->setData($aData);
}
public function getPreviewImageItemsWebPath() {
$aPreviewItems=array();
$sPathbase=$this->getDataOne('image_preview');
$aSizes=$this->getDataOne('image_preview_sizes');
if ($sPathbase and $aSizes) {
foreach($aSizes as $aSize) {
$aPreviewItems[]=$this->Media_GetImageWebPath($sPathbase,$aSize);
}
}
return $aPreviewItems;
}
public function getPreviewImageItemsWebPath()
{
$aPreviewItems = array();
$sPathbase = $this->getDataOne('image_preview');
$aSizes = $this->getDataOne('image_preview_sizes');
if ($sPathbase and $aSizes) {
foreach ($aSizes as $aSize) {
$aPreviewItems[] = $this->Media_GetImageWebPath($sPathbase, $aSize);
}
}
return $aPreviewItems;
}
}

View file

@ -25,15 +25,17 @@
* @package application.modules.media
* @since 2.0
*/
class ModuleMedia_MapperMedia extends Mapper {
class ModuleMedia_MapperMedia extends Mapper
{
public function GetMediaByTarget($sTargetType,$iTargetId,$iUserId=null) {
$sFieldsJoinReturn=$this->GetFieldsRelationTarget();
$sql = "SELECT
public function GetMediaByTarget($sTargetType, $iTargetId, $iUserId = null)
{
$sFieldsJoinReturn = $this->GetFieldsRelationTarget();
$sql = "SELECT
{$sFieldsJoinReturn},
m.*
FROM ".Config::Get('db.table.media_target')." AS t
JOIN ".Config::Get('db.table.media')." as m on ( m.id=t.media_id { and m.user_id = ?d } )
FROM " . Config::Get('db.table.media_target') . " AS t
JOIN " . Config::Get('db.table.media') . " as m on ( m.id=t.media_id { and m.user_id = ?d } )
WHERE
t.target_id = ?d
AND
@ -42,82 +44,86 @@ class ModuleMedia_MapperMedia extends Mapper {
m.id desc
limit 0,500";
$aResult = array();
if ($aRows = $this->oDb->select($sql,$iUserId ? $iUserId : DBSIMPLE_SKIP,$iTargetId, $sTargetType)) {
$aResult=$this->PrepareResultTarget($aRows);
}
return $aResult;
}
$aResult = array();
if ($aRows = $this->oDb->select($sql, $iUserId ? $iUserId : DBSIMPLE_SKIP, $iTargetId, $sTargetType)) {
$aResult = $this->PrepareResultTarget($aRows);
}
return $aResult;
}
public function GetMediaByTargetTmp($sTargetTmp,$iUserId=null) {
$sFieldsJoinReturn=$this->GetFieldsRelationTarget();
$sql = "SELECT
public function GetMediaByTargetTmp($sTargetTmp, $iUserId = null)
{
$sFieldsJoinReturn = $this->GetFieldsRelationTarget();
$sql = "SELECT
{$sFieldsJoinReturn},
m.*
FROM ".Config::Get('db.table.media_target')." AS t
JOIN ".Config::Get('db.table.media')." as m on ( m.id=t.media_id { and m.user_id = ?d } )
FROM " . Config::Get('db.table.media_target') . " AS t
JOIN " . Config::Get('db.table.media') . " as m on ( m.id=t.media_id { and m.user_id = ?d } )
WHERE
t.target_tmp = ?
ORDER BY
m.id desc
limit 0,500";
$aResult = array();
if ($aRows = $this->oDb->select($sql,$iUserId ? $iUserId : DBSIMPLE_SKIP,$sTargetTmp)) {
$aResult=$this->PrepareResultTarget($aRows);
}
return $aResult;
}
$aResult = array();
if ($aRows = $this->oDb->select($sql, $iUserId ? $iUserId : DBSIMPLE_SKIP, $sTargetTmp)) {
$aResult = $this->PrepareResultTarget($aRows);
}
return $aResult;
}
public function RemoveTargetByTypeAndId($sTargetType,$iTargetId) {
$sql = "DELETE
FROM ".Config::Get('db.table.media_target')."
public function RemoveTargetByTypeAndId($sTargetType, $iTargetId)
{
$sql = "DELETE
FROM " . Config::Get('db.table.media_target') . "
WHERE
target_id = ?d
AND
target_type = ?
";
if ($this->oDb->query($sql,$iTargetId,$sTargetType)!==false) {
return true;
}
return false;
}
if ($this->oDb->query($sql, $iTargetId, $sTargetType) !== false) {
return true;
}
return false;
}
protected function GetFieldsRelationTarget() {
$oEntityJoinSample=Engine::GetEntity('ModuleMedia_EntityTarget');
/**
* Формируем список полей для возврата у таблице связей
*/
$aFieldsJoinReturn=$oEntityJoinSample->_getFields();
foreach($aFieldsJoinReturn as $k=>$sField) {
if (!is_numeric($k)) {
// Удаляем служебные (примари) поля
unset($aFieldsJoinReturn[$k]);
continue;
}
$aFieldsJoinReturn[$k]="t.`{$sField}` as t_join_{$sField}";
}
$sFieldsJoinReturn=join(', ',$aFieldsJoinReturn);
return $sFieldsJoinReturn;
}
protected function GetFieldsRelationTarget()
{
$oEntityJoinSample = Engine::GetEntity('ModuleMedia_EntityTarget');
/**
* Формируем список полей для возврата у таблице связей
*/
$aFieldsJoinReturn = $oEntityJoinSample->_getFields();
foreach ($aFieldsJoinReturn as $k => $sField) {
if (!is_numeric($k)) {
// Удаляем служебные (примари) поля
unset($aFieldsJoinReturn[$k]);
continue;
}
$aFieldsJoinReturn[$k] = "t.`{$sField}` as t_join_{$sField}";
}
$sFieldsJoinReturn = join(', ', $aFieldsJoinReturn);
return $sFieldsJoinReturn;
}
protected function PrepareResultTarget($aRows) {
$aResult=array();
foreach ($aRows as $aRow) {
$aData=array();
$aDataRelation=array();
foreach($aRow as $k=>$v) {
if (strpos($k,'t_join_')===0) {
$aDataRelation[str_replace('t_join_','',$k)]=$v;
} else {
$aData[$k]=$v;
}
}
$aData['_relation_entity']=Engine::GetEntity('ModuleMedia_EntityTarget',$aDataRelation);
$oEntity=Engine::GetEntity('ModuleMedia_EntityMedia',$aData);
$oEntity->_SetIsNew(false);
$aResult[]=$oEntity;
}
return $aResult;
}
protected function PrepareResultTarget($aRows)
{
$aResult = array();
foreach ($aRows as $aRow) {
$aData = array();
$aDataRelation = array();
foreach ($aRow as $k => $v) {
if (strpos($k, 't_join_') === 0) {
$aDataRelation[str_replace('t_join_', '', $k)] = $v;
} else {
$aData[$k] = $v;
}
}
$aData['_relation_entity'] = Engine::GetEntity('ModuleMedia_EntityTarget', $aDataRelation);
$oEntity = Engine::GetEntity('ModuleMedia_EntityMedia', $aData);
$oEntity->_SetIsNew(false);
$aResult[] = $oEntity;
}
return $aResult;
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,119 +25,146 @@
* @package application.modules.notify
* @since 1.0
*/
class ModuleNotify_EntityTask extends Entity {
/**
* Возвращает ID задания
*
* @return int|null
*/
public function getTaskId() {
return $this->_getDataOne('notify_task_id');
}
/**
* Возвращает емайл
*
* @return string|null
*/
public function getUserMail() {
return $this->_getDataOne('user_mail');
}
/**
* Возвращает логин пользователя
*
* @return string|null
*/
public function getUserLogin() {
return $this->_getDataOne('user_login');
}
/**
* Возвращает текст сообщения
*
* @return string|null
*/
public function getNotifyText() {
return $this->_getDataOne('notify_text');
}
/**
* Возвращает дату создания сообщения
*
* @return string|null
*/
public function getDateCreated() {
return $this->_getDataOne('date_created');
}
/**
* Возвращает статус отправки
*
* @return int|null
*/
public function getTaskStatus() {
return $this->_getDataOne('notify_task_status');
}
/**
* Возвращает тему сообщения
*
* @return string|null
*/
public function getNotifySubject() {
return $this->_getDataOne('notify_subject');
}
class ModuleNotify_EntityTask extends Entity
{
/**
* Возвращает ID задания
*
* @return int|null
*/
public function getTaskId()
{
return $this->_getDataOne('notify_task_id');
}
/**
* Возвращает емайл
*
* @return string|null
*/
public function getUserMail()
{
return $this->_getDataOne('user_mail');
}
/**
* Возвращает логин пользователя
*
* @return string|null
*/
public function getUserLogin()
{
return $this->_getDataOne('user_login');
}
/**
* Возвращает текст сообщения
*
* @return string|null
*/
public function getNotifyText()
{
return $this->_getDataOne('notify_text');
}
/**
* Возвращает дату создания сообщения
*
* @return string|null
*/
public function getDateCreated()
{
return $this->_getDataOne('date_created');
}
/**
* Возвращает статус отправки
*
* @return int|null
*/
public function getTaskStatus()
{
return $this->_getDataOne('notify_task_status');
}
/**
* Возвращает тему сообщения
*
* @return string|null
*/
public function getNotifySubject()
{
return $this->_getDataOne('notify_subject');
}
/**
* Устанавливает ID задания
*
* @param int $data
*/
public function setTaskId($data) {
$this->_aData['notify_task_id']=$data;
}
/**
* Устанавливает емайл
*
* @param string $data
*/
public function setUserMail($data) {
$this->_aData['user_mail']=$data;
}
/**
* Устанавливает логин
*
* @param string $data
*/
public function setUserLogin($data) {
$this->_aData['user_login']=$data;
}
/**
* Устанавливает текст уведомления
*
* @param string $data
*/
public function setNotifyText($data) {
$this->_aData['notify_text']=$data;
}
/**
* Устанавливает дату создания задания
*
* @param string $data
*/
public function setDateCreated($data) {
$this->_aData['date_created']=$data;
}
/**
* Устанавливает статус задания
*
* @param int $data
*/
public function setTaskStatus($data) {
$this->_aData['notify_task_status']=$data;
}
/**
* Устанавливает тему сообщения
*
* @param string $data
*/
public function setNotifySubject($data) {
$this->_aData['notify_subject']=$data;
}
/**
* Устанавливает ID задания
*
* @param int $data
*/
public function setTaskId($data)
{
$this->_aData['notify_task_id'] = $data;
}
/**
* Устанавливает емайл
*
* @param string $data
*/
public function setUserMail($data)
{
$this->_aData['user_mail'] = $data;
}
/**
* Устанавливает логин
*
* @param string $data
*/
public function setUserLogin($data)
{
$this->_aData['user_login'] = $data;
}
/**
* Устанавливает текст уведомления
*
* @param string $data
*/
public function setNotifyText($data)
{
$this->_aData['notify_text'] = $data;
}
/**
* Устанавливает дату создания задания
*
* @param string $data
*/
public function setDateCreated($data)
{
$this->_aData['date_created'] = $data;
}
/**
* Устанавливает статус задания
*
* @param int $data
*/
public function setTaskStatus($data)
{
$this->_aData['notify_task_status'] = $data;
}
/**
* Устанавливает тему сообщения
*
* @param string $data
*/
public function setNotifySubject($data)
{
$this->_aData['notify_subject'] = $data;
}
}

View file

@ -25,113 +25,124 @@
* @package application.modules.notify
* @since 1.0
*/
class ModuleNotify_MapperNotify extends Mapper {
/**
* Добавляет задание
*
* @param ModuleNotify_EntityTask $oNotifyTask Объект задания
* @return bool
*/
public function AddTask(ModuleNotify_EntityTask $oNotifyTask) {
$sql = "
INSERT INTO ".Config::Get('db.table.notify_task')."
class ModuleNotify_MapperNotify extends Mapper
{
/**
* Добавляет задание
*
* @param ModuleNotify_EntityTask $oNotifyTask Объект задания
* @return bool
*/
public function AddTask(ModuleNotify_EntityTask $oNotifyTask)
{
$sql = "
INSERT INTO " . Config::Get('db.table.notify_task') . "
( user_login, user_mail, notify_subject, notify_text, date_created, notify_task_status )
VALUES
( ?, ?, ?, ?, ?, ?d )
";
if ($this->oDb->query(
$sql,
$oNotifyTask->getUserLogin(),
$oNotifyTask->getUserMail(),
$oNotifyTask->getNotifySubject(),
$oNotifyTask->getNotifyText(),
$oNotifyTask->getDateCreated(),
$oNotifyTask->getTaskStatus()
)===0) {
return true;
}
return false;
}
/**
* Добавляет задания списком
*
* @param array $aTasks Список объектов заданий
* @return bool
*/
public function AddTaskArray($aTasks) {
if(!is_array($aTasks)&&count($aTasks)==0) {
return false;
}
if ($this->oDb->query(
$sql,
$oNotifyTask->getUserLogin(),
$oNotifyTask->getUserMail(),
$oNotifyTask->getNotifySubject(),
$oNotifyTask->getNotifyText(),
$oNotifyTask->getDateCreated(),
$oNotifyTask->getTaskStatus()
) === 0
) {
return true;
}
return false;
}
$aValues=array();
foreach ($aTasks as $oTask) {
$aValues[]="(".implode(',',
array(
$this->oDb->escape($oTask->getUserLogin()),
$this->oDb->escape($oTask->getUserMail()),
$this->oDb->escape($oTask->getNotifySubject()),
$this->oDb->escape($oTask->getNotifyText()),
$this->oDb->escape($oTask->getDateCreated()),
$this->oDb->escape($oTask->getTaskStatus())
)
).")";
}
$sql = "
INSERT INTO ".Config::Get('db.table.notify_task')."
/**
* Добавляет задания списком
*
* @param array $aTasks Список объектов заданий
* @return bool
*/
public function AddTaskArray($aTasks)
{
if (!is_array($aTasks) && count($aTasks) == 0) {
return false;
}
$aValues = array();
foreach ($aTasks as $oTask) {
$aValues[] = "(" . implode(',',
array(
$this->oDb->escape($oTask->getUserLogin()),
$this->oDb->escape($oTask->getUserMail()),
$this->oDb->escape($oTask->getNotifySubject()),
$this->oDb->escape($oTask->getNotifyText()),
$this->oDb->escape($oTask->getDateCreated()),
$this->oDb->escape($oTask->getTaskStatus())
)
) . ")";
}
$sql = "
INSERT INTO " . Config::Get('db.table.notify_task') . "
( user_login, user_mail, notify_subject, notify_text, date_created, notify_task_status )
VALUES
".implode(', ', $aValues);
" . implode(', ', $aValues);
return $this->oDb->query($sql);
}
/**
* Удаляет задание
*
* @param ModuleNotify_EntityTask $oNotifyTask Объект задания
* @return bool
*/
public function DeleteTask(ModuleNotify_EntityTask $oNotifyTask) {
$sql = "
DELETE FROM ".Config::Get('db.table.notify_task')."
return $this->oDb->query($sql);
}
/**
* Удаляет задание
*
* @param ModuleNotify_EntityTask $oNotifyTask Объект задания
* @return bool
*/
public function DeleteTask(ModuleNotify_EntityTask $oNotifyTask)
{
$sql = "
DELETE FROM " . Config::Get('db.table.notify_task') . "
WHERE
notify_task_id = ?d
";
$res=$this->oDb->query($sql,$oNotifyTask->getTaskId());
return $this->IsSuccessful($res);
}
/**
* Удаляет отложенные Notify-задания по списку идентификаторов
*
* @param array $aTaskId Список ID заданий на отправку
* @return bool
*/
public function DeleteTaskByArrayId($aTaskId) {
$sql = "
DELETE FROM ".Config::Get('db.table.notify_task')."
$res = $this->oDb->query($sql, $oNotifyTask->getTaskId());
return $this->IsSuccessful($res);
}
/**
* Удаляет отложенные Notify-задания по списку идентификаторов
*
* @param array $aTaskId Список ID заданий на отправку
* @return bool
*/
public function DeleteTaskByArrayId($aTaskId)
{
$sql = "
DELETE FROM " . Config::Get('db.table.notify_task') . "
WHERE
notify_task_id IN(?a)
";
$res=$this->oDb->query($sql,$aTaskId);
return $this->IsSuccessful($res);
}
/**
* Получает массив заданий на публикацию из базы с указанным количественным ограничением (выборка FIFO)
*
* @param int $iLimit Количество
* @return array
*/
public function GetTasks($iLimit) {
$sql = "SELECT *
FROM ".Config::Get('db.table.notify_task')."
$res = $this->oDb->query($sql, $aTaskId);
return $this->IsSuccessful($res);
}
/**
* Получает массив заданий на публикацию из базы с указанным количественным ограничением (выборка FIFO)
*
* @param int $iLimit Количество
* @return array
*/
public function GetTasks($iLimit)
{
$sql = "SELECT *
FROM " . Config::Get('db.table.notify_task') . "
ORDER BY date_created ASC
LIMIT ?d";
$aTasks=array();
if ($aRows=$this->oDb->select($sql,$iLimit)) {
foreach ($aRows as $aTask) {
$aTasks[]=Engine::GetEntity('Notify_Task',$aTask);
}
}
return $aTasks;
}
$aTasks = array();
if ($aRows = $this->oDb->select($sql, $iLimit)) {
foreach ($aRows as $aTask) {
$aTasks[] = Engine::GetEntity('Notify_Task', $aTask);
}
}
return $aTasks;
}
}

View file

@ -25,154 +25,171 @@
* @package application.modules.poll
* @since 2.0
*/
class ModulePoll extends ModuleORM {
class ModulePoll extends ModuleORM
{
/**
* Объект текущего пользователя
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
/**
* Объект текущего пользователя
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent;
protected $aTargetTypes=array(
'topic'=>array(),
);
protected $aTargetTypes = array(
'topic' => array(),
);
/**
* Инициализация
*
*/
public function Init() {
parent::Init();
$this->oUserCurrent=$this->User_GetUserCurrent();
}
/**
* Возвращает список типов объектов
*
* @return array
*/
public function GetTargetTypes() {
return $this->aTargetTypes;
}
/**
* Добавляет в разрешенные новый тип
*
* @param string $sTargetType Тип
* @param array $aParams Параметры
* @return bool
*/
public function AddTargetType($sTargetType,$aParams=array()) {
if (!array_key_exists($sTargetType,$this->aTargetTypes)) {
$this->aTargetTypes[$sTargetType]=$aParams;
return true;
}
return false;
}
/**
* Проверяет разрешен ли данный тип
*
* @param string $sTargetType Тип
* @return bool
*/
public function IsAllowTargetType($sTargetType) {
return in_array($sTargetType,array_keys($this->aTargetTypes));
}
/**
* Возвращает парметры нужного типа
*
* @param string $sTargetType
*
* @return mixed
*/
public function GetTargetTypeParams($sTargetType) {
if ($this->IsAllowTargetType($sTargetType)) {
return $this->aTargetTypes[$sTargetType];
}
}
/**
* Проверка объекта target - владелец медиа
*
* @param string $sTargetType Тип
* @param int $iTargetId ID владельца
* @return bool
*/
public function CheckTarget($sTargetType,$iTargetId) {
if (!$this->IsAllowTargetType($sTargetType)) {
return false;
}
$sMethod = 'CheckTarget'.func_camelize($sTargetType);
if (method_exists($this,$sMethod)) {
return $this->$sMethod($iTargetId);
}
return false;
}
/**
* Заменяет временный идентификатор на необходимый ID объекта
*
* @param string $sTargetType
* @param string $sTargetId
* @param null|string $sTargetTmp Если не задан, то берется их куки "poll_target_tmp_{$sTargetType}"
*/
public function ReplaceTargetTmpById($sTargetType,$sTargetId,$sTargetTmp=null) {
$sCookieKey='poll_target_tmp_'.$sTargetType;
if (is_null($sTargetTmp) and isset($_COOKIE[$sCookieKey])) {
$sTargetTmp=$_COOKIE[$sCookieKey];
setcookie($sCookieKey,null,-1,Config::Get('sys.cookie.path'),Config::Get('sys.cookie.host'));
}
if (is_string($sTargetTmp)) {
$aPollItems=$this->Poll_GetPollItemsByTargetTmpAndTargetType($sTargetTmp,$sTargetType);
foreach($aPollItems as $oPoll) {
$oPoll->setTargetTmp(null);
$oPoll->setTargetId($sTargetId);
$oPoll->Update();
}
}
}
/**
* Возвращает список опросов для объекта
*
* @param string $sTargetType
* @param string $sTargetId
*
* @return mixed
*/
public function GetPollItemsByTarget($sTargetType,$sTargetId) {
$aFilter=array(
'target_type'=>$sTargetType,
'target_id'=>$sTargetId,
'#with'=>array('answers')
);
if ($this->oUserCurrent) {
$aFilter['#with']['vote_current']=array('user_id'=>$this->oUserCurrent->getId(),'#value-default'=>false);
} else {
$aFilter['#with']['vote_current']=array('#value-set'=>false);
}
$aPollItems=$this->Poll_GetPollItemsByFilter($aFilter);
return $aPollItems;
}
/**
* Инициализация
*
*/
public function Init()
{
parent::Init();
$this->oUserCurrent = $this->User_GetUserCurrent();
}
/**
* Возвращает список типов объектов
*
* @return array
*/
public function GetTargetTypes()
{
return $this->aTargetTypes;
}
/**
* Добавляет в разрешенные новый тип
*
* @param string $sTargetType Тип
* @param array $aParams Параметры
* @return bool
*/
public function AddTargetType($sTargetType, $aParams = array())
{
if (!array_key_exists($sTargetType, $this->aTargetTypes)) {
$this->aTargetTypes[$sTargetType] = $aParams;
return true;
}
return false;
}
/**
* Проверяет разрешен ли данный тип
*
* @param string $sTargetType Тип
* @return bool
*/
public function IsAllowTargetType($sTargetType)
{
return in_array($sTargetType, array_keys($this->aTargetTypes));
}
/**
* Возвращает парметры нужного типа
*
* @param string $sTargetType
*
* @return mixed
*/
public function GetTargetTypeParams($sTargetType)
{
if ($this->IsAllowTargetType($sTargetType)) {
return $this->aTargetTypes[$sTargetType];
}
}
/**
* Проверка объекта target - владелец медиа
*
* @param string $sTargetType Тип
* @param int $iTargetId ID владельца
* @return bool
*/
public function CheckTarget($sTargetType, $iTargetId)
{
if (!$this->IsAllowTargetType($sTargetType)) {
return false;
}
$sMethod = 'CheckTarget' . func_camelize($sTargetType);
if (method_exists($this, $sMethod)) {
return $this->$sMethod($iTargetId);
}
return false;
}
/**
* Заменяет временный идентификатор на необходимый ID объекта
*
* @param string $sTargetType
* @param string $sTargetId
* @param null|string $sTargetTmp Если не задан, то берется их куки "poll_target_tmp_{$sTargetType}"
*/
public function ReplaceTargetTmpById($sTargetType, $sTargetId, $sTargetTmp = null)
{
$sCookieKey = 'poll_target_tmp_' . $sTargetType;
if (is_null($sTargetTmp) and isset($_COOKIE[$sCookieKey])) {
$sTargetTmp = $_COOKIE[$sCookieKey];
setcookie($sCookieKey, null, -1, Config::Get('sys.cookie.path'), Config::Get('sys.cookie.host'));
}
if (is_string($sTargetTmp)) {
$aPollItems = $this->Poll_GetPollItemsByTargetTmpAndTargetType($sTargetTmp, $sTargetType);
foreach ($aPollItems as $oPoll) {
$oPoll->setTargetTmp(null);
$oPoll->setTargetId($sTargetId);
$oPoll->Update();
}
}
}
/**
* Возвращает список опросов для объекта
*
* @param string $sTargetType
* @param string $sTargetId
*
* @return mixed
*/
public function GetPollItemsByTarget($sTargetType, $sTargetId)
{
$aFilter = array(
'target_type' => $sTargetType,
'target_id' => $sTargetId,
'#with' => array('answers')
);
if ($this->oUserCurrent) {
$aFilter['#with']['vote_current'] = array('user_id' => $this->oUserCurrent->getId(),
'#value-default' => false
);
} else {
$aFilter['#with']['vote_current'] = array('#value-set' => false);
}
$aPollItems = $this->Poll_GetPollItemsByFilter($aFilter);
return $aPollItems;
}
/**
* Проверка владельца с типом "topic"
* Название метода формируется автоматически
*
* @param int $iTargetId ID владельца
* @return bool
*/
public function CheckTargetTopic($iTargetId) {
if ($oTopic=$this->Topic_GetTopicById($iTargetId)) {
if (!$oTopicType=$this->Topic_GetTopicType($oTopic->getType()) or !$oTopicType->getParam('allow_poll')) {
return false;
}
/**
* Проверяем права на редактирование топика
*/
if ($this->ACL_IsAllowEditTopic($oTopic,$this->oUserCurrent)) {
return true;
}
}
return false;
}
/**
* Проверка владельца с типом "topic"
* Название метода формируется автоматически
*
* @param int $iTargetId ID владельца
* @return bool
*/
public function CheckTargetTopic($iTargetId)
{
if ($oTopic = $this->Topic_GetTopicById($iTargetId)) {
if (!$oTopicType = $this->Topic_GetTopicType($oTopic->getType()) or !$oTopicType->getParam('allow_poll')) {
return false;
}
/**
* Проверяем права на редактирование топика
*/
if ($this->ACL_IsAllowEditTopic($oTopic, $this->oUserCurrent)) {
return true;
}
}
return false;
}
}

View file

@ -25,29 +25,32 @@
* @package application.modules.poll
* @since 2.0
*/
class ModulePoll_EntityAnswer extends EntityORM {
class ModulePoll_EntityAnswer extends EntityORM
{
protected $aValidateRules=array(
array('title','string','allowEmpty'=>false,'min'=>1,'max'=>250),
array('title','check_title'),
);
protected $aValidateRules = array(
array('title', 'string', 'allowEmpty' => false, 'min' => 1, 'max' => 250),
array('title', 'check_title'),
);
protected $aRelations=array(
'poll' => array(self::RELATION_TYPE_BELONGS_TO,'ModulePoll_EntityPoll','poll_id'),
);
protected $aRelations = array(
'poll' => array(self::RELATION_TYPE_BELONGS_TO, 'ModulePoll_EntityPoll', 'poll_id'),
);
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
public function ValidateCheckTitle() {
$this->setTitle(htmlspecialchars($this->getTitle()));
return true;
}
public function ValidateCheckTitle()
{
$this->setTitle(htmlspecialchars($this->getTitle()));
return true;
}
}

View file

@ -25,230 +25,253 @@
* @package application.modules.poll
* @since 2.0
*/
class ModulePoll_EntityPoll extends EntityORM {
class ModulePoll_EntityPoll extends EntityORM
{
protected $aValidateRules=array(
array('title','string','allowEmpty'=>false,'min'=>3,'max'=>250,'on'=>array('create','update')),
array('count_answer_max','number','allowEmpty'=>true,'integerOnly'=>true,'min'=>0,'on'=>array('create','update')),
array('type','check_type','on'=>array('create','update')),
array('answers_raw','check_answers_raw','on'=>array('create','update')),
array('target_raw','check_target_raw','on'=>array('create')),
array('title','check_title','on'=>array('create','update')),
);
protected $aValidateRules = array(
array('title', 'string', 'allowEmpty' => false, 'min' => 3, 'max' => 250, 'on' => array('create', 'update')),
array(
'count_answer_max',
'number',
'allowEmpty' => true,
'integerOnly' => true,
'min' => 0,
'on' => array('create', 'update')
),
array('type', 'check_type', 'on' => array('create', 'update')),
array('answers_raw', 'check_answers_raw', 'on' => array('create', 'update')),
array('target_raw', 'check_target_raw', 'on' => array('create')),
array('title', 'check_title', 'on' => array('create', 'update')),
);
protected $aRelations=array(
'answers' => array(self::RELATION_TYPE_HAS_MANY,'ModulePoll_EntityAnswer','poll_id'),
'vote_current' => array(self::RELATION_TYPE_HAS_ONE,'ModulePoll_EntityVote','poll_id'),
);
protected $aRelations = array(
'answers' => array(self::RELATION_TYPE_HAS_MANY, 'ModulePoll_EntityAnswer', 'poll_id'),
'vote_current' => array(self::RELATION_TYPE_HAS_ONE, 'ModulePoll_EntityVote', 'poll_id'),
);
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function afterSave() {
parent::afterSave();
/**
* Сохраняем варианты
*/
if ($aAnswers=$this->getAnswersObject()) {
foreach($aAnswers as $oAnswer) {
$oAnswer->setPollId($this->getId());
$oAnswer->Save();
}
}
/**
* Удаляем варианты
*/
if ($aAnswers=$this->getAnswersObjectForRemove()) {
foreach($aAnswers as $oAnswer) {
$oAnswer->Delete();
}
}
}
protected function afterSave()
{
parent::afterSave();
/**
* Сохраняем варианты
*/
if ($aAnswers = $this->getAnswersObject()) {
foreach ($aAnswers as $oAnswer) {
$oAnswer->setPollId($this->getId());
$oAnswer->Save();
}
}
/**
* Удаляем варианты
*/
if ($aAnswers = $this->getAnswersObjectForRemove()) {
foreach ($aAnswers as $oAnswer) {
$oAnswer->Delete();
}
}
}
protected function afterDelete() {
parent::afterDelete();
/**
* Удаляем варианты ответов
*/
$aAnswerItems=$this->Poll_GetAnswerItemsByPollId($this->getId());
foreach($aAnswerItems as $oAnswer) {
$oAnswer->Delete();
}
/**
* Удаляем голосования
*/
$aVoteItems=$this->Poll_GetVoteItemsByPollId($this->getId());
foreach($aVoteItems as $oVote) {
$oVote->Delete();
}
}
protected function afterDelete()
{
parent::afterDelete();
/**
* Удаляем варианты ответов
*/
$aAnswerItems = $this->Poll_GetAnswerItemsByPollId($this->getId());
foreach ($aAnswerItems as $oAnswer) {
$oAnswer->Delete();
}
/**
* Удаляем голосования
*/
$aVoteItems = $this->Poll_GetVoteItemsByPollId($this->getId());
foreach ($aVoteItems as $oVote) {
$oVote->Delete();
}
}
public function ValidateCheckTitle() {
$this->setTitle(htmlspecialchars($this->getTitle()));
return true;
}
public function ValidateCheckTitle()
{
$this->setTitle(htmlspecialchars($this->getTitle()));
return true;
}
public function ValidateCheckType() {
if (!$this->_isNew() and $this->getCountVote()) {
/**
* Запрещаем смену типа
*/
$this->setCountAnswerMax($this->_getOriginalDataOne('count_answer_max'));
return true;
}
$iCount=$this->getCountAnswerMax();
if ($this->getType()=='one') {
$this->setCountAnswerMax(1);
return true;
} else {
if ($iCount<2) {
return 'Максимальное количество вариантов ответа должно быть больше одного';
}
}
return true;
}
public function ValidateCheckType()
{
if (!$this->_isNew() and $this->getCountVote()) {
/**
* Запрещаем смену типа
*/
$this->setCountAnswerMax($this->_getOriginalDataOne('count_answer_max'));
return true;
}
$iCount = $this->getCountAnswerMax();
if ($this->getType() == 'one') {
$this->setCountAnswerMax(1);
return true;
} else {
if ($iCount < 2) {
return 'Максимальное количество вариантов ответа должно быть больше одного';
}
}
return true;
}
public function ValidateCheckAnswersRaw() {
if (!$this->_isNew() and !$this->isAllowUpdate()) {
return true;
}
public function ValidateCheckAnswersRaw()
{
if (!$this->_isNew() and !$this->isAllowUpdate()) {
return true;
}
$aAnswersRaw=$this->getAnswersRaw();
if (!is_array($aAnswersRaw)) {
return 'Необходимо заполнить варианты ответов';
}
if (count($aAnswersRaw)<2) {
return 'Необходимо заполнить больше одного варианта ответов';
}
/**
* Здесь может быть два варианта - создание опроса или редактирование, при редактирование могут передаваться ID ответов
*/
if (!$this->_isNew()) {
$aAnswersOld=$this->Poll_GetAnswerItemsByFilter(array('poll_id'=>$this->getId(),'#index-from-primary'));
} else {
$aAnswersOld=array();
}
$aAnswers=array();
foreach($aAnswersRaw as $aAnswer) {
if ($this->_isNew() or !(isset($aAnswer['id']) and isset($aAnswersOld[$aAnswer['id']]) and $oAnswer=$aAnswersOld[$aAnswer['id']])) {
$oAnswer=Engine::GetEntity('ModulePoll_EntityAnswer');
}
if ($oAnswer->getId()) {
/**
* Фильтруем список старых ответов для будущего удаления оставшихся
*/
unset($aAnswersOld[$oAnswer->getId()]);
}
$oAnswer->setTitle(isset($aAnswer['title']) ? $aAnswer['title'] : '');
if (!$oAnswer->_Validate()) {
return $oAnswer->_getValidateError();
}
$aAnswers[]=$oAnswer;
}
$this->setAnswersObject($aAnswers);
$aAnswersRaw = $this->getAnswersRaw();
if (!is_array($aAnswersRaw)) {
return 'Необходимо заполнить варианты ответов';
}
if (count($aAnswersRaw) < 2) {
return 'Необходимо заполнить больше одного варианта ответов';
}
/**
* Здесь может быть два варианта - создание опроса или редактирование, при редактирование могут передаваться ID ответов
*/
if (!$this->_isNew()) {
$aAnswersOld = $this->Poll_GetAnswerItemsByFilter(array(
'poll_id' => $this->getId(),
'#index-from-primary'
));
} else {
$aAnswersOld = array();
}
$aAnswers = array();
foreach ($aAnswersRaw as $aAnswer) {
if ($this->_isNew() or !(isset($aAnswer['id']) and isset($aAnswersOld[$aAnswer['id']]) and $oAnswer = $aAnswersOld[$aAnswer['id']])) {
$oAnswer = Engine::GetEntity('ModulePoll_EntityAnswer');
}
if ($oAnswer->getId()) {
/**
* Фильтруем список старых ответов для будущего удаления оставшихся
*/
unset($aAnswersOld[$oAnswer->getId()]);
}
$oAnswer->setTitle(isset($aAnswer['title']) ? $aAnswer['title'] : '');
if (!$oAnswer->_Validate()) {
return $oAnswer->_getValidateError();
}
$aAnswers[] = $oAnswer;
}
$this->setAnswersObject($aAnswers);
foreach($aAnswersOld as $oAnswer) {
if ($oAnswer->getCountVote()) {
return 'Нельзя удалить вариант ответа, за который уже голосовали';
}
}
foreach ($aAnswersOld as $oAnswer) {
if ($oAnswer->getCountVote()) {
return 'Нельзя удалить вариант ответа, за который уже голосовали';
}
}
$this->setAnswersObjectForRemove($aAnswersOld);
return true;
}
$this->setAnswersObjectForRemove($aAnswersOld);
return true;
}
public function ValidateCheckTargetRaw() {
$aTarget=$this->getTargetRaw();
public function ValidateCheckTargetRaw()
{
$aTarget = $this->getTargetRaw();
$sTargetType=isset($aTarget['type']) ? $aTarget['type'] : '';
$sTargetId=isset($aTarget['id']) ? $aTarget['id'] : '';
$sTargetTmp=isset($aTarget['tmp']) ? $aTarget['tmp'] : '';
$sTargetType = isset($aTarget['type']) ? $aTarget['type'] : '';
$sTargetId = isset($aTarget['id']) ? $aTarget['id'] : '';
$sTargetTmp = isset($aTarget['tmp']) ? $aTarget['tmp'] : '';
if ($sTargetId) {
$sTargetTmp=null;
if (!$this->Poll_CheckTarget($sTargetType,$sTargetId)) {
return 'Неверный тип объекта';
}
} else {
$sTargetId=null;
if (!$sTargetTmp or !$this->Poll_IsAllowTargetType($sTargetType)) {
return 'Неверный тип объекта';
}
if ($this->Poll_GetPollByFilter(array('target_tmp'=>$sTargetTmp,'target_type <>'=>$sTargetType))) {
return 'Временный идентификатор уже занят';
}
}
if ($sTargetId) {
$sTargetTmp = null;
if (!$this->Poll_CheckTarget($sTargetType, $sTargetId)) {
return 'Неверный тип объекта';
}
} else {
$sTargetId = null;
if (!$sTargetTmp or !$this->Poll_IsAllowTargetType($sTargetType)) {
return 'Неверный тип объекта';
}
if ($this->Poll_GetPollByFilter(array('target_tmp' => $sTargetTmp, 'target_type <>' => $sTargetType))) {
return 'Временный идентификатор уже занят';
}
}
$this->setTargetType($sTargetType);
$this->setTargetId($sTargetId);
$this->setTargetTmp($sTargetTmp);
return true;
}
$this->setTargetType($sTargetType);
$this->setTargetId($sTargetId);
$this->setTargetTmp($sTargetTmp);
return true;
}
/**
* Проверяет доступность опроса для изменения
* Важно понимать, что здесь нет проверки на права доступа
*
* @return bool
*/
public function isAllowUpdate() {
$iTime=$this->getDateCreate();
if ((time()-strtotime($iTime))>Config::Get('module.poll.time_limit_update')) {
return false;
}
return true;
}
/**
* Проверяет доступность опроса для изменения
* Важно понимать, что здесь нет проверки на права доступа
*
* @return bool
*/
public function isAllowUpdate()
{
$iTime = $this->getDateCreate();
if ((time() - strtotime($iTime)) > Config::Get('module.poll.time_limit_update')) {
return false;
}
return true;
}
/**
* Проверяет возможность удаления опроса, не пользователем, а в принципе
* Важно понимать, что здесь нет проверки на права доступа
*
* @return bool
*/
public function isAllowRemove() {
if ($this->getCountVote() || $this->getCountAbstain()) {
return false;
}
return true;
}
/**
* Проверяет возможность удаления опроса, не пользователем, а в принципе
* Важно понимать, что здесь нет проверки на права доступа
*
* @return bool
*/
public function isAllowRemove()
{
if ($this->getCountVote() || $this->getCountAbstain()) {
return false;
}
return true;
}
/**
* Проверяет возможность голосования в опросе, не пользователем, а в принципе
* Важно понимать, что здесь нет проверки на права доступа
*
* @return bool
*/
public function isAllowVote() {
$sDateEnd=$this->getDateEnd();
if ($sDateEnd and (time()-strtotime($sDateEnd))>0) {
return false;
}
return true;
}
/**
* Проверяет возможность голосования в опросе, не пользователем, а в принципе
* Важно понимать, что здесь нет проверки на права доступа
*
* @return bool
*/
public function isAllowVote()
{
$sDateEnd = $this->getDateEnd();
if ($sDateEnd and (time() - strtotime($sDateEnd)) > 0) {
return false;
}
return true;
}
public function getAnswerPercent($oAnswer) {
$iCountAll=$this->getCountVote();
if ($iCountAll==0) {
return 0;
} else {
return number_format(round($oAnswer->getCountVote()*100/$iCountAll,1), 1, '.', '');
}
}
public function getAnswerPercent($oAnswer)
{
$iCountAll = $this->getCountVote();
if ($iCountAll == 0) {
return 0;
} else {
return number_format(round($oAnswer->getCountVote() * 100 / $iCountAll, 1), 1, '.', '');
}
}
public function getCountVoteAnswerMax() {
$iMax=0;
$aAnswers=$this->getAnswers();
foreach($aAnswers as $oAnswer) {
if ($oAnswer->getCountVote()>$iMax) {
$iMax=$oAnswer->getCountVote();
}
}
return $iMax;
}
public function getCountVoteAnswerMax()
{
$iMax = 0;
$aAnswers = $this->getAnswers();
foreach ($aAnswers as $oAnswer) {
if ($oAnswer->getCountVote() > $iMax) {
$iMax = $oAnswer->getCountVote();
}
}
return $iMax;
}
}

View file

@ -25,64 +25,68 @@
* @package application.modules.poll
* @since 2.0
*/
class ModulePoll_EntityVote extends EntityORM {
class ModulePoll_EntityVote extends EntityORM
{
protected $aValidateRules=array(
protected $aValidateRules = array();
);
protected $aRelations = array(
'poll' => array(self::RELATION_TYPE_BELONGS_TO, 'ModulePoll_EntityPoll', 'poll_id'),
);
protected $aRelations=array(
'poll' => array(self::RELATION_TYPE_BELONGS_TO,'ModulePoll_EntityPoll','poll_id'),
);
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
protected function afterSave()
{
parent::afterSave();
if ($this->_isNew()) {
/**
* Отмечаем факт голосования в опросе и вариантах
*/
$oPoll = $this->getPoll();
$aAnswerItems = $this->getAnswersObject();
if ($aAnswerItems) {
foreach ($aAnswerItems as $oAnswer) {
$oAnswer->setCountVote($oAnswer->getCountVote() + 1);
$oAnswer->Update();
}
$oPoll->setCountVote($oPoll->getCountVote() + 1);
} else {
$oPoll->setCountAbstain($oPoll->getCountAbstain() + 1);
}
$oPoll->Update(0);
}
}
protected function afterSave() {
parent::afterSave();
if ($this->_isNew()) {
/**
* Отмечаем факт голосования в опросе и вариантах
*/
$oPoll=$this->getPoll();
$aAnswerItems=$this->getAnswersObject();
if ($aAnswerItems) {
foreach($aAnswerItems as $oAnswer) {
$oAnswer->setCountVote($oAnswer->getCountVote()+1);
$oAnswer->Update();
}
$oPoll->setCountVote($oPoll->getCountVote()+1);
} else {
$oPoll->setCountAbstain($oPoll->getCountAbstain()+1);
}
$oPoll->Update(0);
}
}
/**
* Возвращает список вариантов, за которые голосовали
*
* @return array|mixed
*/
public function getAnswers()
{
$aData = @unserialize($this->_getDataOne('answers'));
if (!$aData) {
$aData = array();
}
return $aData;
}
/**
* Возвращает список вариантов, за которые голосовали
*
* @return array|mixed
*/
public function getAnswers() {
$aData=@unserialize($this->_getDataOne('answers'));
if (!$aData) {
$aData=array();
}
return $aData;
}
/**
* Устанавливает список вариантов, за которые голосовали
*
* @param $aParams
*/
public function setAnswers($aParams) {
$this->_aData['answers']=@serialize($aParams);
}
/**
* Устанавливает список вариантов, за которые голосовали
*
* @param $aParams
*/
public function setAnswers($aParams)
{
$this->_aData['answers'] = @serialize($aParams);
}
}

File diff suppressed because it is too large Load diff

View file

@ -25,109 +25,125 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_BehaviorEntity extends Behavior {
/**
* Дефолтные параметры
*
* @var array
*/
protected $aParams=array(
'target_type'=>'',
);
/**
* Список хуков
*
* @var array
*/
protected $aHooks=array(
'validate_after'=>'CallbackValidateAfter',
'after_save'=>'CallbackAfterSave',
'after_delete'=>'CallbackAfterDelete',
);
class ModuleProperty_BehaviorEntity extends Behavior
{
/**
* Дефолтные параметры
*
* @var array
*/
protected $aParams = array(
'target_type' => '',
);
/**
* Список хуков
*
* @var array
*/
protected $aHooks = array(
'validate_after' => 'CallbackValidateAfter',
'after_save' => 'CallbackAfterSave',
'after_delete' => 'CallbackAfterDelete',
);
/**
* Коллбэк
* Выполняется при инициализации сущности
*
* @param $aParams
*/
public function CallbackValidateAfter($aParams) {
if ($aParams['bResult']) {
$aFields=$aParams['aFields'];
if (is_null($aFields) or in_array('properties',$aFields)) {
$oValidator=$this->Validate_CreateValidator('properties_check',$this,'properties');
$oValidator->validateEntity($this->oObject,$aFields);
$aParams['bResult']=!$this->oObject->_hasValidateErrors();
}
}
}
/**
* Коллбэк
* Выполняется после сохранения сущности
*/
public function CallbackAfterSave() {
$this->Property_UpdatePropertiesValue($this->oObject->getPropertiesObject(),$this->oObject);
}
/**
* Коллбэк
* Выполняется после удаления сущности
*/
public function CallbackAfterDelete() {
$this->Property_RemovePropertiesValue($this->oObject);
}
/**
* Дополнительный метод для сущности
* Запускает валидацию дополнительных полей
*
* @return mixed
*/
public function ValidatePropertiesCheck() {
return $this->Property_ValidateEntityPropertiesCheck($this->oObject);
}
/**
* Возвращает полный список свойств сущности
*
* @return mixed
*/
public function getPropertyList() {
return $this->Property_GetEntityPropertyList($this->oObject);
}
/**
* Возвращает значение конкретного свойства
* @see ModuleProperty_EntityValue::getValueForDisplay
*
* @param int|string $sPropertyId ID или код свойства
*
* @return mixed
*/
public function getPropertyValue($sPropertyId) {
return $this->Property_GetEntityPropertyValue($this->oObject,$sPropertyId);
}
/**
* Возвращает объект конкретного свойства сущности
*
* @param int|string $sPropertyId ID или код свойства
*
* @return ModuleProperty_EntityProperty|null
*/
public function getProperty($sPropertyId) {
return $this->Property_GetEntityProperty($this->oObject,$sPropertyId);
}
/**
* Возвращает тип объекта для дополнительных полей
*
* @return string
*/
public function getPropertyTargetType() {
if ($sType=$this->getParam('target_type')) {
return $sType;
}
/**
* Иначе дополнительно смотрим на наличие данного метода у сущности
* Это необходимо, если тип вычисляется динамически по какой-то своей логике
*/
if (func_method_exists($this->oObject,'getPropertyTargetType','public')) {
return call_user_func(array($this->oObject,'getPropertyTargetType'));
}
}
/**
* Коллбэк
* Выполняется при инициализации сущности
*
* @param $aParams
*/
public function CallbackValidateAfter($aParams)
{
if ($aParams['bResult']) {
$aFields = $aParams['aFields'];
if (is_null($aFields) or in_array('properties', $aFields)) {
$oValidator = $this->Validate_CreateValidator('properties_check', $this, 'properties');
$oValidator->validateEntity($this->oObject, $aFields);
$aParams['bResult'] = !$this->oObject->_hasValidateErrors();
}
}
}
/**
* Коллбэк
* Выполняется после сохранения сущности
*/
public function CallbackAfterSave()
{
$this->Property_UpdatePropertiesValue($this->oObject->getPropertiesObject(), $this->oObject);
}
/**
* Коллбэк
* Выполняется после удаления сущности
*/
public function CallbackAfterDelete()
{
$this->Property_RemovePropertiesValue($this->oObject);
}
/**
* Дополнительный метод для сущности
* Запускает валидацию дополнительных полей
*
* @return mixed
*/
public function ValidatePropertiesCheck()
{
return $this->Property_ValidateEntityPropertiesCheck($this->oObject);
}
/**
* Возвращает полный список свойств сущности
*
* @return mixed
*/
public function getPropertyList()
{
return $this->Property_GetEntityPropertyList($this->oObject);
}
/**
* Возвращает значение конкретного свойства
* @see ModuleProperty_EntityValue::getValueForDisplay
*
* @param int|string $sPropertyId ID или код свойства
*
* @return mixed
*/
public function getPropertyValue($sPropertyId)
{
return $this->Property_GetEntityPropertyValue($this->oObject, $sPropertyId);
}
/**
* Возвращает объект конкретного свойства сущности
*
* @param int|string $sPropertyId ID или код свойства
*
* @return ModuleProperty_EntityProperty|null
*/
public function getProperty($sPropertyId)
{
return $this->Property_GetEntityProperty($this->oObject, $sPropertyId);
}
/**
* Возвращает тип объекта для дополнительных полей
*
* @return string
*/
public function getPropertyTargetType()
{
if ($sType = $this->getParam('target_type')) {
return $sType;
}
/**
* Иначе дополнительно смотрим на наличие данного метода у сущности
* Это необходимо, если тип вычисляется динамически по какой-то своей логике
*/
if (func_method_exists($this->oObject, 'getPropertyTargetType', 'public')) {
return call_user_func(array($this->oObject, 'getPropertyTargetType'));
}
}
}

View file

@ -25,41 +25,48 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_BehaviorModule extends Behavior {
/**
* Список хуков
*
* @var array
*/
protected $aHooks=array(
'module_orm_GetItemsByFilter_after'=>array(
'CallbackGetItemsByFilterAfter',1000
),
'module_orm_GetItemsByFilter_before'=>array(
'CallbackGetItemsByFilterBefore',1000
),
'module_orm_GetByFilter_before'=>array(
'CallbackGetItemsByFilterBefore',1000
),
);
class ModuleProperty_BehaviorModule extends Behavior
{
/**
* Список хуков
*
* @var array
*/
protected $aHooks = array(
'module_orm_GetItemsByFilter_after' => array(
'CallbackGetItemsByFilterAfter',
1000
),
'module_orm_GetItemsByFilter_before' => array(
'CallbackGetItemsByFilterBefore',
1000
),
'module_orm_GetByFilter_before' => array(
'CallbackGetItemsByFilterBefore',
1000
),
);
/**
* Модифицирует фильтр в ORM запросе
*
* @param $aParams
*/
public function CallbackGetItemsByFilterAfter($aParams) {
$aEntities=$aParams['aEntities'];
$aFilter=$aParams['aFilter'];
$this->Property_RewriteGetItemsByFilter($aEntities,$aFilter);
}
/**
* Модифицирует результат ORM запроса
*
* @param $aParams
*/
public function CallbackGetItemsByFilterBefore($aParams) {
$aFilter=$this->Property_RewriteFilter($aParams['aFilter'],$aParams['sEntityFull']);
$aParams['aFilter']=$aFilter;
}
/**
* Модифицирует фильтр в ORM запросе
*
* @param $aParams
*/
public function CallbackGetItemsByFilterAfter($aParams)
{
$aEntities = $aParams['aEntities'];
$aFilter = $aParams['aFilter'];
$this->Property_RewriteGetItemsByFilter($aEntities, $aFilter);
}
/**
* Модифицирует результат ORM запроса
*
* @param $aParams
*/
public function CallbackGetItemsByFilterBefore($aParams)
{
$aFilter = $this->Property_RewriteFilter($aParams['aFilter'], $aParams['sEntityFull']);
$aParams['aFilter'] = $aFilter;
}
}

View file

@ -25,241 +25,307 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityProperty extends EntityORM {
class ModuleProperty_EntityProperty extends EntityORM
{
protected $aValidateRules=array(
array('type','check_type','on'=>array('create','auto')),
array('code','regexp','allowEmpty'=>false,'pattern'=>'#^[a-z0-9\_]+$#i','on'=>array('create','update','auto')),
array('title','string','allowEmpty'=>false,'min'=>1,'max'=>250,'on'=>array('create','update','auto')),
array('description','string','allowEmpty'=>true,'max'=>500,'on'=>array('update','auto')),
array('sort','number','allowEmpty'=>false,'integerOnly'=>true,'min'=>0,'on'=>array('auto')),
array('validate_rules_raw','check_validate_rules_raw','on'=>array('create','update','auto')),
array('params_raw','check_params_raw','on'=>array('update','auto')),
array('code','check_code','on'=>array('create','update','auto')),
array('title','check_title','on'=>array('create','update','auto')),
array('description','check_description','on'=>array('update','auto')),
);
protected $aValidateRules = array(
array('type', 'check_type', 'on' => array('create', 'auto')),
array(
'code',
'regexp',
'allowEmpty' => false,
'pattern' => '#^[a-z0-9\_]+$#i',
'on' => array('create', 'update', 'auto')
),
array(
'title',
'string',
'allowEmpty' => false,
'min' => 1,
'max' => 250,
'on' => array('create', 'update', 'auto')
),
array('description', 'string', 'allowEmpty' => true, 'max' => 500, 'on' => array('update', 'auto')),
array('sort', 'number', 'allowEmpty' => false, 'integerOnly' => true, 'min' => 0, 'on' => array('auto')),
array('validate_rules_raw', 'check_validate_rules_raw', 'on' => array('create', 'update', 'auto')),
array('params_raw', 'check_params_raw', 'on' => array('update', 'auto')),
array('code', 'check_code', 'on' => array('create', 'update', 'auto')),
array('title', 'check_title', 'on' => array('create', 'update', 'auto')),
array('description', 'check_description', 'on' => array('update', 'auto')),
);
protected $aRelations=array(
'selects' => array(self::RELATION_TYPE_HAS_MANY,'ModuleProperty_EntitySelect','property_id',array('#order'=>array('sort'=>'desc'))),
);
protected $aRelations = array(
'selects' => array(
self::RELATION_TYPE_HAS_MANY,
'ModuleProperty_EntitySelect',
'property_id',
array('#order' => array('sort' => 'desc'))
),
);
public function ValidateCheckType() {
if ($this->Property_IsAllowPropertyType($this->getType())) {
return true;
}
return 'Неверный тип поля';
}
public function ValidateCheckType()
{
if ($this->Property_IsAllowPropertyType($this->getType())) {
return true;
}
return 'Неверный тип поля';
}
public function ValidateCheckCode() {
if ($oProperty=$this->Property_GetPropertyByTargetTypeAndCode($this->getTargetType(),$this->getCode())) {
if ($this->getId()!=$oProperty->getId()) {
return 'Код поля должен быть уникальным';
}
}
return true;
}
public function ValidateCheckCode()
{
if ($oProperty = $this->Property_GetPropertyByTargetTypeAndCode($this->getTargetType(), $this->getCode())) {
if ($this->getId() != $oProperty->getId()) {
return 'Код поля должен быть уникальным';
}
}
return true;
}
public function ValidateCheckTitle() {
$this->setTitle(htmlspecialchars($this->getTitle()));
return true;
}
public function ValidateCheckTitle()
{
$this->setTitle(htmlspecialchars($this->getTitle()));
return true;
}
public function ValidateCheckDescription() {
$this->setDescription(htmlspecialchars($this->getDescription()));
return true;
}
public function ValidateCheckDescription()
{
$this->setDescription(htmlspecialchars($this->getDescription()));
return true;
}
public function ValidateCheckValidateRulesRaw() {
$aRulesRaw=$this->getValidateRulesRaw();
/**
* Валидация зависит от типа
*/
$oValue=Engine::GetEntity('ModuleProperty_EntityValue',array('property_type'=>$this->getType(),'property_id'=>$this->getId(),'target_type'=>$this->getTargetType(),'target_id'=>$this->getId()));
$oValueType=$oValue->getValueTypeObject();
$aRules=$oValueType->prepareValidateRulesRaw($aRulesRaw);
$this->setValidateRules($aRules);
return true;
}
public function ValidateCheckValidateRulesRaw()
{
$aRulesRaw = $this->getValidateRulesRaw();
/**
* Валидация зависит от типа
*/
$oValue = Engine::GetEntity('ModuleProperty_EntityValue', array(
'property_type' => $this->getType(),
'property_id' => $this->getId(),
'target_type' => $this->getTargetType(),
'target_id' => $this->getId()
));
$oValueType = $oValue->getValueTypeObject();
$aRules = $oValueType->prepareValidateRulesRaw($aRulesRaw);
$this->setValidateRules($aRules);
return true;
}
public function ValidateCheckParamsRaw() {
$aParamsRaw=$this->getParamsRaw();
/**
* Валидация зависит от типа
*/
$oValue=Engine::GetEntity('ModuleProperty_EntityValue',array('property_type'=>$this->getType(),'property_id'=>$this->getId(),'target_type'=>$this->getTargetType(),'target_id'=>$this->getId()));
$oValueType=$oValue->getValueTypeObject();
$aParams=$oValueType->prepareParamsRaw($aParamsRaw);
$this->setParams($aParams);
return true;
}
public function ValidateCheckParamsRaw()
{
$aParamsRaw = $this->getParamsRaw();
/**
* Валидация зависит от типа
*/
$oValue = Engine::GetEntity('ModuleProperty_EntityValue', array(
'property_type' => $this->getType(),
'property_id' => $this->getId(),
'target_type' => $this->getTargetType(),
'target_id' => $this->getId()
));
$oValueType = $oValue->getValueTypeObject();
$aParams = $oValueType->prepareParamsRaw($aParamsRaw);
$this->setParams($aParams);
return true;
}
/**
* Выполняется перед сохранением сущности
*
* @return bool
*/
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
/**
* Выполняется перед сохранением сущности
*
* @return bool
*/
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
$oValue=Engine::GetEntity('ModuleProperty_EntityValue',array('property_type'=>$this->getType(),'property_id'=>$this->getId(),'target_type'=>$this->getTargetType(),'target_id'=>$this->getId()));
$oValueType=$oValue->getValueTypeObject();
/**
* Выставляем дефолтные значения параметров
*/
$this->setParams($oValueType->getParamsDefault());
/**
* Выставляем дефолтные значения параметров валидации
*/
$this->setValidateRules($oValueType->getValidateRulesDefault());
}
}
return $bResult;
}
/**
* Выполняется перед удалением сущности
*
* @return bool
*/
protected function beforeDelete() {
if ($bResult=parent::beforeDelete()) {
/**
* Сначала удаляем стандартные значения
*/
$this->Property_RemoveValueByPropertyId($this->getId());
/**
* Удаляем значения тегов
*/
$this->Property_RemoveValueTagByPropertyId($this->getId());
/**
* Удаляем значения селектов
*/
$this->Property_RemoveValueSelectByPropertyId($this->getId());
/**
* Удаляем сами варианты селектов
*/
$this->Property_RemoveSelectByPropertyId($this->getId());
}
return $bResult;
}
/**
* Возвращает правила валидации поля
*
* @return array
*/
public function getValidateRules() {
$aData=@unserialize($this->_getDataOne('validate_rules'));
if (!$aData) {
$aData=array();
}
return $aData;
}
/**
* Возвращает экранированный список правил валидации
*
* @return array
*/
public function getValidateRulesEscape() {
$aRules=$this->getValidateRules();
func_htmlspecialchars($aRules);
return $aRules;
}
/**
* Возвращает конкретное правило валидации
*
* @param string $sRule
*
* @return null|mixed
*/
public function getValidateRuleOne($sRule) {
$aData=$this->getValidateRules();
if (isset($aData[$sRule])) {
return $aData[$sRule];
}
return null;
}
/**
* Устанавливает правила валидации поля
*
* @param array $aRules
*/
public function setValidateRules($aRules) {
$this->_aData['validate_rules']=@serialize($aRules);
}
/**
* Возвращает список дополнительных параметров поля
*
* @return array|mixed
*/
public function getParams() {
$aData=@unserialize($this->_getDataOne('params'));
if (!$aData) {
$aData=array();
}
return $aData;
}
/**
* Возвращает экранированный список параметров
*
* @return array
*/
public function getParamsEscape() {
$aParams=$this->getParams();
func_htmlspecialchars($aParams);
return $aParams;
}
/**
* Устанавливает список дополнительных параметров поля
*
* @param $aParams
*/
public function setParams($aParams) {
$this->_aData['params']=@serialize($aParams);
}
/**
* Возвращает конкретный параметр поля
*
* @param $sName
*
* @return null
*/
public function getParam($sName) {
$aParams=$this->getParams();
return isset($aParams[$sName]) ? $aParams[$sName] : null;
}
/**
* Возвращает URL админки для редактирования поля
*
* @return string
*/
public function getUrlAdminUpdate() {
return Router::GetPath('admin/properties/'.$this->getTargetType().'/update/'.$this->getId());
}
/**
* Возвращает URL админки для редактирования поля
*
* @return string
*/
public function getUrlAdminRemove() {
return Router::GetPath('admin/properties/'.$this->getTargetType().'/remove/'.$this->getId());
}
/**
* Возвращает описание типа поля
*
* @return mixed
*/
public function getTypeTitle() {
/**
* TODO: использовать текстовку из языкового
*/
return $this->getType();
}
$oValue = Engine::GetEntity('ModuleProperty_EntityValue', array(
'property_type' => $this->getType(),
'property_id' => $this->getId(),
'target_type' => $this->getTargetType(),
'target_id' => $this->getId()
));
$oValueType = $oValue->getValueTypeObject();
/**
* Выставляем дефолтные значения параметров
*/
$this->setParams($oValueType->getParamsDefault());
/**
* Выставляем дефолтные значения параметров валидации
*/
$this->setValidateRules($oValueType->getValidateRulesDefault());
}
}
return $bResult;
}
public function getSaveFileDir($sPostfix='') {
$sPostfix=trim($sPostfix,'/');
return Config::Get('path.uploads.base').'/property/'.$this->getTargetType().'/'.$this->getType().'/'.date('Y/m/d/H/').($sPostfix ? "{$sPostfix}/" : '');
}
/**
* Выполняется перед удалением сущности
*
* @return bool
*/
protected function beforeDelete()
{
if ($bResult = parent::beforeDelete()) {
/**
* Сначала удаляем стандартные значения
*/
$this->Property_RemoveValueByPropertyId($this->getId());
/**
* Удаляем значения тегов
*/
$this->Property_RemoveValueTagByPropertyId($this->getId());
/**
* Удаляем значения селектов
*/
$this->Property_RemoveValueSelectByPropertyId($this->getId());
/**
* Удаляем сами варианты селектов
*/
$this->Property_RemoveSelectByPropertyId($this->getId());
}
return $bResult;
}
/**
* Возвращает правила валидации поля
*
* @return array
*/
public function getValidateRules()
{
$aData = @unserialize($this->_getDataOne('validate_rules'));
if (!$aData) {
$aData = array();
}
return $aData;
}
/**
* Возвращает экранированный список правил валидации
*
* @return array
*/
public function getValidateRulesEscape()
{
$aRules = $this->getValidateRules();
func_htmlspecialchars($aRules);
return $aRules;
}
/**
* Возвращает конкретное правило валидации
*
* @param string $sRule
*
* @return null|mixed
*/
public function getValidateRuleOne($sRule)
{
$aData = $this->getValidateRules();
if (isset($aData[$sRule])) {
return $aData[$sRule];
}
return null;
}
/**
* Устанавливает правила валидации поля
*
* @param array $aRules
*/
public function setValidateRules($aRules)
{
$this->_aData['validate_rules'] = @serialize($aRules);
}
/**
* Возвращает список дополнительных параметров поля
*
* @return array|mixed
*/
public function getParams()
{
$aData = @unserialize($this->_getDataOne('params'));
if (!$aData) {
$aData = array();
}
return $aData;
}
/**
* Возвращает экранированный список параметров
*
* @return array
*/
public function getParamsEscape()
{
$aParams = $this->getParams();
func_htmlspecialchars($aParams);
return $aParams;
}
/**
* Устанавливает список дополнительных параметров поля
*
* @param $aParams
*/
public function setParams($aParams)
{
$this->_aData['params'] = @serialize($aParams);
}
/**
* Возвращает конкретный параметр поля
*
* @param $sName
*
* @return null
*/
public function getParam($sName)
{
$aParams = $this->getParams();
return isset($aParams[$sName]) ? $aParams[$sName] : null;
}
/**
* Возвращает URL админки для редактирования поля
*
* @return string
*/
public function getUrlAdminUpdate()
{
return Router::GetPath('admin/properties/' . $this->getTargetType() . '/update/' . $this->getId());
}
/**
* Возвращает URL админки для редактирования поля
*
* @return string
*/
public function getUrlAdminRemove()
{
return Router::GetPath('admin/properties/' . $this->getTargetType() . '/remove/' . $this->getId());
}
/**
* Возвращает описание типа поля
*
* @return mixed
*/
public function getTypeTitle()
{
/**
* TODO: использовать текстовку из языкового
*/
return $this->getType();
}
public function getSaveFileDir($sPostfix = '')
{
$sPostfix = trim($sPostfix, '/');
return Config::Get('path.uploads.base') . '/property/' . $this->getTargetType() . '/' . $this->getType() . '/' . date('Y/m/d/H/') . ($sPostfix ? "{$sPostfix}/" : '');
}
}

View file

@ -25,14 +25,11 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntitySelect extends EntityORM {
class ModuleProperty_EntitySelect extends EntityORM
{
protected $aValidateRules=array(
protected $aValidateRules = array();
);
protected $aRelations=array(
);
protected $aRelations = array();
}

View file

@ -25,56 +25,59 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityTarget extends EntityORM {
class ModuleProperty_EntityTarget extends EntityORM
{
protected $aValidateRules=array(
protected $aValidateRules = array();
);
protected $aRelations = array();
protected $aRelations=array(
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
} else {
$this->setDateUpdate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
);
/**
* Возвращает список дополнительных параметров
*
* @return array|mixed
*/
public function getParams()
{
$aData = @unserialize($this->_getDataOne('params'));
if (!$aData) {
$aData = array();
}
return $aData;
}
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
if ($this->_isNew()) {
$this->setDateCreate(date("Y-m-d H:i:s"));
} else {
$this->setDateUpdate(date("Y-m-d H:i:s"));
}
}
return $bResult;
}
/**
* Устанавливает список дополнительных параметров
*
* @param $aParams
*/
public function setParams($aParams)
{
$this->_aData['params'] = @serialize($aParams);
}
/**
* Возвращает список дополнительных параметров
*
* @return array|mixed
*/
public function getParams() {
$aData=@unserialize($this->_getDataOne('params'));
if (!$aData) {
$aData=array();
}
return $aData;
}
/**
* Устанавливает список дополнительных параметров
*
* @param $aParams
*/
public function setParams($aParams) {
$this->_aData['params']=@serialize($aParams);
}
/**
* Возвращает конкретный параметр
*
* @param $sName
*
* @return null
*/
public function getParam($sName) {
$aParams=$this->getParams();
return isset($aParams[$sName]) ? $aParams[$sName] : null;
}
/**
* Возвращает конкретный параметр
*
* @param $sName
*
* @return null
*/
public function getParam($sName)
{
$aParams = $this->getParams();
return isset($aParams[$sName]) ? $aParams[$sName] : null;
}
}

View file

@ -25,62 +25,71 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValue extends EntityORM {
class ModuleProperty_EntityValue extends EntityORM
{
protected $aRelations=array(
'property' => array(self::RELATION_TYPE_BELONGS_TO,'ModuleProperty_EntityProperty','property_id'),
);
protected $aRelations = array(
'property' => array(self::RELATION_TYPE_BELONGS_TO, 'ModuleProperty_EntityProperty', 'property_id'),
);
protected function beforeSave() {
if ($bResult=parent::beforeSave()) {
$oValueType=$this->getValueTypeObject();
$oValueType->beforeSaveValue();
}
return $bResult;
}
protected function beforeSave()
{
if ($bResult = parent::beforeSave()) {
$oValueType = $this->getValueTypeObject();
$oValueType->beforeSaveValue();
}
return $bResult;
}
public function getValueForDisplay() {
$oValueType=$this->getValueTypeObject();
return $oValueType->getValueForDisplay();
}
public function getValueForDisplay()
{
$oValueType = $this->getValueTypeObject();
return $oValueType->getValueForDisplay();
}
public function getValueForForm() {
$oValueType=$this->getValueTypeObject();
return $oValueType->getValueForForm();
}
public function getValueForForm()
{
$oValueType = $this->getValueTypeObject();
return $oValueType->getValueForForm();
}
public function getValueTypeObject() {
if (!$this->_getDataOne('value_type_object')) {
$oObject=Engine::GetEntity('ModuleProperty_EntityValueType'.func_camelize($this->getPropertyType()));
$oObject->setValueObject($this);
$this->setValueTypeObject($oObject);
}
return $this->_getDataOne('value_type_object');
}
public function getValueTypeObject()
{
if (!$this->_getDataOne('value_type_object')) {
$oObject = Engine::GetEntity('ModuleProperty_EntityValueType' . func_camelize($this->getPropertyType()));
$oObject->setValueObject($this);
$this->setValueTypeObject($oObject);
}
return $this->_getDataOne('value_type_object');
}
public function getData() {
$aData=@unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData=array();
}
return $aData;
}
public function getData()
{
$aData = @unserialize($this->_getDataOne('data'));
if (!$aData) {
$aData = array();
}
return $aData;
}
public function setData($aRules) {
$this->_aData['data']=@serialize($aRules);
}
public function setData($aRules)
{
$this->_aData['data'] = @serialize($aRules);
}
public function getDataOne($sKey) {
$aData=$this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
public function getDataOne($sKey)
{
$aData = $this->getData();
if (isset($aData[$sKey])) {
return $aData[$sKey];
}
return null;
}
public function setDataOne($sKey,$mValue) {
$aData=$this->getData();
$aData[$sKey]=$mValue;
$this->setData($aData);
}
public function setDataOne($sKey, $mValue)
{
$aData = $this->getData();
$aData[$sKey] = $mValue;
$this->setData($aData);
}
}

View file

@ -25,10 +25,9 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueSelect extends EntityORM {
class ModuleProperty_EntityValueSelect extends EntityORM
{
protected $aRelations=array(
);
protected $aRelations = array();
}

View file

@ -25,10 +25,9 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTag extends EntityORM {
class ModuleProperty_EntityValueTag extends EntityORM
{
protected $aRelations=array(
);
protected $aRelations = array();
}

View file

@ -25,95 +25,115 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueType extends Entity {
class ModuleProperty_EntityValueType extends Entity
{
protected $oValue=null;
protected $oValue = null;
public function getValueForDisplay() {
// TODO: getValue() всегда вернет null
return $this->getValueObject()->getValue();
}
public function getValueForDisplay()
{
// TODO: getValue() всегда вернет null
return $this->getValueObject()->getValue();
}
public function getValueForForm() {
return htmlspecialchars($this->getValueObject()->getValue());
}
public function getValueForForm()
{
return htmlspecialchars($this->getValueObject()->getValue());
}
public function validate() {
return 'Неверное значение';
}
public function validate()
{
return 'Неверное значение';
}
protected function validateStandart($sTypeValidator,$aParamsAdditional=array(),$sFieldForValidate='value_for_validate') {
$oProperty=$this->getValueObject()->getProperty();
/**
* Получаем параметры валидации
*/
$aParams=$oProperty->getValidateRules();
if (!isset($aParams['label'])) {
$aParams['label']=$oProperty->getTitle();
}
$aParams=array_merge($aParams,$aParamsAdditional);
protected function validateStandart(
$sTypeValidator,
$aParamsAdditional = array(),
$sFieldForValidate = 'value_for_validate'
) {
$oProperty = $this->getValueObject()->getProperty();
/**
* Получаем параметры валидации
*/
$aParams = $oProperty->getValidateRules();
if (!isset($aParams['label'])) {
$aParams['label'] = $oProperty->getTitle();
}
$aParams = array_merge($aParams, $aParamsAdditional);
$oValidator=$this->Validate_CreateValidator($sTypeValidator,$this,null,$aParams);
$oValidator->fields=array($sFieldForValidate);
$oValidator->validateEntity($this);
if ($this->_hasValidateErrors()) {
return $this->_getValidateError();
} else {
return true;
}
}
$oValidator = $this->Validate_CreateValidator($sTypeValidator, $this, null, $aParams);
$oValidator->fields = array($sFieldForValidate);
$oValidator->validateEntity($this);
if ($this->_hasValidateErrors()) {
return $this->_getValidateError();
} else {
return true;
}
}
public function setValue($mValue) {
$this->resetAllValue();
}
public function setValue($mValue)
{
$this->resetAllValue();
}
public function setValueObject($oValue) {
$this->oValue=$oValue;
}
public function setValueObject($oValue)
{
$this->oValue = $oValue;
}
public function getValueObject() {
return $this->oValue;
}
public function getValueObject()
{
return $this->oValue;
}
public function resetAllValue() {
$oValue=$this->getValueObject();
$oValue->setValueInt(null);
$oValue->setValueFloat(null);
$oValue->setValueVarchar(null);
$oValue->setValueText(null);
$oValue->setValueDate(null);
$oValue->setData(null);
/**
* Удаляем из таблицы тегов
*/
$this->Property_RemoveValueTagsByTarget($oValue->getTargetType(),$oValue->getTargetId(),$oValue->getPropertyId());
/**
* Удаляем из таблицы селектов
*/
$this->Property_RemoveValueSelectsByTarget($oValue->getTargetType(),$oValue->getTargetId(),$oValue->getPropertyId());
}
public function resetAllValue()
{
$oValue = $this->getValueObject();
$oValue->setValueInt(null);
$oValue->setValueFloat(null);
$oValue->setValueVarchar(null);
$oValue->setValueText(null);
$oValue->setValueDate(null);
$oValue->setData(null);
/**
* Удаляем из таблицы тегов
*/
$this->Property_RemoveValueTagsByTarget($oValue->getTargetType(), $oValue->getTargetId(),
$oValue->getPropertyId());
/**
* Удаляем из таблицы селектов
*/
$this->Property_RemoveValueSelectsByTarget($oValue->getTargetType(), $oValue->getTargetId(),
$oValue->getPropertyId());
}
public function prepareValidateRulesRaw($aRulesRaw) {
return array();
}
public function prepareValidateRulesRaw($aRulesRaw)
{
return array();
}
public function getValidateRulesDefault() {
return array();
}
public function getValidateRulesDefault()
{
return array();
}
public function prepareParamsRaw($aParamsRaw) {
return array();
}
public function prepareParamsRaw($aParamsRaw)
{
return array();
}
public function getParamsDefault() {
return array();
}
public function getParamsDefault()
{
return array();
}
public function beforeSaveValue() {
public function beforeSaveValue()
{
}
}
public function removeValue() {
public function removeValue()
{
}
}
}

View file

@ -25,19 +25,23 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeCheckbox extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeCheckbox extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
return (bool)$this->getValueObject()->getValueInt();
}
public function getValueForDisplay()
{
return (bool)$this->getValueObject()->getValueInt();
}
public function validate() {
return $this->validateStandart('boolean');
}
public function validate()
{
return $this->validateStandart('boolean');
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oValue->setValueInt($mValue ? 1 : 0);
}
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oValue->setValueInt($mValue ? 1 : 0);
}
}

View file

@ -25,131 +25,142 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeDate extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeDate extends ModuleProperty_EntityValueType
{
protected $sFormatDateInput='dd.MM.yyyy';
protected $sFormatDateInput = 'dd.MM.yyyy';
public function getValueForDisplay() {
$oValue=$this->getValueObject();
$oProperty=$oValue->getProperty();
public function getValueForDisplay()
{
$oValue = $this->getValueObject();
$oProperty = $oValue->getProperty();
return $oValue->getValueDate() ? date($oProperty->getParam('format_out'),strtotime($oValue->getValueDate())) : '';
}
return $oValue->getValueDate() ? date($oProperty->getParam('format_out'),
strtotime($oValue->getValueDate())) : '';
}
public function getValueForForm() {
$oValue=$this->getValueObject();
public function getValueForForm()
{
$oValue = $this->getValueObject();
$sDate=$oValue->getValueDate();
// TODO: нужен конвертор формата дат вида Y в yyyy для учета $this->sFormatDateInput
return $sDate ? date('d.m.Y',strtotime($sDate)) : '';
}
$sDate = $oValue->getValueDate();
// TODO: нужен конвертор формата дат вида Y в yyyy для учета $this->sFormatDateInput
return $sDate ? date('d.m.Y', strtotime($sDate)) : '';
}
public function getValueTimeH() {
$sDate=$this->getValueObject()->getValueDate();
return $sDate ? date('H',strtotime($sDate)) : '';
}
public function getValueTimeH()
{
$sDate = $this->getValueObject()->getValueDate();
return $sDate ? date('H', strtotime($sDate)) : '';
}
public function getValueTimeM() {
$sDate=$this->getValueObject()->getValueDate();
return $sDate ? date('i',strtotime($sDate)) : '';
}
public function getValueTimeM()
{
$sDate = $this->getValueObject()->getValueDate();
return $sDate ? date('i', strtotime($sDate)) : '';
}
public function validate() {
/**
* Данные поступают ввиде массива array( 'date'=>'..', 'time' => array( 'h' => '..', 'm' => '..' ) )
*/
$aValue=$this->getValueForValidate();
$this->setValueForValidateDate(isset($aValue['date']) ? $aValue['date'] : '');
/**
* Сначала проверяем корректность даты
* В инпуте дата идет в формате d.m.Y
*/
$mRes=$this->validateStandart('date',array('format'=>$this->sFormatDateInput),'value_for_validate_date');
if ($mRes===true) {
/**
* Теперь проверяем на требование указывать дату
*/
$iTimeH=0;
$iTimeM=0;
$oValueObject=$this->getValueObject();
$oProperty=$oValueObject->getProperty();
if ($oProperty->getParam('use_time')) {
$iTimeH=isset($aValue['time']['h']) ? $aValue['time']['h'] : 0;
$iTimeM=isset($aValue['time']['m']) ? $aValue['time']['m'] : 0;
if ($iTimeH<0 or $iTimeH>23) {
$iTimeH=0;
}
if ($iTimeM<0 or $iTimeM>59) {
$iTimeM=0;
}
}
/**
* Формируем полную дату
*/
if ($this->getValueForValidateDate()) {
$sTimeFull=strtotime($this->getValueForValidateDate())+60*$iTimeM+60*60*$iTimeH;
public function validate()
{
/**
* Данные поступают ввиде массива array( 'date'=>'..', 'time' => array( 'h' => '..', 'm' => '..' ) )
*/
$aValue = $this->getValueForValidate();
$this->setValueForValidateDate(isset($aValue['date']) ? $aValue['date'] : '');
/**
* Сначала проверяем корректность даты
* В инпуте дата идет в формате d.m.Y
*/
$mRes = $this->validateStandart('date', array('format' => $this->sFormatDateInput), 'value_for_validate_date');
if ($mRes === true) {
/**
* Теперь проверяем на требование указывать дату
*/
$iTimeH = 0;
$iTimeM = 0;
$oValueObject = $this->getValueObject();
$oProperty = $oValueObject->getProperty();
if ($oProperty->getParam('use_time')) {
$iTimeH = isset($aValue['time']['h']) ? $aValue['time']['h'] : 0;
$iTimeM = isset($aValue['time']['m']) ? $aValue['time']['m'] : 0;
if ($iTimeH < 0 or $iTimeH > 23) {
$iTimeH = 0;
}
if ($iTimeM < 0 or $iTimeM > 59) {
$iTimeM = 0;
}
}
/**
* Формируем полную дату
*/
if ($this->getValueForValidateDate()) {
$sTimeFull = strtotime($this->getValueForValidateDate()) + 60 * $iTimeM + 60 * 60 * $iTimeH;
/**
* Проверка на ограничение даты
*/
if ($oProperty->getValidateRuleOne('disallowFuture')) {
if ($sTimeFull>time()) {
return "{$oProperty->getTitle()}: дата не может быть в будущем";
}
}
/**
* Проверка на ограничения только если это новая запись, либо старая с изменениями
*/
if ($oValueObject->_isNew() or strtotime($oValueObject->getValueDate())!=$sTimeFull ) {
if ($oProperty->getValidateRuleOne('disallowPast')) {
if ($sTimeFull<time()) {
return "{$oProperty->getTitle()}: дата не может быть в прошлом";
}
}
}
} else {
$sTimeFull=null;
}
/**
* Переопределяем результирующее значение
*/
$this->setValueForValidate($sTimeFull ? date('Y-m-d H:i:00',$sTimeFull) : null);
return true;
} else {
return $mRes;
}
}
/**
* Проверка на ограничение даты
*/
if ($oProperty->getValidateRuleOne('disallowFuture')) {
if ($sTimeFull > time()) {
return "{$oProperty->getTitle()}: дата не может быть в будущем";
}
}
/**
* Проверка на ограничения только если это новая запись, либо старая с изменениями
*/
if ($oValueObject->_isNew() or strtotime($oValueObject->getValueDate()) != $sTimeFull) {
if ($oProperty->getValidateRuleOne('disallowPast')) {
if ($sTimeFull < time()) {
return "{$oProperty->getTitle()}: дата не может быть в прошлом";
}
}
}
} else {
$sTimeFull = null;
}
/**
* Переопределяем результирующее значение
*/
$this->setValueForValidate($sTimeFull ? date('Y-m-d H:i:00', $sTimeFull) : null);
return true;
} else {
return $mRes;
}
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oValue->setValueDate($mValue ? $mValue : null);
}
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oValue->setValueDate($mValue ? $mValue : null);
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
$aRules['disallowFuture']=isset($aRulesRaw['disallowFuture']) ? true : false;
$aRules['disallowPast']=isset($aRulesRaw['disallowPast']) ? true : false;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
$aRules['disallowFuture'] = isset($aRulesRaw['disallowFuture']) ? true : false;
$aRules['disallowPast'] = isset($aRulesRaw['disallowPast']) ? true : false;
return $aRules;
}
return $aRules;
}
public function prepareParamsRaw($aParamsRaw) {
$aParams=array();
$aParams['use_time']=isset($aParamsRaw['use_time']) ? true : false;
public function prepareParamsRaw($aParamsRaw)
{
$aParams = array();
$aParams['use_time'] = isset($aParamsRaw['use_time']) ? true : false;
if (isset($aParamsRaw['format_out'])) {
$aParams['format_out']=$aParamsRaw['format_out'];
}
if (isset($aParamsRaw['format_out'])) {
$aParams['format_out'] = $aParamsRaw['format_out'];
}
return $aParams;
}
return $aParams;
}
public function getParamsDefault() {
return array(
'format_out'=>'Y-m-d H:i:s',
'use_time'=>true,
);
}
public function getParamsDefault()
{
return array(
'format_out' => 'Y-m-d H:i:s',
'use_time' => true,
);
}
}

View file

@ -25,252 +25,268 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeFile extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeFile extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
return $this->getFileFullName();
}
public function getValueForDisplay()
{
return $this->getFileFullName();
}
public function validate() {
$oValue=$this->getValueObject();
$oProperty=$oValue->getProperty();
$iPropertyId=$oProperty->getId();
public function validate()
{
$oValue = $this->getValueObject();
$oProperty = $oValue->getProperty();
$iPropertyId = $oProperty->getId();
$mValue=$this->getValueForValidate();
if (isset($mValue['remove']) and $mValue['remove']) {
$this->setValueForValidate(array('remove'=>true));
}
$mValue = $this->getValueForValidate();
if (isset($mValue['remove']) and $mValue['remove']) {
$this->setValueForValidate(array('remove' => true));
}
$sFileName=$this->_getValueFromFiles($iPropertyId,'name');
$sFileTmpName=$this->_getValueFromFiles($iPropertyId,'tmp_name');
$sFileError=$this->_getValueFromFiles($iPropertyId,'error');
$sFileSize=$this->_getValueFromFiles($iPropertyId,'size');
$sFileName = $this->_getValueFromFiles($iPropertyId, 'name');
$sFileTmpName = $this->_getValueFromFiles($iPropertyId, 'tmp_name');
$sFileError = $this->_getValueFromFiles($iPropertyId, 'error');
$sFileSize = $this->_getValueFromFiles($iPropertyId, 'size');
if (!$sFileTmpName) {
if ($oProperty->getValidateRuleOne('allowEmpty')) {
return true;
} elseif ($aFilePrev=$oValue->getDataOne('file') and isset($aFilePrev['path'])) {
return true;
} else {
return 'Необходимо выбрать файл';
}
}
/**
* Проверяем на ошибки
*/
if ($sFileError and $sFileError!=UPLOAD_ERR_NO_FILE) {
return "При загрузке файла возникла ошибка - {$sFileError}";
}
/**
* На корректность загрузки
*/
if (!$sFileName or !$sFileTmpName) {
return false;
}
/**
* На ограниечение по размеру файла
*/
if ($iSizeKb=$oProperty->getValidateRuleOne('size_max') and $iSizeKb*1025 < $sFileSize) {
return "Превышен размер файла, максимальный {$iSizeKb}Kb";
}
/**
* На допустимые типы файлов
*/
$aPath=pathinfo($sFileName);
if (!isset($aPath['extension']) or !$aPath['extension']) {
return false;
}
if ($aTypes=$oProperty->getParam('types') and !in_array($aPath['extension'],$aTypes)) {
return 'Неверный тип файла, допустимы '.join(', ',$aTypes);
}
/**
* Пробрасываем данные по файлу
*/
$this->setValueForValidate(array(
'name'=>$sFileName,
'tmp_name'=>$sFileTmpName,
'error'=>$sFileError,
'size'=>$sFileSize,
));
return true;
}
if (!$sFileTmpName) {
if ($oProperty->getValidateRuleOne('allowEmpty')) {
return true;
} elseif ($aFilePrev = $oValue->getDataOne('file') and isset($aFilePrev['path'])) {
return true;
} else {
return 'Необходимо выбрать файл';
}
}
/**
* Проверяем на ошибки
*/
if ($sFileError and $sFileError != UPLOAD_ERR_NO_FILE) {
return "При загрузке файла возникла ошибка - {$sFileError}";
}
/**
* На корректность загрузки
*/
if (!$sFileName or !$sFileTmpName) {
return false;
}
/**
* На ограниечение по размеру файла
*/
if ($iSizeKb = $oProperty->getValidateRuleOne('size_max') and $iSizeKb * 1025 < $sFileSize) {
return "Превышен размер файла, максимальный {$iSizeKb}Kb";
}
/**
* На допустимые типы файлов
*/
$aPath = pathinfo($sFileName);
if (!isset($aPath['extension']) or !$aPath['extension']) {
return false;
}
if ($aTypes = $oProperty->getParam('types') and !in_array($aPath['extension'], $aTypes)) {
return 'Неверный тип файла, допустимы ' . join(', ', $aTypes);
}
/**
* Пробрасываем данные по файлу
*/
$this->setValueForValidate(array(
'name' => $sFileName,
'tmp_name' => $sFileTmpName,
'error' => $sFileError,
'size' => $sFileSize,
));
return true;
}
protected function _getValueFromFiles($iId,$sName) {
if (isset($_FILES['property'][$sName][$iId]['file'])) {
return $_FILES['property'][$sName][$iId]['file'];
}
return null;
}
protected function _getValueFromFiles($iId, $sName)
{
if (isset($_FILES['property'][$sName][$iId]['file'])) {
return $_FILES['property'][$sName][$iId]['file'];
}
return null;
}
/**
* Устанавливает значение после валидации конкретного поля, а не всех полей
* Поэтому здесь нельзя сохранять файл, это нужно делать в beforeSaveValue()
*
* @param $aValue
*/
public function setValue($aValue) {
$oValue=$this->getValueObject();
/**
* Просто пробрасываем данные
*/
if ($aValue) {
$oValue->setDataOne('file_raw',$aValue);
}
}
/**
* Устанавливает значение после валидации конкретного поля, а не всех полей
* Поэтому здесь нельзя сохранять файл, это нужно делать в beforeSaveValue()
*
* @param $aValue
*/
public function setValue($aValue)
{
$oValue = $this->getValueObject();
/**
* Просто пробрасываем данные
*/
if ($aValue) {
$oValue->setDataOne('file_raw', $aValue);
}
}
/**
* Дополнительная обработка перед сохранением значения
* Здесь нужно выполнять основную загрузку файла
*/
public function beforeSaveValue() {
$oValue=$this->getValueObject();
$oProperty=$oValue->getProperty();
if (!$aFile=$oValue->getDataOne('file_raw')) {
return true;
}
$oValue->setDataOne('file_raw',null);
/**
* Удаляем предыдущий файл
*/
if (isset($aFile['remove']) or isset($aFile['name'])) {
if ($aFilePrev=$oValue->getDataOne('file')) {
$this->RemoveFile($aFilePrev['path']);
$oValue->setDataOne('file',array());
$oValue->setValueVarchar(null);
}
}
/**
* Дополнительная обработка перед сохранением значения
* Здесь нужно выполнять основную загрузку файла
*/
public function beforeSaveValue()
{
$oValue = $this->getValueObject();
$oProperty = $oValue->getProperty();
if (!$aFile = $oValue->getDataOne('file_raw')) {
return true;
}
$oValue->setDataOne('file_raw', null);
/**
* Удаляем предыдущий файл
*/
if (isset($aFile['remove']) or isset($aFile['name'])) {
if ($aFilePrev = $oValue->getDataOne('file')) {
$this->RemoveFile($aFilePrev['path']);
$oValue->setDataOne('file', array());
$oValue->setValueVarchar(null);
}
}
if (isset($aFile['name'])) {
/**
* Выполняем загрузку файла
*/
$aPathInfo=pathinfo($aFile['name']);
$sExtension=isset($aPathInfo['extension']) ? $aPathInfo['extension'] : 'unknown';
$sFileName = func_generator(20).'.'.$sExtension;
/**
* Копируем загруженный файл
*/
$sDirTmp=Config::Get('path.tmp.server').'/property/';
if (!is_dir($sDirTmp)) {
@mkdir($sDirTmp,0777,true);
}
$sFileTmp=$sDirTmp.$sFileName;
if (isset($aFile['name'])) {
/**
* Выполняем загрузку файла
*/
$aPathInfo = pathinfo($aFile['name']);
$sExtension = isset($aPathInfo['extension']) ? $aPathInfo['extension'] : 'unknown';
$sFileName = func_generator(20) . '.' . $sExtension;
/**
* Копируем загруженный файл
*/
$sDirTmp = Config::Get('path.tmp.server') . '/property/';
if (!is_dir($sDirTmp)) {
@mkdir($sDirTmp, 0777, true);
}
$sFileTmp = $sDirTmp . $sFileName;
if (move_uploaded_file($aFile['tmp_name'],$sFileTmp)) {
$sDirSave=Config::Get('path.root.server').$oProperty->getSaveFileDir();
if (!is_dir($sDirSave)) {
@mkdir($sDirSave,0777,true);
}
$sFilePath=$sDirSave.$sFileName;
/**
* Сохраняем файл
*/
if ($sFilePathNew=$this->SaveFile($sFileTmp,$sFilePath,null,true)) {
/**
* Сохраняем данные о файле
*/
$oValue->setDataOne('file',array(
'path'=>$sFilePathNew,
'size'=>filesize($sFilePath),
'name'=>htmlspecialchars($aPathInfo['filename']),
'extension'=>htmlspecialchars($aPathInfo['extension']),
));
/**
* Сохраняем уникальный ключ для доступа к файлу
*/
$oValue->setValueVarchar(func_generator(32));
return true;
}
}
}
}
if (move_uploaded_file($aFile['tmp_name'], $sFileTmp)) {
$sDirSave = Config::Get('path.root.server') . $oProperty->getSaveFileDir();
if (!is_dir($sDirSave)) {
@mkdir($sDirSave, 0777, true);
}
$sFilePath = $sDirSave . $sFileName;
/**
* Сохраняем файл
*/
if ($sFilePathNew = $this->SaveFile($sFileTmp, $sFilePath, null, true)) {
/**
* Сохраняем данные о файле
*/
$oValue->setDataOne('file', array(
'path' => $sFilePathNew,
'size' => filesize($sFilePath),
'name' => htmlspecialchars($aPathInfo['filename']),
'extension' => htmlspecialchars($aPathInfo['extension']),
));
/**
* Сохраняем уникальный ключ для доступа к файлу
*/
$oValue->setValueVarchar(func_generator(32));
return true;
}
}
}
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
if (isset($aRulesRaw['size_max']) and is_numeric($aRulesRaw['size_max'])) {
$aRules['size_max']=(int)$aRulesRaw['size_max'];
}
return $aRules;
}
if (isset($aRulesRaw['size_max']) and is_numeric($aRulesRaw['size_max'])) {
$aRules['size_max'] = (int)$aRulesRaw['size_max'];
}
return $aRules;
}
public function prepareParamsRaw($aParamsRaw) {
$aParams=array();
public function prepareParamsRaw($aParamsRaw)
{
$aParams = array();
$aParams['types']=array();
if (isset($aParamsRaw['types']) and is_array($aParamsRaw['types'])) {
foreach($aParamsRaw['types'] as $sType) {
if ($sType) {
$aParams['types'][]=htmlspecialchars($sType);
}
}
}
$aParams['access_only_auth']=isset($aParamsRaw['access_only_auth']) ? true : false;
$aParams['types'] = array();
if (isset($aParamsRaw['types']) and is_array($aParamsRaw['types'])) {
foreach ($aParamsRaw['types'] as $sType) {
if ($sType) {
$aParams['types'][] = htmlspecialchars($sType);
}
}
}
$aParams['access_only_auth'] = isset($aParamsRaw['access_only_auth']) ? true : false;
return $aParams;
}
return $aParams;
}
public function getParamsDefault() {
return array(
'types'=>array(
'zip'
),
);
}
public function getParamsDefault()
{
return array(
'types' => array(
'zip'
),
);
}
public function removeValue() {
$oValue=$this->getValueObject();
/**
* Удаляем файл
*/
if ($aFilePrev=$oValue->getDataOne('file')) {
$this->RemoveFile($aFilePrev['path']);
}
}
public function removeValue()
{
$oValue = $this->getValueObject();
/**
* Удаляем файл
*/
if ($aFilePrev = $oValue->getDataOne('file')) {
$this->RemoveFile($aFilePrev['path']);
}
}
public function getFileFullName() {
$oValue=$this->getValueObject();
if ($aFilePrev=$oValue->getDataOne('file')) {
return $aFilePrev['name'].'.'.$aFilePrev['extension'];
}
return null;
}
public function getFileFullName()
{
$oValue = $this->getValueObject();
if ($aFilePrev = $oValue->getDataOne('file')) {
return $aFilePrev['name'] . '.' . $aFilePrev['extension'];
}
return null;
}
/**
* Сохраняет(копирует) файл на сервер
* Если переопределить данный метод, то можно сохранять файл, например, на Amazon S3
*
* @param string $sFileSource Полный путь до исходного файла
* @param string $sFileDest Полный путь до файла для сохранения с типом, например, [server]/home/var/site.ru/book.pdf
* @param int|null $iMode Права chmod для файла, например, 0777
* @param bool $bRemoveSource Удалять исходный файл или нет
* @return bool | string При успешном сохранении возвращает относительный путь до файла с типом, например, [relative]/image.jpg
*/
protected function SaveFile($sFileSource,$sFileDest,$iMode=null,$bRemoveSource=false) {
if ($this->Fs_SaveFileLocal($sFileSource,$this->Fs_GetPathServer($sFileDest),$iMode,$bRemoveSource)) {
return $this->Fs_MakePath($this->Fs_GetPathRelativeFromServer($sFileDest),ModuleFs::PATH_TYPE_RELATIVE);
}
return false;
}
/**
* Удаляет файл
* Если переопределить данный метод, то можно удалять файл, например, с Amazon S3
*
* @param string $sPathFile Полный путь до файла с типом, например, [relative]/book.pdf
*
* @return mixed
*/
protected function RemoveFile($sPathFile) {
$sPathFile=$this->Fs_GetPathServer($sPathFile);
return $this->Fs_RemoveFileLocal($sPathFile);
}
/**
* Сохраняет(копирует) файл на сервер
* Если переопределить данный метод, то можно сохранять файл, например, на Amazon S3
*
* @param string $sFileSource Полный путь до исходного файла
* @param string $sFileDest Полный путь до файла для сохранения с типом, например, [server]/home/var/site.ru/book.pdf
* @param int|null $iMode Права chmod для файла, например, 0777
* @param bool $bRemoveSource Удалять исходный файл или нет
* @return bool | string При успешном сохранении возвращает относительный путь до файла с типом, например, [relative]/image.jpg
*/
protected function SaveFile($sFileSource, $sFileDest, $iMode = null, $bRemoveSource = false)
{
if ($this->Fs_SaveFileLocal($sFileSource, $this->Fs_GetPathServer($sFileDest), $iMode, $bRemoveSource)) {
return $this->Fs_MakePath($this->Fs_GetPathRelativeFromServer($sFileDest), ModuleFs::PATH_TYPE_RELATIVE);
}
return false;
}
public function DownloadFile() {
$oValue=$this->getValueObject();
if ($aFilePrev=$oValue->getDataOne('file')) {
$this->Tools_DownloadFile($this->Fs_GetPathServer($aFilePrev['path']),$aFilePrev['name'].'.'.$aFilePrev['extension'],$aFilePrev['size']);
}
return false;
}
/**
* Удаляет файл
* Если переопределить данный метод, то можно удалять файл, например, с Amazon S3
*
* @param string $sPathFile Полный путь до файла с типом, например, [relative]/book.pdf
*
* @return mixed
*/
protected function RemoveFile($sPathFile)
{
$sPathFile = $this->Fs_GetPathServer($sPathFile);
return $this->Fs_RemoveFileLocal($sPathFile);
}
public function DownloadFile()
{
$oValue = $this->getValueObject();
if ($aFilePrev = $oValue->getDataOne('file')) {
$this->Tools_DownloadFile($this->Fs_GetPathServer($aFilePrev['path']),
$aFilePrev['name'] . '.' . $aFilePrev['extension'], $aFilePrev['size']);
}
return false;
}
}

View file

@ -25,32 +25,37 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeFloat extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeFloat extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
return $this->getValueObject()->getValueFloat();
}
public function getValueForDisplay()
{
return $this->getValueObject()->getValueFloat();
}
public function validate() {
return $this->validateStandart('number',array('integerOnly'=>false));
}
public function validate()
{
return $this->validateStandart('number', array('integerOnly' => false));
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oValue->setValueFloat($mValue ? $mValue : null);
}
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oValue->setValueFloat($mValue ? $mValue : null);
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max']=(int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min']=(int)$aRulesRaw['min'];
}
return $aRules;
}
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max'] = (int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min'] = (int)$aRulesRaw['min'];
}
return $aRules;
}
}

View file

@ -25,199 +25,212 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeImage extends ModuleProperty_EntityValueTypeFile {
class ModuleProperty_EntityValueTypeImage extends ModuleProperty_EntityValueTypeFile
{
public function getValueForDisplay() {
/**
* Показываем превью, в качестве изображения берем первый ресайз из списка размеров
*/
if ($aFile=$this->oValue->getDataOne('file') and isset($aFile['path'])) {
$sSize=null;
if ($aSizes=$this->oValue->getDataOne('image_sizes')) {
$sSize=array_shift($aSizes);
}
$sWebPath=$this->Media_GetImageWebPath($aFile['path'],$sSize);
return '<a href=""><img src="'.$sWebPath.'" class="js-lbx" /></a>';
}
return $this->getFileFullName();
}
public function getValueForDisplay()
{
/**
* Показываем превью, в качестве изображения берем первый ресайз из списка размеров
*/
if ($aFile = $this->oValue->getDataOne('file') and isset($aFile['path'])) {
$sSize = null;
if ($aSizes = $this->oValue->getDataOne('image_sizes')) {
$sSize = array_shift($aSizes);
}
$sWebPath = $this->Media_GetImageWebPath($aFile['path'], $sSize);
return '<a href=""><img src="' . $sWebPath . '" class="js-lbx" /></a>';
}
return $this->getFileFullName();
}
public function getImageWebPath($sSize=null) {
if ($aFile=$this->oValue->getDataOne('file') and isset($aFile['path'])) {
return $this->Media_GetImageWebPath($aFile['path'],$sSize);
}
return null;
}
public function getImageWebPath($sSize = null)
{
if ($aFile = $this->oValue->getDataOne('file') and isset($aFile['path'])) {
return $this->Media_GetImageWebPath($aFile['path'], $sSize);
}
return null;
}
public function getImageSizes() {
return $this->oValue->getDataOne('image_sizes');
}
public function getImageSizes()
{
return $this->oValue->getDataOne('image_sizes');
}
public function getImageSizeFirst() {
if ($aSizes=$this->getImageSizes()) {
return array_shift($aSizes);
}
return null;
}
public function getImageSizeFirst()
{
if ($aSizes = $this->getImageSizes()) {
return array_shift($aSizes);
}
return null;
}
public function validate() {
/**
* Выполняем стандартные проверки для типа "Файл"
*/
$bRes=parent::validate();
public function validate()
{
/**
* Выполняем стандартные проверки для типа "Файл"
*/
$bRes = parent::validate();
$oProperty=$this->oValue->getProperty();
$oProperty = $this->oValue->getProperty();
$aValue=$this->getValueForValidate();
if (isset($aValue['tmp_name'])) {
if(!$aImageInfo=(@getimagesize($aValue['tmp_name']))) {
return 'Файл не является изображением';
}
/**
* Проверяем на максимальную ширину
*/
if ($iWMax=$oProperty->getValidateRuleOne('width_max') and $iWMax<$aImageInfo[0]) {
return 'Максимальная допустимая ширина изображения '.$iWMax.'px';
}
/**
* Проверяем на максимальную высоту
*/
if ($iHMax=$oProperty->getValidateRuleOne('height_max') and $iHMax<$aImageInfo[1]) {
return 'Максимальная допустимая высота изображения '.$iHMax.'px';
}
}
$aValue = $this->getValueForValidate();
if (isset($aValue['tmp_name'])) {
if (!$aImageInfo = (@getimagesize($aValue['tmp_name']))) {
return 'Файл не является изображением';
}
/**
* Проверяем на максимальную ширину
*/
if ($iWMax = $oProperty->getValidateRuleOne('width_max') and $iWMax < $aImageInfo[0]) {
return 'Максимальная допустимая ширина изображения ' . $iWMax . 'px';
}
/**
* Проверяем на максимальную высоту
*/
if ($iHMax = $oProperty->getValidateRuleOne('height_max') and $iHMax < $aImageInfo[1]) {
return 'Максимальная допустимая высота изображения ' . $iHMax . 'px';
}
}
return $bRes;
}
return $bRes;
}
public function beforeSaveValue() {
$oProperty=$this->oValue->getProperty();
if (!$aFile=$this->oValue->getDataOne('file_raw')) {
return true;
}
$this->oValue->setDataOne('file_raw',null);
/**
* Удаляем предыдущий файл
*/
if (isset($aFile['remove']) or isset($aFile['name'])) {
if ($aFilePrev=$this->oValue->getDataOne('file')) {
$this->Media_RemoveImageBySizes($aFilePrev['path'],$this->oValue->getDataOne('image_sizes'),true);
public function beforeSaveValue()
{
$oProperty = $this->oValue->getProperty();
if (!$aFile = $this->oValue->getDataOne('file_raw')) {
return true;
}
$this->oValue->setDataOne('file_raw', null);
/**
* Удаляем предыдущий файл
*/
if (isset($aFile['remove']) or isset($aFile['name'])) {
if ($aFilePrev = $this->oValue->getDataOne('file')) {
$this->Media_RemoveImageBySizes($aFilePrev['path'], $this->oValue->getDataOne('image_sizes'), true);
$this->oValue->setDataOne('file',array());
$this->oValue->setDataOne('image_sizes',array());
$this->oValue->setValueVarchar(null);
}
}
$this->oValue->setDataOne('file', array());
$this->oValue->setDataOne('image_sizes', array());
$this->oValue->setValueVarchar(null);
}
}
if (isset($aFile['name'])) {
/**
* Выполняем загрузку файла
*/
$aPathInfo=pathinfo($aFile['name']);
$sFileName = func_generator(20);
/**
* Копируем загруженный файл
*/
$sDirTmp=Config::Get('path.tmp.server').'/property/';
if (!is_dir($sDirTmp)) {
@mkdir($sDirTmp,0777,true);
}
$sFileTmp=$sDirTmp.$sFileName;
if (isset($aFile['name'])) {
/**
* Выполняем загрузку файла
*/
$aPathInfo = pathinfo($aFile['name']);
$sFileName = func_generator(20);
/**
* Копируем загруженный файл
*/
$sDirTmp = Config::Get('path.tmp.server') . '/property/';
if (!is_dir($sDirTmp)) {
@mkdir($sDirTmp, 0777, true);
}
$sFileTmp = $sDirTmp . $sFileName;
if (move_uploaded_file($aFile['tmp_name'],$sFileTmp)) {
$aParams=$this->Image_BuildParams('property.'.$oProperty->getTargetType().'.'.$oProperty->getType().'.'.$oProperty->getCode());
/**
* Если объект изображения не создан, возвращаем ошибку
*/
if($oImage=$this->Image_Open($sFileTmp,$aParams)) {
$sPath=$oProperty->getSaveFileDir();
/**
* Сохраняем оригинальную копию
*/
if ($sFileResult=$oImage->saveSmart($sPath,$sFileName)) {
/**
* Сохраняем данные о файле
*/
$this->oValue->setDataOne('file',array(
'path'=>$sFileResult,
'size'=>filesize($sFileTmp),
'name'=>htmlspecialchars($aPathInfo['filename']),
'extension'=>htmlspecialchars($oImage->getFormat()),
));
$aSizes=$oProperty->getParam('sizes');
/**
* Сохраняем размеры
*/
$this->oValue->setDataOne('image_sizes',$aSizes);
/**
* Сохраняем уникальный ключ для доступа к файлу
*/
$this->oValue->setValueVarchar(func_generator(32));
unset($oImage);
/**
* Генерируем ресайзы
*/
$this->Media_GenerateImageBySizes($sFileTmp,$sPath,$sFileName,$aSizes,$aParams);
if (move_uploaded_file($aFile['tmp_name'], $sFileTmp)) {
$aParams = $this->Image_BuildParams('property.' . $oProperty->getTargetType() . '.' . $oProperty->getType() . '.' . $oProperty->getCode());
/**
* Если объект изображения не создан, возвращаем ошибку
*/
if ($oImage = $this->Image_Open($sFileTmp, $aParams)) {
$sPath = $oProperty->getSaveFileDir();
/**
* Сохраняем оригинальную копию
*/
if ($sFileResult = $oImage->saveSmart($sPath, $sFileName)) {
/**
* Сохраняем данные о файле
*/
$this->oValue->setDataOne('file', array(
'path' => $sFileResult,
'size' => filesize($sFileTmp),
'name' => htmlspecialchars($aPathInfo['filename']),
'extension' => htmlspecialchars($oImage->getFormat()),
));
$aSizes = $oProperty->getParam('sizes');
/**
* Сохраняем размеры
*/
$this->oValue->setDataOne('image_sizes', $aSizes);
/**
* Сохраняем уникальный ключ для доступа к файлу
*/
$this->oValue->setValueVarchar(func_generator(32));
unset($oImage);
/**
* Генерируем ресайзы
*/
$this->Media_GenerateImageBySizes($sFileTmp, $sPath, $sFileName, $aSizes, $aParams);
$this->Fs_RemoveFileLocal($sFileTmp);
return true;
}
}
$this->Fs_RemoveFileLocal($sFileTmp);
}
}
}
$this->Fs_RemoveFileLocal($sFileTmp);
return true;
}
}
$this->Fs_RemoveFileLocal($sFileTmp);
}
}
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
if (isset($aRulesRaw['size_max']) and is_numeric($aRulesRaw['size_max'])) {
$aRules['size_max']=(int)$aRulesRaw['size_max'];
}
if (isset($aRulesRaw['width_max']) and is_numeric($aRulesRaw['width_max'])) {
$aRules['width_max']=(int)$aRulesRaw['width_max'];
}
if (isset($aRulesRaw['height_max']) and is_numeric($aRulesRaw['height_max'])) {
$aRules['height_max']=(int)$aRulesRaw['height_max'];
}
return $aRules;
}
if (isset($aRulesRaw['size_max']) and is_numeric($aRulesRaw['size_max'])) {
$aRules['size_max'] = (int)$aRulesRaw['size_max'];
}
if (isset($aRulesRaw['width_max']) and is_numeric($aRulesRaw['width_max'])) {
$aRules['width_max'] = (int)$aRulesRaw['width_max'];
}
if (isset($aRulesRaw['height_max']) and is_numeric($aRulesRaw['height_max'])) {
$aRules['height_max'] = (int)$aRulesRaw['height_max'];
}
return $aRules;
}
public function prepareParamsRaw($aParamsRaw) {
$aParams=array();
public function prepareParamsRaw($aParamsRaw)
{
$aParams = array();
$aParams['sizes']=array();
if (isset($aParamsRaw['sizes']) and is_array($aParamsRaw['sizes'])) {
foreach($aParamsRaw['sizes'] as $sSize) {
if ($sSize and preg_match('#^(\d+)?(x)?(\d+)?([a-z]{2,10})?$#Ui',$sSize)) {
$aParams['sizes'][]=htmlspecialchars($sSize);
}
}
}
$aParams['types']=array();
if (isset($aParamsRaw['types']) and is_array($aParamsRaw['types'])) {
foreach($aParamsRaw['types'] as $sType) {
if ($sType) {
$aParams['types'][]=htmlspecialchars($sType);
}
}
}
$aParams['sizes'] = array();
if (isset($aParamsRaw['sizes']) and is_array($aParamsRaw['sizes'])) {
foreach ($aParamsRaw['sizes'] as $sSize) {
if ($sSize and preg_match('#^(\d+)?(x)?(\d+)?([a-z]{2,10})?$#Ui', $sSize)) {
$aParams['sizes'][] = htmlspecialchars($sSize);
}
}
}
$aParams['types'] = array();
if (isset($aParamsRaw['types']) and is_array($aParamsRaw['types'])) {
foreach ($aParamsRaw['types'] as $sType) {
if ($sType) {
$aParams['types'][] = htmlspecialchars($sType);
}
}
}
return $aParams;
}
return $aParams;
}
public function getParamsDefault() {
return array(
'sizes'=>array(
'150x150crop'
),
'types'=>array(
'jpg','jpeg','gif','png'
)
);
}
public function getParamsDefault()
{
return array(
'sizes' => array(
'150x150crop'
),
'types' => array(
'jpg',
'jpeg',
'gif',
'png'
)
);
}
}

View file

@ -25,32 +25,37 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeInt extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeInt extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
return $this->getValueObject()->getValueInt();
}
public function getValueForDisplay()
{
return $this->getValueObject()->getValueInt();
}
public function validate() {
return $this->validateStandart('number',array('integerOnly'=>true));
}
public function validate()
{
return $this->validateStandart('number', array('integerOnly' => true));
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oValue->setValueInt($mValue ? $mValue : null);
}
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oValue->setValueInt($mValue ? $mValue : null);
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max']=(int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min']=(int)$aRulesRaw['min'];
}
return $aRules;
}
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max'] = (int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min'] = (int)$aRulesRaw['min'];
}
return $aRules;
}
}

View file

@ -25,130 +25,149 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeSelect extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeSelect extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
$oValue=$this->getValueObject();
$aValues=$oValue->getDataOne('values');
return is_array($aValues) ? join(', ',$aValues) : '';
}
public function getValueForDisplay()
{
$oValue = $this->getValueObject();
$aValues = $oValue->getDataOne('values');
return is_array($aValues) ? join(', ', $aValues) : '';
}
public function getValueForForm() {
$oValue=$this->getValueObject();
$aValues=$oValue->getDataOne('values');
return $aValues;
}
public function getValueForForm()
{
$oValue = $this->getValueObject();
$aValues = $oValue->getDataOne('values');
return $aValues;
}
public function validate() {
$oProperty=$this->getValueObject()->getProperty();
public function validate()
{
$oProperty = $this->getValueObject()->getProperty();
$iValue=$this->getValueForValidate();
if (is_array($iValue)) {
$iValue=array_filter($iValue);
}
if (!$iValue and $oProperty->getValidateRuleOne('allowEmpty')) {
return true;
}
if (is_array($iValue)) {
if ($oProperty->getValidateRuleOne('allowMany')) {
if ($oProperty->getValidateRuleOne('max') and count($iValue)>$oProperty->getValidateRuleOne('max')) {
return 'Максимально можно выбрать только '.$oProperty->getValidateRuleOne('max').' элемента';
}
if ($oProperty->getValidateRuleOne('min') and count($iValue)<$oProperty->getValidateRuleOne('min')) {
return 'Минимально можно выбрать только '.$oProperty->getValidateRuleOne('min').' элемента';
}
/**
* Для безопасности
*/
$aValues=array();
foreach($iValue as $iV) {
$aValues[]=(int)$iV;
}
if (count($aValues)==count($this->Property_GetSelectItemsByFilter(array('property_id'=>$oProperty->getId(),'id in'=>$aValues)))) {
$this->setValueForValidate($aValues);
return true;
} else {
return 'Проверьте корректность выбранных элементов';
}
} elseif (count($iValue)==1) {
$iValue=(int)reset($iValue);
} else {
return 'Можно выбрать только один элемент';
}
}
/**
* Проверяем значение
*/
if ($oSelect=$this->Property_GetSelectByIdAndPropertyId($iValue,$oProperty->getId())) {
return true;
}
return 'Необходимо выбрать значение';
}
$iValue = $this->getValueForValidate();
if (is_array($iValue)) {
$iValue = array_filter($iValue);
}
if (!$iValue and $oProperty->getValidateRuleOne('allowEmpty')) {
return true;
}
if (is_array($iValue)) {
if ($oProperty->getValidateRuleOne('allowMany')) {
if ($oProperty->getValidateRuleOne('max') and count($iValue) > $oProperty->getValidateRuleOne('max')) {
return 'Максимально можно выбрать только ' . $oProperty->getValidateRuleOne('max') . ' элемента';
}
if ($oProperty->getValidateRuleOne('min') and count($iValue) < $oProperty->getValidateRuleOne('min')) {
return 'Минимально можно выбрать только ' . $oProperty->getValidateRuleOne('min') . ' элемента';
}
/**
* Для безопасности
*/
$aValues = array();
foreach ($iValue as $iV) {
$aValues[] = (int)$iV;
}
if (count($aValues) == count($this->Property_GetSelectItemsByFilter(array(
'property_id' => $oProperty->getId(),
'id in' => $aValues
)))
) {
$this->setValueForValidate($aValues);
return true;
} else {
return 'Проверьте корректность выбранных элементов';
}
} elseif (count($iValue) == 1) {
$iValue = (int)reset($iValue);
} else {
return 'Можно выбрать только один элемент';
}
}
/**
* Проверяем значение
*/
if ($oSelect = $this->Property_GetSelectByIdAndPropertyId($iValue, $oProperty->getId())) {
return true;
}
return 'Необходимо выбрать значение';
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oProperty=$oValue->getProperty();
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oProperty = $oValue->getProperty();
$aValues=array();
/**
* Сохраняем с data, т.к. может быть множественный выбор
*/
if ($mValue) {
if (is_array($mValue)) {
$aSelectItems=$this->Property_GetSelectItemsByFilter(array('property_id'=>$oProperty->getId(),'id in'=>$mValue));
foreach($aSelectItems as $oSelect) {
$aValues[$oSelect->getId()]=$oSelect->getValue();
}
} else {
if ($oSelect=$this->Property_GetSelectByIdAndPropertyId($mValue,$oProperty->getId())) {
$aValues[$oSelect->getId()]=$oSelect->getValue();
}
}
}
$oValue->setData($aValues ? array('values'=>$aValues) : array());
}
$aValues = array();
/**
* Сохраняем с data, т.к. может быть множественный выбор
*/
if ($mValue) {
if (is_array($mValue)) {
$aSelectItems = $this->Property_GetSelectItemsByFilter(array(
'property_id' => $oProperty->getId(),
'id in' => $mValue
));
foreach ($aSelectItems as $oSelect) {
$aValues[$oSelect->getId()] = $oSelect->getValue();
}
} else {
if ($oSelect = $this->Property_GetSelectByIdAndPropertyId($mValue, $oProperty->getId())) {
$aValues[$oSelect->getId()] = $oSelect->getValue();
}
}
}
$oValue->setData($aValues ? array('values' => $aValues) : array());
}
/**
* Дополнительная обработка перед сохранением значения
*/
public function beforeSaveValue() {
$oValue=$this->getValueObject();
if ($aValues=$oValue->getData()) {
foreach($aValues['values'] as $k=>$v) {
$oSelect=Engine::GetEntity('ModuleProperty_EntityValueSelect');
$oSelect->setPropertyId($oValue->getPropertyId());
$oSelect->setTargetType($oValue->getTargetType());
$oSelect->setTargetId($oValue->getTargetId());
$oSelect->setSelectId($k);
$oSelect->Add();
}
}
}
/**
* Дополнительная обработка перед сохранением значения
*/
public function beforeSaveValue()
{
$oValue = $this->getValueObject();
if ($aValues = $oValue->getData()) {
foreach ($aValues['values'] as $k => $v) {
$oSelect = Engine::GetEntity('ModuleProperty_EntityValueSelect');
$oSelect->setPropertyId($oValue->getPropertyId());
$oSelect->setTargetType($oValue->getTargetType());
$oSelect->setTargetId($oValue->getTargetId());
$oSelect->setSelectId($k);
$oSelect->Add();
}
}
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
$aRules['allowMany']=isset($aRulesRaw['allowMany']) ? true : false;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
$aRules['allowMany'] = isset($aRulesRaw['allowMany']) ? true : false;
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max']=(int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min']=(int)$aRulesRaw['min'];
}
return $aRules;
}
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max'] = (int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min'] = (int)$aRulesRaw['min'];
}
return $aRules;
}
public function removeValue() {
$oValue=$this->getValueObject();
/**
* Удаляем значения select'а из дополнительной таблицы
*/
if ($aSelects=$this->Property_GetValueSelectItemsByFilter(array('property_id'=>$oValue->getPropertyId(),'target_id'=>$oValue->getTargetId()))) {
foreach($aSelects as $oSelect) {
$oSelect->Delete();
}
}
}
public function removeValue()
{
$oValue = $this->getValueObject();
/**
* Удаляем значения select'а из дополнительной таблицы
*/
if ($aSelects = $this->Property_GetValueSelectItemsByFilter(array(
'property_id' => $oValue->getPropertyId(),
'target_id' => $oValue->getTargetId()
))
) {
foreach ($aSelects as $oSelect) {
$oSelect->Delete();
}
}
}
}

View file

@ -25,69 +25,81 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeTags extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeTags extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
return htmlspecialchars($this->getValueObject()->getValueVarchar());
}
public function getValueForDisplay()
{
return htmlspecialchars($this->getValueObject()->getValueVarchar());
}
public function validate() {
return $this->validateStandart('tags');
}
public function validate()
{
return $this->validateStandart('tags');
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oValue->setValueVarchar($mValue ? $mValue : null);
}
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oValue->setValueVarchar($mValue ? $mValue : null);
}
/**
* Дополнительная обработка перед сохранением значения
*/
public function beforeSaveValue() {
/**
* Заливаем теги в отдельную таблицу
*/
if ($aTags=$this->getTagsArray()) {
$oValue=$this->getValueObject();
foreach($aTags as $sTag) {
$oTag=Engine::GetEntity('ModuleProperty_EntityValueTag');
$oTag->setPropertyId($oValue->getPropertyId());
$oTag->setTargetType($oValue->getTargetType());
$oTag->setTargetId($oValue->getTargetId());
$oTag->setText($sTag);
$oTag->Add();
}
}
}
/**
* Дополнительная обработка перед сохранением значения
*/
public function beforeSaveValue()
{
/**
* Заливаем теги в отдельную таблицу
*/
if ($aTags = $this->getTagsArray()) {
$oValue = $this->getValueObject();
foreach ($aTags as $sTag) {
$oTag = Engine::GetEntity('ModuleProperty_EntityValueTag');
$oTag->setPropertyId($oValue->getPropertyId());
$oTag->setTargetType($oValue->getTargetType());
$oTag->setTargetId($oValue->getTargetId());
$oTag->setText($sTag);
$oTag->Add();
}
}
}
public function getTagsArray() {
$sTags=$this->getValueObject()->getValueVarchar();
if ($sTags) {
return explode(',',$sTags);
}
return array();
}
public function getTagsArray()
{
$sTags = $this->getValueObject()->getValueVarchar();
if ($sTags) {
return explode(',', $sTags);
}
return array();
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
if (isset($aRulesRaw['count']) and ($iCount=(int)$aRulesRaw['count']) > 0) {
$aRules['count']=$iCount;
}
return $aRules;
}
if (isset($aRulesRaw['count']) and ($iCount = (int)$aRulesRaw['count']) > 0) {
$aRules['count'] = $iCount;
}
return $aRules;
}
public function removeValue() {
$oValue=$this->getValueObject();
/**
* Удаляем теги из дополнительной таблицы
*/
if ($aTags=$this->Property_GetValueTagItemsByFilter(array('property_id'=>$oValue->getPropertyId(),'target_id'=>$oValue->getTargetId()))) {
foreach($aTags as $oTag) {
$oTag->Delete();
}
}
}
public function removeValue()
{
$oValue = $this->getValueObject();
/**
* Удаляем теги из дополнительной таблицы
*/
if ($aTags = $this->Property_GetValueTagItemsByFilter(array(
'property_id' => $oValue->getPropertyId(),
'target_id' => $oValue->getTargetId()
))
) {
foreach ($aTags as $oTag) {
$oTag->Delete();
}
}
}
}

View file

@ -25,52 +25,59 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeText extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeText extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
return $this->getValueObject()->getValueText();
}
public function getValueForDisplay()
{
return $this->getValueObject()->getValueText();
}
public function getValueForForm() {
$oValue=$this->getValueObject();
return htmlspecialchars($oValue->getDataOne('text_source'));
}
public function getValueForForm()
{
$oValue = $this->getValueObject();
return htmlspecialchars($oValue->getDataOne('text_source'));
}
public function validate() {
return $this->validateStandart('string');
}
public function validate()
{
return $this->validateStandart('string');
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oProperty=$oValue->getProperty();
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oProperty = $oValue->getProperty();
$oValue->setDataOne('text_source',$mValue);
if ($oProperty->getParam('use_html')) {
$mValue=$this->Text_Parser($mValue);
} else {
$mValue=htmlspecialchars($mValue);
}
$oValue->setValueText($mValue ? $mValue : null);
}
$oValue->setDataOne('text_source', $mValue);
if ($oProperty->getParam('use_html')) {
$mValue = $this->Text_Parser($mValue);
} else {
$mValue = htmlspecialchars($mValue);
}
$oValue->setValueText($mValue ? $mValue : null);
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max']=(int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min']=(int)$aRulesRaw['min'];
}
return $aRules;
}
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max'] = (int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min'] = (int)$aRulesRaw['min'];
}
return $aRules;
}
public function prepareParamsRaw($aParamsRaw) {
$aParams=array();
$aParams['use_html']=isset($aParamsRaw['use_html']) ? true : false;
public function prepareParamsRaw($aParamsRaw)
{
$aParams = array();
$aParams['use_html'] = isset($aParamsRaw['use_html']) ? true : false;
return $aParams;
}
return $aParams;
}
}

View file

@ -25,32 +25,37 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeVarchar extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeVarchar extends ModuleProperty_EntityValueType
{
public function getValueForDisplay() {
return $this->getValueObject()->getValueVarchar();
}
public function getValueForDisplay()
{
return $this->getValueObject()->getValueVarchar();
}
public function validate() {
return $this->validateStandart('string');
}
public function validate()
{
return $this->validateStandart('string');
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oValue->setValueVarchar($mValue ? htmlspecialchars($mValue) : null);
}
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oValue->setValueVarchar($mValue ? htmlspecialchars($mValue) : null);
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max']=(int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min']=(int)$aRulesRaw['min'];
}
return $aRules;
}
if (isset($aRulesRaw['max']) and is_numeric($aRulesRaw['max'])) {
$aRules['max'] = (int)$aRulesRaw['max'];
}
if (isset($aRulesRaw['min']) and is_numeric($aRulesRaw['min'])) {
$aRules['min'] = (int)$aRulesRaw['min'];
}
return $aRules;
}
}

View file

@ -25,171 +25,188 @@
* @package application.modules.property
* @since 2.0
*/
class ModuleProperty_EntityValueTypeVideoLink extends ModuleProperty_EntityValueType {
class ModuleProperty_EntityValueTypeVideoLink extends ModuleProperty_EntityValueType
{
const VIDEO_PROVIDER_YOUTUBE='youtube';
const VIDEO_PROVIDER_VIMEO='vimeo';
const VIDEO_PROVIDER_RUTUBE='rutube';
const VIDEO_PROVIDER_YOUTUBE = 'youtube';
const VIDEO_PROVIDER_VIMEO = 'vimeo';
const VIDEO_PROVIDER_RUTUBE = 'rutube';
public function getValueForDisplay() {
return $this->getVideoCodeFrame();
}
public function getValueForDisplay()
{
return $this->getVideoCodeFrame();
}
public function validate() {
$mRes=$this->validateStandart('url',array('defaultScheme'=>'http'));
if ($mRes===true) {
/**
* Теперь проверяем на принадлежность к разным видео-хостингам
*/
if ($this->getValueForValidate() and !$this->checkVideo($this->getValueForValidate())) {
return 'Необходимо указать корректную ссылку на видео: YouTube, Vimeo';
}
return true;
} else {
return $mRes;
}
}
public function validate()
{
$mRes = $this->validateStandart('url', array('defaultScheme' => 'http'));
if ($mRes === true) {
/**
* Теперь проверяем на принадлежность к разным видео-хостингам
*/
if ($this->getValueForValidate() and !$this->checkVideo($this->getValueForValidate())) {
return 'Необходимо указать корректную ссылку на видео: YouTube, Vimeo';
}
return true;
} else {
return $mRes;
}
}
public function prepareValidateRulesRaw($aRulesRaw) {
$aRules=array();
$aRules['allowEmpty']=isset($aRulesRaw['allowEmpty']) ? false : true;
return $aRules;
}
public function prepareValidateRulesRaw($aRulesRaw)
{
$aRules = array();
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false : true;
return $aRules;
}
public function setValue($mValue) {
$this->resetAllValue();
$oValue=$this->getValueObject();
$oValue->setValueVarchar($mValue ? $mValue : null);
/**
* Получаем и сохраняем ссылку на превью
*/
$this->retrievePreview($oValue);
}
public function setValue($mValue)
{
$this->resetAllValue();
$oValue = $this->getValueObject();
$oValue->setValueVarchar($mValue ? $mValue : null);
/**
* Получаем и сохраняем ссылку на превью
*/
$this->retrievePreview($oValue);
}
protected function retrievePreview($oValue) {
$sLink=$oValue->getValueVarchar();
$sProvider=$this->getVideoProvider($sLink);
$sId=$this->getVideoId($sLink);
if ($sProvider==self::VIDEO_PROVIDER_YOUTUBE) {
$oValue->setDataOne('preview_small',"http://img.youtube.com/vi/{$sId}/default.jpg");
$oValue->setDataOne('preview_normal',"http://img.youtube.com/vi/{$sId}/0.jpg");
} elseif ($sProvider==self::VIDEO_PROVIDER_VIMEO) {
$aRetrieveData=@json_decode(file_get_contents("http://vimeo.com/api/v2/video/{$sId}.json"),true);
if (isset($aRetrieveData[0]['thumbnail_medium'])) {
$oValue->setDataOne('preview_small',$aRetrieveData[0]['thumbnail_medium']);
$oValue->setDataOne('preview_normal',$aRetrieveData[0]['thumbnail_large']);
}
} elseif ($sProvider==self::VIDEO_PROVIDER_RUTUBE) {
$aRetrieveData=@json_decode(file_get_contents("http://rutube.ru/api/video/{$sId}/?format=json"),true);
if (isset($aRetrieveData['thumbnail_url'])) {
$oValue->setDataOne('preview_small',$aRetrieveData['thumbnail_url'].'?size=s');
$oValue->setDataOne('preview_normal',$aRetrieveData['thumbnail_url']);
}
}
}
protected function retrievePreview($oValue)
{
$sLink = $oValue->getValueVarchar();
$sProvider = $this->getVideoProvider($sLink);
$sId = $this->getVideoId($sLink);
if ($sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
$oValue->setDataOne('preview_small', "http://img.youtube.com/vi/{$sId}/default.jpg");
$oValue->setDataOne('preview_normal', "http://img.youtube.com/vi/{$sId}/0.jpg");
} elseif ($sProvider == self::VIDEO_PROVIDER_VIMEO) {
$aRetrieveData = @json_decode(file_get_contents("http://vimeo.com/api/v2/video/{$sId}.json"), true);
if (isset($aRetrieveData[0]['thumbnail_medium'])) {
$oValue->setDataOne('preview_small', $aRetrieveData[0]['thumbnail_medium']);
$oValue->setDataOne('preview_normal', $aRetrieveData[0]['thumbnail_large']);
}
} elseif ($sProvider == self::VIDEO_PROVIDER_RUTUBE) {
$aRetrieveData = @json_decode(file_get_contents("http://rutube.ru/api/video/{$sId}/?format=json"), true);
if (isset($aRetrieveData['thumbnail_url'])) {
$oValue->setDataOne('preview_small', $aRetrieveData['thumbnail_url'] . '?size=s');
$oValue->setDataOne('preview_normal', $aRetrieveData['thumbnail_url']);
}
}
}
public function checkVideo($sLink) {
return $this->getVideoId($sLink) ? true : false;
}
public function checkVideo($sLink)
{
return $this->getVideoId($sLink) ? true : false;
}
public function getVideoId($sLink=null) {
if (is_null($sLink)) {
$sLink=$this->getValueObject()->getValueVarchar();
}
$sProvider=$this->getVideoProvider($sLink);
/**
* youtube
* http://www.youtube.com/watch?v=LZaCb5Y9SyM
* http://youtu.be/LZaCb5Y9SyM
*/
if ($sProvider==self::VIDEO_PROVIDER_YOUTUBE) {
if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $sLink, $aMatch)) {
return $aMatch[0];
}
}
/**
* vimeo
* http://vimeo.com/72359144
*/
if ($sProvider==self::VIDEO_PROVIDER_VIMEO) {
return substr(parse_url($sLink, PHP_URL_PATH), 1);
}
/**
* rutube
* http://rutube.ru/video/ee523c9164c8f9fc8b267c66a0a3adae/
* http://rutube.ru/video/6fd81c1c212c002673280850a1c56415/#.UMQYln9yTWQ
* http://rutube.ru/tracks/6032725.html
* http://rutube.ru/video/embed/6032725
*/
if ($sProvider==self::VIDEO_PROVIDER_RUTUBE) {
if (preg_match('/(?:http|https)+:\/\/(?:www\.|)rutube\.ru\/video\/embed\/([a-zA-Z0-9_\-]+)/i', $sLink, $aMatch) || preg_match('/(?:http|https)+:\/\/(?:www\.|)rutube\.ru\/(?:tracks|video)\/([a-zA-Z0-9_\-]+)(&.+)?/i', $sLink, $aMatch)) {
return $aMatch[1];
}
}
return null;
}
public function getVideoId($sLink = null)
{
if (is_null($sLink)) {
$sLink = $this->getValueObject()->getValueVarchar();
}
$sProvider = $this->getVideoProvider($sLink);
/**
* youtube
* http://www.youtube.com/watch?v=LZaCb5Y9SyM
* http://youtu.be/LZaCb5Y9SyM
*/
if ($sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $sLink,
$aMatch)) {
return $aMatch[0];
}
}
/**
* vimeo
* http://vimeo.com/72359144
*/
if ($sProvider == self::VIDEO_PROVIDER_VIMEO) {
return substr(parse_url($sLink, PHP_URL_PATH), 1);
}
/**
* rutube
* http://rutube.ru/video/ee523c9164c8f9fc8b267c66a0a3adae/
* http://rutube.ru/video/6fd81c1c212c002673280850a1c56415/#.UMQYln9yTWQ
* http://rutube.ru/tracks/6032725.html
* http://rutube.ru/video/embed/6032725
*/
if ($sProvider == self::VIDEO_PROVIDER_RUTUBE) {
if (preg_match('/(?:http|https)+:\/\/(?:www\.|)rutube\.ru\/video\/embed\/([a-zA-Z0-9_\-]+)/i', $sLink,
$aMatch) || preg_match('/(?:http|https)+:\/\/(?:www\.|)rutube\.ru\/(?:tracks|video)\/([a-zA-Z0-9_\-]+)(&.+)?/i',
$sLink, $aMatch)
) {
return $aMatch[1];
}
}
return null;
}
public function getVideoProvider($sLink) {
if (preg_match("#(youtube\.)|(youtu\.be)#i",$sLink)) {
return self::VIDEO_PROVIDER_YOUTUBE;
}
if (preg_match("#(vimeo\.)#i",$sLink)) {
return self::VIDEO_PROVIDER_VIMEO;
}
if (preg_match("#(rutube\.ru)#i",$sLink)) {
return self::VIDEO_PROVIDER_RUTUBE;
}
return null;
}
public function getVideoProvider($sLink)
{
if (preg_match("#(youtube\.)|(youtu\.be)#i", $sLink)) {
return self::VIDEO_PROVIDER_YOUTUBE;
}
if (preg_match("#(vimeo\.)#i", $sLink)) {
return self::VIDEO_PROVIDER_VIMEO;
}
if (preg_match("#(rutube\.ru)#i", $sLink)) {
return self::VIDEO_PROVIDER_RUTUBE;
}
return null;
}
public function getVideoCodeFrame() {
$sLink=$this->getValueObject()->getValueVarchar();
$sProvider=$this->getVideoProvider($sLink);
$sId=$this->getVideoId($sLink);
if ($sProvider==self::VIDEO_PROVIDER_YOUTUBE) {
return '
<iframe style="max-width: 100%;width: 100%;height: 495px;" src="//www.youtube.com/embed/'.$sId.'" frameborder="0" allowfullscreen></iframe>
public function getVideoCodeFrame()
{
$sLink = $this->getValueObject()->getValueVarchar();
$sProvider = $this->getVideoProvider($sLink);
$sId = $this->getVideoId($sLink);
if ($sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
return '
<iframe style="max-width: 100%;width: 100%;height: 495px;" src="//www.youtube.com/embed/' . $sId . '" frameborder="0" allowfullscreen></iframe>
';
} elseif ($sProvider==self::VIDEO_PROVIDER_VIMEO) {
return '
<iframe src="http://player.vimeo.com/video/'.$sId.'?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;color=e6ae9e" style="max-width: 100%;width: 100%;height: 495px;" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
} elseif ($sProvider == self::VIDEO_PROVIDER_VIMEO) {
return '
<iframe src="http://player.vimeo.com/video/' . $sId . '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;color=e6ae9e" style="max-width: 100%;width: 100%;height: 495px;" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
';
} elseif ($sProvider==self::VIDEO_PROVIDER_RUTUBE) {
return '
<iframe src="http://rutube.ru/video/embed/'.$sId.'" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowfullscreen style="max-width: 100%;width: 100%;height: 495px;"></iframe>
} elseif ($sProvider == self::VIDEO_PROVIDER_RUTUBE) {
return '
<iframe src="http://rutube.ru/video/embed/' . $sId . '" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowfullscreen style="max-width: 100%;width: 100%;height: 495px;"></iframe>
';
}
return '';
}
}
return '';
}
public function getPreview($sType='small') {
$oValue=$this->getValueObject();
return $oValue->getDataOne("preview_{$sType}");
}
public function getPreview($sType = 'small')
{
$oValue = $this->getValueObject();
return $oValue->getDataOne("preview_{$sType}");
}
public function getCountView() {
$oValue=$this->getValueObject();
$sLink=$oValue->getValueVarchar();
$sProvider=$this->getVideoProvider($sLink);
$sId=$this->getVideoId($sLink);
if ($sProvider==self::VIDEO_PROVIDER_YOUTUBE) {
$iCount=(int)$oValue->getDataOne("count_view");
$iCountViewLastTime=(int)$oValue->getDataOne("count_view_last_time");
if (time()-$iCountViewLastTime > 60*60*1) {
$aData = @json_decode(file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$sId}?v=2&alt=json"),true);
if (isset($aData['entry']['yt$statistics']['viewCount'])) {
$iCount=$aData['entry']['yt$statistics']['viewCount'];
}
$oValue->setDataOne("count_view",$iCount);
$oValue->setDataOne("count_view_last_time",time());
$oValue->Update();
}
return $iCount;
} elseif ($sProvider==self::VIDEO_PROVIDER_VIMEO) {
public function getCountView()
{
$oValue = $this->getValueObject();
$sLink = $oValue->getValueVarchar();
$sProvider = $this->getVideoProvider($sLink);
$sId = $this->getVideoId($sLink);
if ($sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
$iCount = (int)$oValue->getDataOne("count_view");
$iCountViewLastTime = (int)$oValue->getDataOne("count_view_last_time");
if (time() - $iCountViewLastTime > 60 * 60 * 1) {
$aData = @json_decode(file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$sId}?v=2&alt=json"),
true);
if (isset($aData['entry']['yt$statistics']['viewCount'])) {
$iCount = $aData['entry']['yt$statistics']['viewCount'];
}
$oValue->setDataOne("count_view", $iCount);
$oValue->setDataOne("count_view_last_time", time());
$oValue->Update();
}
return $iCount;
} elseif ($sProvider == self::VIDEO_PROVIDER_VIMEO) {
} elseif ($sProvider==self::VIDEO_PROVIDER_RUTUBE) {
} elseif ($sProvider == self::VIDEO_PROVIDER_RUTUBE) {
}
return null;
}
}
return null;
}
}

Some files were not shown because too many files have changed in this diff Show more