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

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

/*------------------------------------------------

	Все значение передаются в массиве:
	
	$NewsList = array(
		
		"template"		=> "Файл шаблона",
		"template_nav"	=> "Файл шаблона для навигации",
		"tpl_compile"	=> "Имя скомпилированного шаблона (очищается автоматически)",
		"template_info"	=> "Файл шаблона для вывода различной информации",
		"cashe_folder"	=> "Путь до папки с кэшем",
		"cashe_file"	=> "Имя файла",
		"cache"			=> true|false "Кэшировать или нет",
		"sql_count"		=> "Запрос для подсчёта новостей",
		"sql_query"		=> "Запрос для вывода новостей",
		"num"			=> "Максимум новостей на странице",
		"nav"			=> "Ссылка для навигации",
		"banners"		=> true,
		"no_news_error" => "Ошибка, если не найдено новостей",
		"backlight"		=> array(), // Массив, содержащий фразы, которые необходимо подсвечивать
		"ajaxlink"		=> "Запрос для аякс без ЧПУ", // Если пустая, то аякс не работает
		"search_info"	=> true|false "Выводить информацию, сколько новостей найдено",
		"search_text"	=> "", // текст для вывода информации о том, сколько нашлось объявлений
		"allow_edit"	=> false, // Если false, то нельзя редактировать
	);

-------------------------------------------------*/

$tpl->result[ $NewsList['tpl_compile'] ] = "";
if( $NewsList['cache'] ) $tpl->result[ $NewsList['tpl_compile'] ] = $Board->OpenCache( $NewsList['cashe_folder'], $NewsList['cashe_file'], intval( $_REQUEST['page'] ) );
if( !$tpl->result[ $NewsList['tpl_compile'] ] )
	{
		$temp = $db->super_query( $NewsList['sql_count'] );
		$posts = $temp['count'];
		
		if( $posts > 0 )
			{
				$num = $NewsList['num'] > 0 ? $NewsList['num'] : 1;
				$page = intval( $_REQUEST['page'] );
				$total = intval( ( ( $posts - 1 ) / $num ) + 1 );
				if( $page <= 0 ) $page = 1;
				if( $page > $total ) $page = $total;
				$start = $page * $num - $num;
				$limit = "LIMIT $start, $num";
				$NewsList['sql_query'] = str_replace( "{limit}", $limit, $NewsList['sql_query'] );
				
				//--------------------------------------------------
				//  Информация при поиске
				//--------------------------------------------------
				
				if( $NewsList['search_info'] === true )
					{
						if( !$NewsList['search_text'] )
							{
								$text = "По вашему запросу, найдено {$posts} объявлений на {$total} страницах.";
							}
								else
							{
								$text = str_replace( "{posts}", $posts, $NewsList['search_text'] );
								$text = str_replace( "{total}", $total, $text );
							}
							
						$tpl->Load_Template( $NewsList['template_info'] );
						$tpl->set( "{title}", "Информация" );
						$tpl->set( "{error}", $text );
						$tpl->compile( $NewsList['tpl_compile'] );
						$tpl->clear();
					}
				
				//--------------------------------------------------
				//  Вывод объявлений
				//--------------------------------------------------
				
				$i = 1;
				$result = $db->query( $NewsList['sql_query'] );
				$tpl->load_template( $NewsList['template'] );	
				while( $row = $db->get_row( $result ) )
					{
						$id = $row['id'];
						$author = stripslashes( $row['author'] );
						$author_id = stripslashes( $row['author_id'] );
						$date = strtotime( $row['date'] );
						$end_date = strtotime( $row['end_date'] );
						$text = stripslashes( $row['text'] );
						$title = htmlspecialchars( stripslashes( $row['title'] ) );
						$alt_name = stripslashes( $row['alt_name'] );
						$price = intval( $row['price'] );
						$currency = intval( $row['currency'] );
						$board_type = intval( $row['board_type'] );
						$country = intval( $row['country'] );
						$city = intval( $row['city'] );
						$category = intval( $row['category'] );
						$approve = intval( $row['approve'] );
						$fio = htmlspecialchars( stripslashes( $row['fio'] ) );
						$phone = htmlspecialchars( stripslashes( $row['phone'] ) );
						$email = htmlspecialchars( stripslashes( $row['email'] ) );
						$http = htmlspecialchars( stripslashes( $row['http'] ) );						
						$views = intval( $row['views'] );						
						$super_vip_date = intval( $row['super_vip_date'] );
						$vip_date = intval( $row['vip_date'] );
						$color = htmlspecialchars( stripslashes( $row['color'] ) );
						$color_date = intval( $row['color_date'] );
						$comm_num = intval( $row['comm_num'] );
						
						if( $Board->Config['short_echo_allowhtml'] != "yes" ) $text = strip_tags( $text, "<br>" );
						if( strlen( $text ) > $Board->Config['short_echo_max_strlen'] ) $text = substr( $text, 0, $Board->Config['short_echo_max_strlen'] )."..";
						
						if( $Board->Config['short_echo_city'] == "yes" ) $Board->LoadListCity( $country );
						
						$super_vip_date = $super_vip_date > 0 ? date( "Y-m-d H:i:s", ( $super_vip_date + ( $config['date_adjust'] * 60 ) ) ) : "";
						$vip_date = $vip_date > 0 ? date( "Y-m-d H:i:s", ( $vip_date + ( $config['date_adjust'] * 60 ) ) ) : "";
						$color_date = $color_date > 0 ? date( "Y-m-d H:i:s", ( $color_date + ( $config['date_adjust'] * 60 ) ) ) : "";
						
						$board_type = $Board->DB['board_type'][ $board_type ] != "" ? $Board->DB['board_type'][ $board_type ]['name'] : "---";
						$currency = $Board->DB['currency'][ $currency ] != "" ? $Board->DB['currency'][ $currency ]['symbol'] : "---";
						$city = $Board->DB['city'][ $country ][ $city ] != "" ? $city = $Board->DB['city'][ $country ][ $city ]['name'] : "---";
						$country = $Board->DB['country'][ $country ] != "" ? $Board->DB['country'][ $country ]['name'] : "---";
												
						// Подстветка указанных слов
						if( is_array( $NewsList['backlight'] ) && count( $NewsList['backlight'] ) > 0 )
							{
								$BackLightWord = implode( "|", $NewsList['backlight'] );
								
								$title = preg_replace( "'({$BackLightWord})'i", "<span style=\"background-color: yellow; color: #F00;\">\\1</span>", $title );
								foreach( $NewsList['backlight'] as $BackLightWord )
									{
										$short_story = preg_replace( "#((?:^|>)[^<]*)({$BackLightWord})#i", "<span style=\"background-color: yellow; color: #F00;\">\\2 </span>", $short_story );
									}
							}
						
						// Ссылка на автора объявления
						if( $config['allow_alt_url'] == "yes" )
							{
								$author_profile = "/user/{$author}/";
								$author_news = "/user/{$author}/news/";
							}
								else
							{
								$author_profile = "/index.php?subaction=userinfo&user={$author}";
								$author_news = "/index.php?subaction=allnews&user={$author}";
							}
		
						$author = "<a onclick=\"ShowProfile('{$author}', '{$author_profile}', '{$author_id}'); return false;\" href=\"{$author_profile}\">{$author}</a>";
		
						// Работаем с датой
						if( date( "Ymd", $date ) == date( "Ymd", $_TIME ) )
							$tpl->set( "{date}", $lang['time_heute'].langdate( ", H:i", $date ) );
						elseif( date( "Ymd", $date ) == date( "Ymd", ( $_TIME - 86400 ) ) )
							$tpl->set( "{date}", $lang['time_gestern'].langdate( ", H:i", $date ) );
						else
							$tpl->set( "{date}", langdate( $config['timestamp_comment'], $date ) );
							
						$tpl->copy_template = preg_replace ( "#\{date=(.+?)\}#ie", "langdate('\\1', '{$date}')", $tpl->copy_template );
		
						// Ссылка на редактирование объявления
						if( $config['allow_alt_url'] == "yes" )
							{
								$link_edit = "/board/edit/{$id}/";
								$link_del = "/board/del/{$id}/";
							}
								else
							{
								$link_edit = "/index.php?do=board&action=edit&id={$id}";
								$link_del = "/index.php?do=board&action=del&id={$id}";
							}
						
						$tpl->set( "{edit-link}", $link_edit );
						$tpl->set( "{del-link}", $link_del );
						
						$tpl->set( "{vip-link}", "javascript:void(0);\" onclick=\"BoardVip( '{$id}' ); return false;" );
						$tpl->set( "{color-link}", "javascript:void(0);\" onclick=\"BoardColor( '{$id}' ); return false;" );
						
						// Ссылка на объявление
						$full_link = $Board->ReturnLinkPost( $id, $alt_name, $category );
						$tpl->set( "{full-link}", $full_link );
						$tpl->set( "[full-link]", "<a href=\"{$full_link}\">" );
						$tpl->set( "[/full-link]", "</a>" );
		
						// Ссылка на комментарии
						if( $comm_num > 0 )
							{
								$tpl->set( "[com-link]", "<a href=\"{$full_link}#comment\">" );
								$tpl->set( "[/com-link]", "</a>");
							}
								else
							{
								$tpl->set( "[com-link]", "" );
								$tpl->set( "[/com-link]", "" );
							}
						
						if( $NewsList['tag_id'] === true )
							$tpl->set( "{id}", $id );
						else
							$tpl->set( "{id}", "" );
						
						$tpl->copy_template = preg_replace( "#\\[not-approve\\](.+?)\\[/not-approve\\]#is", ( $approve == 1 ? "" : "\\1" ), $tpl->copy_template );
						
						$tpl->copy_template = preg_replace( "#\\[super-vip\\](.+?)\\[/super-vip\\]#is", ( $super_vip_date ? "\\1" : "" ), $tpl->copy_template );
						$tpl->copy_template = preg_replace( "#\\[no-super-vip\\](.+?)\\[/no-super-vip\\]#is", ( $super_vip_date ? "" : "\\1" ), $tpl->copy_template );
						$tpl->copy_template = preg_replace( "#\\[vip\\](.+?)\\[/vip\\]#is", ( $vip_date ? "\\1" : "" ), $tpl->copy_template );
						$tpl->copy_template = preg_replace( "#\\[no-vip\\](.+?)\\[/no-vip\\]#is", ( $vip_date ? "" : "\\1" ), $tpl->copy_template );
						$tpl->copy_template = preg_replace( "#\\[color\\](.+?)\\[/color\\]#is", ( $color_date ? "\\1" : "" ), $tpl->copy_template );
						$tpl->copy_template = preg_replace( "#\\[no-color\\](.+?)\\[/no-color\\]#is", ( $color_date ? "" : "\\1" ), $tpl->copy_template );
						
						$tpl->copy_template = preg_replace( "#\\[allow-vip\\](.+?)\\[/allow-vip\\]#is", ( ( !in_array( $Board->Config['echo_post_vip'], array( "hand", "auto" ) ) && !in_array( $Board->Config['echo_post_supervip'], array( "hand", "auto" ) ) ) ? "" : "\\1" ), $tpl->copy_template );
						$tpl->copy_template = preg_replace( "#\\[allow-color\\](.+?)\\[/allow-color\\]#is", ( ( !in_array( $Board->Config['echo_post_color'], array( "hand", "auto" ) ) ) ? "" : "\\1" ), $tpl->copy_template );
						
						$tpl->set( "{color}", $color );
						
						$tpl->set( "{price}", $Board->ReplacePrice( $price ) );
						$tpl->set( "{notepad}", "{notepad-{$id}}" );
						$tpl->set( "{currency}", $currency );
						$tpl->set( "{board_type}", $board_type );
						$tpl->set( "{country}", $country );
						$tpl->set( "{city}", $city );
						$tpl->set( "{category}", $Board->ReturnLinkHrefCategory( $category ) );
						
						$tpl->set( "{fio}", $fio );
						$tpl->set( "{phone}", $phone );
						$tpl->set( "{email}", $email );
						$tpl->set( "{http}", $http );
						
						$tpl->set( "{title}", $title );
						$tpl->set( "{author}", $author );
						$tpl->set( "{views}", $views );
						$tpl->set( "{text}", $text );
						$tpl->set( "{comments-num}", $comm_num );
						$tpl->set( "[allow-edit]", "[allow-edit-{$id}-{$author_id}]" );
						
						$tpl->copy_template = $Board->ParsePhotosNews( $tpl->copy_template, $row['photos'] );
						if( $Board->Field !== false ) $tpl->copy_template = $Board->Field->ParseTags( $tpl->copy_template, $row['xfields'] );
						if( $NewsList['banners'] !== false ) $tpl->copy_template .= $Board->SetBanners( "short", $i );
						
						$tpl->compile( $NewsList['tpl_compile'] );
						$i++;
					}
				
				$tpl->clear();
				
				//--------------------------------------------------
				//  Навигация
				//--------------------------------------------------
				
				if( $NewsList['nav'] !== false ) $Board->CreateNavigation( $NewsList['nav'], $page, $total, $NewsList['template_nav'], $page_ajax, $NewsList['tpl_compile'] );
				
			}
				else
			{
				$tpl->Load_Template( $NewsList['template_info'] );
				$tpl->set( "{title}", "Информация" );
				$tpl->set( "{error}", $NewsList['no_news_error'] );
				$tpl->compile( $NewsList['tpl_compile'] );
				$tpl->clear();
			}
		
		if( $NewsList['cache'] && $Board->Config['cache'] == "yes" ) $Board->CreateCache( $NewsList['cashe_folder'], $NewsList['cashe_file'], $tpl->result[ $NewsList['tpl_compile'] ], intval( $_REQUEST['page'] ) );
	}
	
// Обновляем функцию блокнот
if( $is_logged )
	$tpl->result[ $NewsList['tpl_compile'] ] = preg_replace( "/{notepad-([0-9]+){1,10}}/ies", "\$Board->NotepadPost( '\\1' )", $tpl->result[ $NewsList['tpl_compile'] ] );
else
	$tpl->result[ $NewsList['tpl_compile'] ] = preg_replace( "/{notepad-([0-9]+){1,10}}/is", "", $tpl->result[ $NewsList['tpl_compile'] ] );
	
// Обновляем редактирование
if( $Board->AllowEditAllPost === true )
	{
		$tpl->result[ $NewsList['tpl_compile'] ] = preg_replace( "#\\[allow-edit-([0-9]+)-([0-9]+)\\](.+?)\\[/allow-edit\\]#is", "\\3", $tpl->result[ $NewsList['tpl_compile'] ] );
	}
		else
	{
		if( $is_logged && $Board->AllowEditPost( $member_id['user_id'], 1 ) )
			{
				$tpl->result[ $NewsList['tpl_compile'] ] = preg_replace( "#\\[allow-edit-([0-9]+)-{$member_id['user_id']}\\](.+?)\\[/allow-edit\\]#is", "\\2", $tpl->result[ $NewsList['tpl_compile'] ] );
			}
			
		$tpl->result[ $NewsList['tpl_compile'] ] = preg_replace( "#\\[allow-edit-([0-9]+)-([0-9]+)\\](.+?)\\[/allow-edit\\]#is", "", $tpl->result[ $NewsList['tpl_compile'] ] );
	}

?>