Отключение активности поста блога при добавлении через postAdd

Материал из Umicms
Перейти к:навигация, поиск

Актуально для версии 2.9.1

Задача

Необходимо добавлять посты блога неактивными для возможности предварительной модерации.

Решение

Для добавления постов блога используется макрос postAdd, но там активность страницы не задается. Создадим кастомный метод postAddCustom где добавим передаваемый параметр в зависимости от которого будет переключатся активность создаваемой страницы. В конечном итоге файл \classes\modules\blogs20\__custom.php должен иметь следующее содержание:

<?php
abstract class __custom_blogs20 extends blogs20 {
	//TODO: Write here your own macroses
	public function postAddCustom($blogId = false, $template = 'default', $active = false) {
		if($blogId === false) {
			$iTmp = getRequest('param0');
			if($iTmp) $blogId = $iTmp;
			else      $blogId = getRequest('bid');
		}

		$blogId = intval($blogId);

		if($oUsers = cmsController::getInstance()->getModule('users')) {
			list($canRead, $canWrite) = permissionsCollection::getInstance()->isAllowedObject($oUsers->user_id, $blogId);
			if(!$oUsers->is_auth() || (!$canWrite && $blogId)) {
				return false;
			}
		} else {
			return false;
		}

		$sTitle   = htmlspecialchars(trim(getRequest('title')));
		$sContent = htmlspecialchars(trim(getRequest('content')));
		if(strlen($sTitle) && strlen($sContent) && $blogId) {
			if (!umiCaptcha::checkCaptcha()) {
				$this->errorNewMessage("%errors_wrong_captcha%");
				$this->errorPanic();
			}
			if(!($blog = umiHierarchy::getInstance()->getElement($blogId)) ||
				($blog->getTypeId() != umiHierarchyTypesCollection::getInstance()->getTypeByName("blogs20", "blog")->getId()) ) {
				$this->errorNewMessage('%error_wrong_parent%');
				$this->errorPanic();
			}
			$iFriendsOnly = getRequest('visible_for_friends') ? 1 : 0;
			$bActivity	  = getRequest('draught') ? false : true;
			$sTags 		  = getRequest('tags');
			$oHierarchy = umiHierarchy::getInstance();
			$hierarchy_type_id = umiHierarchyTypesCollection::getInstance()->getTypeByName("blogs20", "post")->getId();
			$iPostId = $oHierarchy->addElement($blogId, $hierarchy_type_id, $sTitle, $sTitle);
			permissionsCollection::getInstance()->setDefaultPermissions($iPostId);
			$oPost   = $oHierarchy->getElement($iPostId, true);
			
			if($active){
				if($bActivity) {
					$bActivity = antiSpamHelper::checkContent($sContent.$sTitle.$sTags);
				}
			}else{
				$bActivity = false;
			}
			
			$oPost->setIsActive($bActivity);
			$oPost->setValue('title', $sTitle);
			$oPost->setValue('content', $sContent);
			$oPost->setValue('tags', $sTags);
			$oPost->setValue('publish_time', new umiDate());
			$oPost->setValue('only_for_friends', $iFriendsOnly);
			// Raise Event
			$oEventPoint = new umiEventPoint("blogs20PostAdded");
			$oEventPoint->setMode("after");
			$oEventPoint->setParam("id", $iPostId);
			$oEventPoint->setParam('template', $template);
			$this->setEventPoint($oEventPoint);
			// Redirecting
			$sRefererUri = getServer('HTTP_REFERER');
			if(strlen($sRefererUri)) $this->redirect(str_replace("_err=","",$sRefererUri));
			return null;
		} else {
			if($blogId && !strlen($sTitle) && strlen($sContent)) {
				$this->errorNewMessage('Не заполнен заголовок');
			} else if($blogId && strlen($sTitle) && !strlen($sContent)) {
				$this->errorNewMessage('Не заполнен текст публикации');
			}
		}

		list($sFormTemplate) = self::loadTemplates('blogs20/'.$template, 'post_add_form');
		$aParams = array('action'  => '/blogs20/postAdd/'.$blogId.'/',
						 'id'	   => 'new',
						 'title'   => '',
						 'content' => '',
						 'tags'    => '',
						 'visible_for_friends' => '',
						 'blog_select' => $this->prepareBlogSelect($blogId, false, $template)
						 );
		return self::parseTemplate($sFormTemplate, $aParams);
	}
};
?>

теперь мы можем для добавления постов использовать макрос postAddCustom в котором будем передавать параметр активности страницы, выглядеть это должно примерно так:

<form name="frm_addblogmsg" method="post" action="/blogs20/postAddCustom/{$document-page-id}/notemplate/0"
onsubmit="site.forms.data.save(this); return site.forms.data.check(this);">
	<div class="form_element">
		<label class="required">
			<span><xsl:text>Ваше Имя:</xsl:text></span>
			<input type="text" name="title" class="textinputs" />
		</label>
	</div>
	<div class="form_element">
		<label class="required">
			<span><xsl:text>Сообщение:</xsl:text></span>
			<textarea name="content"></textarea>
		</label>
	</div>
	<div class="form_element">
	<label>
		<span><xsl:text>Тэги:</xsl:text></span>
		<input type="text" name="tags" class="textinputs" />
	</label>
	</div>
	<xsl:apply-templates select="document('udata://system/captcha')/udata[url]" />
	<div class="form_element">
		<input type="submit" class="button" value="Добавить сообщение" />
	</div>
</form>

в атрибуте action мы передаем ссылку на макрос где указываем последним параметром активность добавляемого поста, в данном случае мы передаем "0" поэтому добавленный пост будет неактивным и его перед выводом на сайте можно промодерировать в административной части сайта.