<?php
/*
=====================================================
 Модуль создал: REZER (http://rezer.net)
=====================================================
 Файл: add.post.php
=====================================================
 Данный код защищен авторскими правами
=====================================================
 Назначение: добавление объявления
=====================================================
*/

if( !defined( "DATALIFEENGINE" ) ) die( "Hacking attempt!" );

//--------------------------------------------------=-=-=-=-=
//	Проверка прав добавления
//--------------------------------------------------=-=-=-=-=

if( $Board->AllowAddPost() )
	{
		//--------------------------------------------------=-=-=-=-=
		//	Инициализируем категорию
		//--------------------------------------------------=-=-=-=-=
		
		if( $Board->DefinitionCat() )
			{		
				//--------------------------------------------------=-=-=-=-=
				//	Настройка метатитлов
				//--------------------------------------------------=-=-=-=-=
				
				$SpeedBarCat = $Board->SpeedBarCat( $Board->RequestCat );
				
				for( $i = count( $SpeedBarCat ); $i > 0; $i-- ) $module['title'][] = $SpeedBarCat[ ( $i - 1 ) ]['title'];
				for( $i = count( $SpeedBarCat ); $i > 0; $i-- ) $module['speedbar'][] = "<a href=\"".$SpeedBarCat[ ( $i - 1 ) ]['link']."\">".$SpeedBarCat[ ( $i - 1 ) ]['title']."</a>";
				
				//--------------------------------------------------=-=-=-=-=
				//	Смотрим, какую папку с шаблонами нам грузить
				//--------------------------------------------------=-=-=-=-=
				
				$RowCat = $Board->DB['category'][ $Board->RequestCat ];
				$Folder = $RowCat['template'] != "" ? totranslit( $RowCat['template'] ) : "default";
			}
				else
			{
				$Folder = "default";
			}
		
		$module['title'][] = "Добавление объявления";
		$module['speedbar'][] = "Добавление объявления";
				
		//--------------------------------------------------=-=-=-=-=
		//	Генерация формы
		//--------------------------------------------------=-=-=-=-=
				
		$AllowAddForm = true;
				
		if( $Board->Config['add_post_end_date'] != "" )
			{
				$MaxDays = array();
				$MaxDaysEx = explode( ",", $Board->Config['add_post_end_date'] );
				if( $Board->Config['add_post_no_end_date'] == "yes" && $Board->AllowAddPostNoDel === true ) $MaxDays['all'] = "Не ограниченно";
				foreach( $MaxDaysEx as $key => $value )
					{
						$value = intval( $value );
						if( $value > 0 )
							{
								$MaxDays[ $value ] = $value;
							}
					}
						
				unset( $MaxDaysEx );
			}
				else
			{
				$MaxDays = array( 1 => 1, 3 => 3, 7 => 7 );
			}
				
		//--------------------------------------------------=-=-=-=-=
		//	Проверка на ошибки и добавление в БД
		//--------------------------------------------------=-=-=-=-=
				
		if( isset( $_POST['submit_true'] ) )
			{
				$AddError = "";
				$category = intval( $_POST['category'] );
				$board_type = intval( $_POST['board_type'] );
				$currency = intval( $_POST['currency'] );
				$country = intval( $_POST['country'] );
				$city = intval( $_POST['city'] );
				$price = preg_replace( "/[^(0-9)\s]/i", "", $_POST['price'] );
				$max_days = in_array( $_POST['max_days'], $MaxDays ) ? intval( $_POST['max_days'] ) : 1;
				
				require_once( ENGINE_DIR."/classes/parse.class.php" );
				$parse = new ParseFilter( array(), array(), 1, 1 );
				
				if( $Board->Config['add_post_no_end_date'] == "all" )
					{
						$max_days = "all";
					}
						else
					{
						if( $Board->Config['add_post_no_end_date'] == "yes" && $_POST['max_days'] == "all" && $Board->AllowAddPostNoDel === true ) $max_days = "all";
						if( !$max_days ) $max_days = in_array( $_POST['max_days'], $MaxDays ) ? intval( $_POST['max_days'] ) : 1;
					}
						
				$title = $db->safesql( htmlspecialchars( stripslashes( $_POST['title'] ) ) );
				
				if( $Board->Config['add_post_bbcode'] == "yes" )
					{
						$text = $db->safesql( $parse->BB_Parse( $parse->process( strip_tags( $_POST['text'] ) ), false ) );
					}
						else
					{
						$text = htmlspecialchars( stripslashes( $_POST['text'] ) );
						$text = str_replace( "\r", "", $text );
						$text = str_replace( "\n", "<br />", $text );
						$text = $db->safesql( $text );
					}
						
				$fio = $db->safesql( htmlspecialchars( stripslashes( $_POST['fio'] ) ) );
				$email = $db->safesql( htmlspecialchars( stripslashes( $_POST['email'] ) ) );
				$http = $db->safesql( htmlspecialchars( stripslashes( $_POST['http'] ) ) );
				$phone = preg_replace( "/[^(0-9))(-\s]/i", "", $_REQUEST['phone'] ) ? $db->safesql( $_REQUEST['phone'] ) : "";	
				
				if( !$title ) $AddError .= "<li>Введите название объявления.</li>";
				if( !$fio && $Board->Config['add_post_fio'] == "yes" ) $AddError .= "<li>Введите ваше имя.</li>";
				
				if( $Board->Config['add_post_email'] == "yes" && empty( $email ) ) $AddError .= "<li>Email адрес введён не верно.</li>";
				if( !preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])'.'(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', $email ) && !empty( $email ) ) $AddError .= "<li>Email адрес введён не верно.</li>";
				
				if( !preg_match( "/^http:\/\/([-.a-z0-9]*)\.([a-z]{2,4})(\/?)*$/", $http ) ) $http = "";
				if( !$text ) $AddError .= "<li>Введите текст объявления.</li>";
				if( !$category ) $AddError .= "<li>Выберите категорию объявления.</li>";
				if( !$board_type || $Board->AllowTypeInCats( $board_type, $category ) !== true ) $AddError .= "<li>Выберите тип объявления.</li>";
				if( !$currency  && $Board->Config['add_post_price'] == "yes" ) $AddError .= "<li>Выберите валюту стоимости.</li>";
				if( !$price && $Board->Config['add_post_price'] == "yes" ) $AddError .= "<li>Введите стоимость.</li>";
				if( !$country && $Board->Config['region_on'] == "on" ) $AddError .= "<li>Выберите вашу страну.</li>";
				if( !$phone && $Board->Config['add_post_phone'] == "yes" ) $AddError .= "<li>Укажите телефон.</li>";
				if( $Board->Config['add_post_http'] != "yes" ) $http = "";
				
				if( $Board->AllowAddPostCaptcha )
					{
						if( $_REQUEST['sec_code'] != $_SESSION['sec_code_session'] || !$_SESSION['sec_code_session'] ) $AddError .= "<li>Введён не верный код безопастности!</li>";
					}
						
				if( $Board->Field !== false && empty( $AddError ) )
					{
						$xfields = $db->safesql( $Board->Field->SaveField( "add", "", $category ) );
						if( $Board->Field->ErrorSave ) $AddError .= $Board->Field->ErrorSave;
					}
						
				if( empty( $AddError ) )
					{
						if( $BoardAjax === true )
							{
								die( "<script language=\"language\" type=\"text/javascript\">document.forms.BoardPost.submit();</script>" );
							}
							
						$phone = $db->safesql( $phone );
						$author = $db->safesql( $member_id['name'] );
						$author_id = intval( $member_id['user_id'] );
						$alt_name = totranslit( $title );
						$added_time = time() + ( $config['date_adjust'] * 60 );
						$date = date( "Y-m-d H:i:s", $added_time );
						
						if( $max_days == "all" )
							{
								$end_date = $date;
								$no_del = 1;
							}	
								else
							{
								$end_date = date( "Y-m-d H:i:s", ( $added_time + ( 86400 * $max_days ) ) );
								$no_del = 0;
							}
								
						$Approve = 0;
						if( $Board->Config['add_post_moder'] == "yes" )
							{
								if( in_array( $member_id['user_group'], explode( ",", $Board->Config['post_groups_no_moder'] ) ) ) $Approve = 1;	
							}
								else
							{
								$Approve = 1;	
							}
							
						$images = $db->safesql( $Board->CompileImages() );
								
						$Board->AddPostCategory( $category );
						$db->query( "INSERT INTO ".PREFIX."_board_post (`title`,`alt_name`,`text`,`author`,`author_id`,`date`,`end_date`,`no_del`,`price`,`currency`,`board_type`,`country`,`city`,`category`,`allow_comm`,`xfields`,`fio`,`phone`,`email`,`http`,`photos`,`approve`) VALUES ('{$title}','{$alt_name}','{$text}','{$author}','{$author_id}','{$date}','{$end_date}','{$no_del}','{$price}','{$currency}','{$board_type}','{$country}','{$city}','{$category}','1','{$xfields}','{$fio}','{$phone}','{$email}','{$http}','{$images}','{$Approve}')" );
								
						$AllowAddForm = false;
						
						$id = $db->insert_id();
						$LinkPost = $Board->ReturnLinkPost( $id, $alt_name, $category );
						
						if( $Board->Config['add_post_admin_email'] == "yes" || ( $Board->Config['add_post_admin_email'] == "only_moder" && $Approve == 0 ) ) $Board->SendEmail( "send_admin_email", "Поступило новое объявление", "", $member_id['email'], array(
							"title"			=> $title,
							"link"			=> "http://".$_SERVER['HTTP_HOST']."/".$config['admin_path']."?mod=board",
							"moder-status"	=> ( $Approve == 1 ? "Опубликовано" : "Не опубликовано" ),
						) );
						
						if( in_array( "on_create", $Board->AllowSendEmail ) ) $Board->SendEmail( "send_create", "Объявление успешно добавлено", "", $member_id['email'], array(
							"title"			=> $title,
							"link"			=> "http://".$_SERVER['HTTP_HOST'].$LinkPost,
							"user"			=> stripslashes( $member_id['name'] ),
						) );
						
						$tpl->Load_Template( "board/{$Folder}/info.tpl" );
						$tpl->set( "{title}", "Информация" );
						$tpl->set( "{error}", "Спасибо, ваше объявление успешно добавлено, <a href=\"{$LinkPost}\">посмотреть его.</a>" );
						$tpl->compile( "board_content" );
						$tpl->clear();
					}
						else
					{
						if( $BoardAjax === true ) die( "<div class=\"BoardAddError\"><ol>{$AddError}</ol></div>" );
						$tpl->Load_Template( "board/{$Folder}/info.tpl" );
						$tpl->set( "{title}", "Ошибка" );
						$tpl->set( "{error}", "<ol>{$AddError}</ol>" );
						$tpl->compile( "board_content" );
						$tpl->clear();
					}
			}
				
		//--------------------------------------------------=-=-=-=-=
		//	Вывод формы добавления
		//--------------------------------------------------=-=-=-=-=
				
		if( $AllowAddForm === true )
			{
				$Board->LoadListCity( $_SESSION['BoardCountry'] );
				$SelectBoardType = $Board->ReturnSelectBoardType();
				$SelectCurrency = $Board->ReturnSelectCurrency();
				$SelectCountry = $Board->ReturnSelectCountry( $_SESSION['BoardCountry'] );
				$SelectCity = $Board->ReturnSelectCity( $_SESSION['BoardCountry'], $_SESSION['BoardCity'] );
				$MaxDays = $Board->SelectList( $MaxDays );
				$JSBoardType = $Board->JSType();
				
				if( $Board->Config['add_post_main_cat'] == "yes" )
					{
						$SelectCategory = $Board->SelectCategory( $Board->RequestCat );
						$SelectCategory = "<select name=\"category\" id=\"BoardSelectCategory\" onkeyup=\"CategorySelect();\" onkeydown=\"CategorySelect();\" onchange=\"CategorySelect();\">{$SelectCategory}</select>";
					}
						else
					{
						$SelectCategory = $Board->JSSelectCategory( $Board->RequestCat );
						$JSCategory = $SelectCategory['js'];
						$SelectCategory = $SelectCategory['main'];
					}
					
				if( $Board->Config['add_post_bbcode'] == "yes" ) include_once( ENGINE_DIR."/modules/board/editor/bb_news.php" );
				
				$tpl->Load_Template( "board/{$Folder}/add.tpl" );
				$tpl->set( "{bbcode}", $bb_code );
				$tpl->set( "{category}", $SelectCategory );
				$tpl->set( "{board_type}", "<span id=\"boardType\"><select name=\"board_type\" id=\"BoardTypeSelect\"><option value=\"\">---</option></select></span>" );
				$tpl->set( "{currency}", "<select name=\"currency\">{$SelectCurrency}</select>" );
				$tpl->set( "{country}", "<select name=\"country\" id=\"SelectListCountryAdd\" onchange=\"SelectCountry( 'Add', 'Выберите' );\"><option value=\"\">- Выберите -</option>{$SelectCountry}</select>" );
				$tpl->set( "{city}", "<span id=\"FormSelectCityAdd\"><select name=\"city\" id=\"SelectCityAdd\"><option value=\"\">- Выберите страну -</option>{$SelectCity}</select> <span id=\"FormSelectCityStatusAdd\"></span></span>" );
				$tpl->set( "{MaxDays}", "<select name=\"max_days\">{$MaxDays}</select>" );
				
				$tpl->set_block( "'\\[MaxDays\\](.*?)\\[/MaxDays\\]'si", ( $Board->Config['add_post_no_end_date'] == "all" ? "" : "\\1" ) );
				$tpl->set_block( "'\\[price\\](.*?)\\[/price\\]'si", ( $Board->Config['add_post_price'] == "not" ? "" : "\\1" ) );
				$tpl->set_block( "'\\[fio\\](.*?)\\[/fio\\]'si", ( $Board->Config['add_post_fio'] == "not" ? "" : "\\1" ) );
				$tpl->set_block( "'\\[phone\\](.*?)\\[/phone\\]'si", ( $Board->Config['add_post_phone'] == "not" ? "" : "\\1" ) );
				$tpl->set_block( "'\\[email\\](.*?)\\[/email\\]'si", ( $Board->Config['add_post_email'] == "not" ? "" : "\\1" ) );
				$tpl->set_block( "'\\[http\\](.*?)\\[/http\\]'si", ( $Board->Config['add_post_http'] == "no" ? "" : "\\1" ) );
				
				$tpl->copy_template = "<form name=\"BoardPost\" method=\"post\" enctype=\"multipart/form-data\" action=\"\" onsubmit=\"BoardformSubmit( 'BoardPost', 'add-post.php', 'statusBoardSubmit', '', 'statusBoardSubmit' ); return false;\">{$tpl->copy_template}</form>{$JSCategory}{$JSBoardType}";
				if( $Board->Field !== false )
					{
						$tpl->set( "{xfields}", $Board->Field->ShowForm( "add", @file_get_contents( TEMPLATE_DIR."/board/{$Folder}/xfields.tpl" ), "" ) );
						$CategoryJS = $Board->Field->ReturnCategoryJS();
						$tpl->copy_template = "{$tpl->copy_template}<script language=\"javascript\" type=\"text/javascript\">\n{$CategoryJS}\nBoardFieldsSetCategory();\n</script>";
					}
						
				if( $Board->AllowAddPostCaptcha )
					{
						$tpl->set( "{captcha}", "<span id=\"dle-captcha\"><img src=\"/engine/modules/antibot.php\" border=\"0\" width=\"120\" height=\"50\" onclick=\"BoardReCaptcha(); return false;\" style=\"cursor: pointer;\" /></span>" );
						$tpl->set( "[captcha]", "" );
						$tpl->set( "[/captcha]", "" );
					}
						else
					{
						$tpl->set_block( "'\\[captcha\\](.*?)\\[/captcha\\]'si", "" );
					}
					
				$tpl->set( "{Photos}", $Board->BoardNewsImages( "", file_get_contents( TEMPLATE_DIR."/board/main/add_photos/photo.list.tpl" ), file_get_contents( TEMPLATE_DIR."/board/main/add_photos/photo.tpl" ) ) );
						
				$tpl->compile( "board_content" );
				$tpl->clear();
			}
				
		// Разрешаем вывод формы поиска
		$BoardLoadMainTpl = true;
		$BoardAllowSearch = false;
		
//--------------------------------------------------=-=-=-=-=
//	В случае ошибки, выводим информацию
//--------------------------------------------------=-=-=-=-=

	}
		else
	{
		$module['title'][] = "Добавление объявления";
		$module['speedbar'][] = "Добавление объявления";
				
		$tpl->Load_Template( "info.tpl" );
		$tpl->set( "{title}", "Ошибка" );
		$tpl->set( "{error}", "Вы не можете добавлять объявления." );
		$tpl->compile( "board" );
		$tpl->clear();
	}

?>