1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-28 20:45:00 +03:00

Оптимизация валидации полей топика - вынос валидации в правила сущности

This commit is contained in:
Mzhelskiy Maxim 2012-04-06 20:34:11 +04:00
parent 3145f9d1e6
commit 928fe58013
10 changed files with 202 additions and 95 deletions

View file

@ -240,10 +240,23 @@ class ActionTopic extends Action {
if (!isPost('submit_topic_publish') and !isPost('submit_topic_save')) {
return false;
}
$oTopic=Engine::GetEntity('Topic');
$oTopic->_setValidateScenario('topic');
/**
* Заполняем поля для валидации
*/
$oTopic->setBlogId(getRequest('blog_id'));
$oTopic->setTitle(strip_tags(getRequest('topic_title')));
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setUserId($this->oUserCurrent->getId());
$oTopic->setType('topic');
$oTopic->setDateAdd(date("Y-m-d H:i:s"));
$oTopic->setUserIp(func_getIp());
/**
* Проверка корректности полей формы
*/
if (!$this->checkTopicFields()) {
if (!$this->checkTopicFields($oTopic)) {
return false;
}
/**
@ -269,13 +282,6 @@ class ActionTopic extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'),$this->Lang_Get('error'));
return false;
}
/**
* Проверяем топик на уникальность
*/
if ($oTopicEquivalent=$this->Topic_GetTopicUnique($this->oUserCurrent->getId(),md5(getRequest('topic_text')))) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_text_error_unique'),$this->Lang_Get('error'));
return false;
}
/**
* Проверяем разрешено ли постить топик по времени
*/
@ -286,25 +292,15 @@ class ActionTopic extends Action {
/**
* Теперь можно смело добавлять топик к блогу
*/
$oTopic=Engine::GetEntity('Topic');
$oTopic->setBlogId($oBlog->getId());
$oTopic->setUserId($this->oUserCurrent->getId());
$oTopic->setType('topic');
$oTopic->setTitle(getRequest('topic_title'));
$oTopic->setTextHash(md5(getRequest('topic_text')));
/**
* Получаемый и устанавливаем разрезанный текст по тегу <cut>
*/
list($sTextShort,$sTextNew,$sTextCut) = $this->Text_Cut(getRequest('topic_text'));
list($sTextShort,$sTextNew,$sTextCut) = $this->Text_Cut($oTopic->getTextSource());
$oTopic->setCutText($sTextCut);
$oTopic->setText($this->Text_Parser($sTextNew));
$oTopic->setTextShort($this->Text_Parser($sTextShort));
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setDateAdd(date("Y-m-d H:i:s"));
$oTopic->setUserIp(func_getIp());
/**
* Публикуем или сохраняем
*/
@ -376,16 +372,31 @@ class ActionTopic extends Action {
* @return unknown
*/
protected function SubmitEdit($oTopic) {
$oTopic->_setValidateScenario('topic');
/**
* Сохраняем старое значение идентификатора блога
*/
$sBlogIdOld = $oTopic->getBlogId();
/**
* Заполняем поля для валидации
*/
$oTopic->setBlogId(getRequest('blog_id'));
$oTopic->setTitle(strip_tags(getRequest('topic_title')));
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setUserIp(func_getIp());
/**
* Проверка корректности полей формы
*/
if (!$this->checkTopicFields()) {
if (!$this->checkTopicFields($oTopic)) {
return false;
}
/**
* Определяем в какой блог делаем запись
*/
$iBlogId=getRequest('blog_id');
$iBlogId=$oTopic->getBlogId();
if ($iBlogId==0) {
$oBlog=$this->Blog_GetPersonalBlogByUserId($oTopic->getUserId());
} else {
@ -405,15 +416,6 @@ class ActionTopic extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'),$this->Lang_Get('error'));
return false;
}
/**
* Проверяем топик на уникальность
*/
if ($oTopicEquivalent=$this->Topic_GetTopicUnique($oTopic->getUserId(),md5(getRequest('topic_text')))) {
if ($oTopicEquivalent->getId()!=$oTopic->getId()) {
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_text_error_unique'),$this->Lang_Get('error'));
return false;
}
}
/**
* Проверяем разрешено ли постить топик по времени
*/
@ -421,28 +423,16 @@ class ActionTopic extends Action {
$this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'),$this->Lang_Get('error'));
return;
}
/**
* Сохраняем старое значение идентификатора блога
*/
$sBlogIdOld = $oTopic->getBlogId();
/**
* Теперь можно смело редактировать топик
*/
$oTopic->setBlogId($oBlog->getId());
$oTopic->setTitle(getRequest('topic_title'));
$oTopic->setTextHash(md5(getRequest('topic_text')));
/**
* Получаемый и устанавливаем разрезанный текст по тегу <cut>
*/
list($sTextShort,$sTextNew,$sTextCut) = $this->Text_Cut(getRequest('topic_text'));
list($sTextShort,$sTextNew,$sTextCut) = $this->Text_Cut($oTopic->getTextSource());
$oTopic->setCutText($sTextCut);
$oTopic->setText($this->Text_Parser($sTextNew));
$oTopic->setTextShort($this->Text_Parser($sTextShort));
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setUserIp(func_getIp());
/**
* Публикуем или сохраняем в черновиках
*/
@ -517,60 +507,16 @@ class ActionTopic extends Action {
/**
* Проверка полей формы
*
* @return unknown
* @return bool
*/
protected function checkTopicFields() {
protected function checkTopicFields($oTopic) {
$this->Security_ValidateSendForm();
$bOk=true;
/**
* Проверяем есть ли блог в кторый постим
*/
if (!func_check(getRequest('blog_id',null,'post'),'id')) {
$this->Message_AddError($this->Lang_Get('topic_create_blog_error_unknown'),$this->Lang_Get('error'));
if (!$oTopic->_Validate()) {
$this->Message_AddError($oTopic->_getValidateError(),$this->Lang_Get('error'));
$bOk=false;
}
/**
* Проверяем есть ли заголовок топика
*/
if (!func_check(getRequest('topic_title',null,'post'),'text',2,200)) {
$this->Message_AddError($this->Lang_Get('topic_create_title_error'),$this->Lang_Get('error'));
$bOk=false;
}
/**
* Проверяем есть ли содержание топика
*/
if (!func_check(getRequest('topic_text',null,'post'),'text',2,Config::Get('module.topic.max_length'))) {
$this->Message_AddError($this->Lang_Get('topic_create_text_error'),$this->Lang_Get('error'));
$bOk=false;
}
/**
* Проверяем есть ли теги(метки)
*/
if (!func_check(getRequest('topic_tags',null,'post'),'text',2,500)) {
$this->Message_AddError($this->Lang_Get('topic_create_tags_error'),$this->Lang_Get('error'));
$bOk=false;
}
/**
* проверяем ввод тегов
*/
$sTags=getRequest('topic_tags',null,'post');
$aTags=explode(',',rtrim($sTags,"\r\n\t\0\x0B ."));
$aTagsNew=array();
$aTagsNewLow=array();
foreach ($aTags as $sTag) {
$sTag=trim($sTag);
if (func_check($sTag,'text',2,50) and !in_array(mb_strtolower($sTag,'UTF-8'),$aTagsNewLow)) {
$aTagsNew[]=$sTag;
$aTagsNewLow[]=mb_strtolower($sTag,'UTF-8');
}
}
if (!count($aTagsNew)) {
$this->Message_AddError($this->Lang_Get('topic_create_tags_error_bad'),$this->Lang_Get('error'));
$bOk=false;
} else {
$_REQUEST['topic_tags']=join(',',$aTagsNew);
}
/**
* Выполнение хуков
*/

View file

@ -15,14 +15,61 @@
---------------------------------------------------------
*/
class ModuleTopic_EntityTopic extends Entity
{
class ModuleTopic_EntityTopic extends Entity {
/**
* Определяем правила валидации
*/
public function Init() {
parent::Init();
$this->aValidateRules[]=array('topic_title','string','max'=>200,'min'=>2,'allowEmpty'=>false,'label'=>$this->Lang_Get('topic_create_title'),'on'=>array('topic'));
$this->aValidateRules[]=array('topic_text_source','string','max'=>Config::Get('module.topic.max_length'),'min'=>2,'allowEmpty'=>false,'label'=>$this->Lang_Get('topic_create_text'),'on'=>array('topic'));
$this->aValidateRules[]=array('topic_tags','tags','count'=>15,'label'=>$this->Lang_Get('topic_create_tags'),'on'=>array('topic'));
$this->aValidateRules[]=array('blog_id','blog_id','on'=>array('topic'));
$this->aValidateRules[]=array('topic_text_source','topic_unique','on'=>array('topic'));
}
/**
* массив объектов(не всегда) для дополнительных типов топиков(линки, опросы, подкасты и т.п.)
*
* @var unknown_type
* @var array
*/
protected $aExtra=null;
/**
* Проверка топика на уникальность
*
* @param $sValue
* @param $aParams
* @return bool | string
*/
public function ValidateTopicUnique($sValue,$aParams) {
$this->setTextHash(md5($this->getType().$sValue.$this->getTitle()));
if ($oTopicEquivalent=$this->Topic_GetTopicUnique($this->getUserId(),$this->getTextHash())) {
if ($iId=$this->getTopicId() and $oTopicEquivalent->getId()==$iId) { // хак, запрашиваем не getId(), а getTopicId() - вернет null если это новый топик без ID
return true;
}
return $this->Lang_Get('topic_create_text_error_unique');
}
return true;
}
/**
* Валидация ID блога
*
* @param $sValue
* @param $aParams
* @return bool | string
*/
public function ValidateBlogId($sValue,$aParams) {
if ($sValue==0) {
return true; // персональный блог
}
if ($this->Blog_GetBlogById((string)$sValue)) {
return true;
}
return $this->Lang_Get('topic_create_blog_error_unknown');
}
public function getId() {
return $this->_aData['topic_id'];

View file

@ -181,5 +181,16 @@ abstract class ModuleValidate_EntityValidator extends Entity {
}
return null;
}
/**
* Устанавливает значение поля текущей сущности
*
* @param $sField
* @return mixed|null
*/
protected function setValueOfCurrentEntity($sField,$sValue) {
if ($this->oEntityCurrent) {
call_user_func_array(array($this->oEntityCurrent,'set'.func_camelize($sField)),array($sValue));
}
}
}
?>

View file

@ -37,6 +37,7 @@ class ModuleValidate_EntityValidatorCaptcha extends ModuleValidate_EntityValidat
* @return bool|string
*/
public function validate($sValue) {
$sValue=(string)$sValue;
if($this->allowEmpty && $this->isEmpty($sValue)) {
return true;
}

View file

@ -49,6 +49,7 @@ class ModuleValidate_EntityValidatorDate extends ModuleValidate_EntityValidator
* @return bool|string
*/
public function validate($sValue) {
$sValue=(string)$sValue;
if($this->allowEmpty && $this->isEmpty($sValue)) {
return true;
}

View file

@ -57,6 +57,7 @@ class ModuleValidate_EntityValidatorRegexp extends ModuleValidate_EntityValidato
* @return bool|string
*/
public function validate($sValue) {
$sValue=(string)$sValue;
if($this->allowEmpty && $this->isEmpty($sValue)) {
return true;
}

View file

@ -75,6 +75,7 @@ class ModuleValidate_EntityValidatorString extends ModuleValidate_EntityValidato
* @return bool|string
*/
public function validate($sValue) {
$sValue=(string)$sValue;
if($this->allowEmpty && $this->isEmpty($sValue)) {
return true;
}

View file

@ -0,0 +1,95 @@
<?php
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Валидатор тегов - строка с перечислением тегов
*/
class ModuleValidate_EntityValidatorTags extends ModuleValidate_EntityValidator {
/**
* Максимальня длина тега
*
* @var int
*/
public $max=50;
/**
* Минимальня длина тега
*
* @var int
*/
public $min=2;
/**
* Минимальное количество тегов
*
* @var int
*/
public $count=15;
/**
* Разделитель тегов
*
* @var string
*/
public $sep=',';
/**
* Допускать или нет пустое значение
*
* @var bool
*/
public $allowEmpty=false;
/**
* Запуск валидации
*
* @param $sValue Данные для валидации
*
* @return bool|string
*/
public function validate($sValue) {
$sValue=(string)$sValue;
if($this->allowEmpty && $this->isEmpty($sValue)) {
return true;
}
$aTags=explode($this->sep,trim($sValue,"\r\n\t\0\x0B ."));
$aTagsNew=array();
$aTagsNewLow=array();
foreach ($aTags as $sTag) {
$sTag=trim($sTag,"\r\n\t\0\x0B .");
$iLength=mb_strlen($sTag, 'UTF-8');
if ($iLength>=$this->min and $iLength<=$this->max and !in_array(mb_strtolower($sTag,'UTF-8'),$aTagsNewLow)) {
$aTagsNew[]=$sTag;
$aTagsNewLow[]=mb_strtolower($sTag,'UTF-8');
}
}
$iCount=count($aTagsNew);
if ($iCount>$this->count) {
return $this->getMessage($this->Lang_Get('validate_tags_count_more',null,false),'msg',array('count'=>$this->count));
} elseif (!$iCount) {
return $this->getMessage($this->Lang_Get('validate_tags_empty',null,false),'msg',array('min'=>$this->min,'max'=>$this->max));
}
/**
* Если проверка от сущности, то возвращаем обновленное значение
*/
if ($this->oEntityCurrent) {
$this->setValueOfCurrentEntity($this->sFieldCurrent,join($this->sep,$aTagsNew));
}
return true;
}
}
?>

View file

@ -941,6 +941,8 @@ return array(
'validate_compare_invalid_operator' => 'Field %%field%% invalid operator %%operator%%',
'validate_regexp_not_valid' => 'Field %%field%% is not valid',
'validate_regexp_invalid_pattern' => 'Field %%field%% invalid regular expression',
'validate_tags_count_more' => 'Field %%field%% contains too many tags (maximum is %%count%%)',
'validate_tags_empty' => 'Field %%field%% does not contain a tag, or has the wrong tag (size tag from %%min%% to %%max%% characters)',
/**
* Подписка
*/

View file

@ -941,6 +941,8 @@ return array(
'validate_compare_invalid_operator' => 'У поля %%field%% неверный оператор сравнения %%operator%%',
'validate_regexp_not_valid' => 'Поля %%field%% неверное',
'validate_regexp_invalid_pattern' => 'У поля %%field%% неверное регулярное выражение',
'validate_tags_count_more' => 'Поле %%field%% содержит слишком много тегов (максимально допустимо %%count%%)',
'validate_tags_empty' => 'Поле %%field%% не содержит тегов, либо содержит неверные теги (размер тега допустим от %%min%% до %%max%% символов)',
/**
* Подписка
*/