<?php

define('IN_PHPBB', true);
$phpbb_root_path = './';
include($phpbb_root_path . 'extension.inc');
include($phpbb_root_path . 'common.'.$phpEx);
include($phpbb_root_path . 'includes/functions_news.'.$phpEx);

error_reporting(0);
$this_file = basename(__FILE__);

if (!empty($board_config['index_announcement']))
{
	include($phpbb_root_path . 'includes/bbcode.'.$phpEx);
}

$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
$new_posts = mysql_result(mysql_query("SELECT COUNT(*) FROM `" . POSTS_TABLE . "` WHERE `post_time` >= '".$userdata['user_lastvisit']."'"),0);


$viewcat = ( !empty($HTTP_GET_VARS[POST_CAT_URL]) ) ? $HTTP_GET_VARS[POST_CAT_URL] : -1;

$verh = '';
$niz = '';

$sql = "SELECT * 
	FROM ".$table_prefix."shop_sites
	ORDER BY id ASC";
if( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, 'Could not query users', '', __LINE__, __FILE__, $sql);
}

if ( $row = $db->sql_fetchrow($result) )
{
	$i = 0;
	do
	{
		if ( $row['site_order'] )
		{
			if ( $row['site_time'] < time() )
			{
				$sqldel = "DELETE FROM ".$table_prefix."shop_sites WHERE id = " . $row['id'];
				$resultdel = $db->sql_query($sqldel);
			}
			else
			{
				$niz .= '<a href="http://' . $row['site_url'] . '">' . $row['site_desc'] . '</a><br/>';
			}
		}
		else
		{
			if ( $row['site_time'] < time() )
			{
				$sqldel = "DELETE FROM ".$table_prefix."shop_sites WHERE id = " . $row['id'];
				$resultdel = $db->sql_query($sqldel);
			}
			else
			{
				$verh .= '<a href="http://' . $row['site_url'] . '">' . $row['site_desc'] . '</a><br/>';
			}
		}

		$i++;
	}
	while ( $row = $db->sql_fetchrow($result) );
	$db->sql_freeresult($result);
}

$tracking_topics = ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_t']) ) ? unserialize($HTTP_COOKIE_VARS[$board_config['cookie_name'] . "_t"]) : array();
$tracking_forums = ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f']) ) ? unserialize($HTTP_COOKIE_VARS[$board_config['cookie_name'] . "_f"]) : array();

$total_posts = get_db_stat('postcount');
$total_users = get_db_stat('usercount');
$total_attach = get_db_stat('attachcount');
$newest_userdata = get_db_stat('newestuser');
$newest_user = $newest_userdata['username'];
$newest_uid = $newest_userdata['user_id'];
$CFG['news_forum'] = '43'; //ID форума
$CFG['number_of_news'] = '1'; //Кол-во выводимых новостей
$CFG['news_length'] = '600'; // длина выводимой новости в символах

$statistika = sprintf($lang['Posted_articles_total'], $total_posts)."<br/>\n".sprintf($lang['Attach_total'], $total_attach)."<br/>\n".sprintf($lang['Registered_users_total'], $total_users)."<br/>\n".sprintf($lang['Newest_user'], '<a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=$newest_uid") . '">', $newest_user, '</a>');


if( $total_posts == 0 )
{
$l_total_post_s = $lang['Posted_articles_zero_total'];
}
else if( $total_posts == 1 )
{
$l_total_post_s = $lang['Posted_article_total'];
}
else
{
$l_total_post_s = $lang['Posted_articles_total'];
}




$ban_information = session_userban($user_ip, $userdata['user_id']);
if ($ban_information)
{
	$ban = '<div style="border: 1px solid #d4d6d4;background:#ffffa0;color:#494949;margin-bottom:4px;border-radius:6px;padding:5px"><span style="color: red; font-weight: bold;">Внимание!</span><br/>Ваш '.$ban_information.'</div>';
}
else
{
	$ban = '';
}

$sql = "SELECT c.cat_id, c.cat_title, c.cat_order
	FROM " . CATEGORIES_TABLE . " c 
	ORDER BY c.cat_order";
if( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, 'Could not query categories list', '', __LINE__, __FILE__, $sql);
}

$category_rows = array();
while ($row = $db->sql_fetchrow($result))
{
	$category_rows[] = $row;
}
$db->sql_freeresult($result);
$total_categories = count($category_rows);

$sql = "SELECT f.*, p.post_time, p.post_username, u.username, u.user_id
	FROM (( " . FORUMS_TABLE . " f
	LEFT JOIN " . POSTS_TABLE . " p ON p.post_id = f.forum_last_post_id )
	LEFT JOIN " . USERS_TABLE . " u ON u.user_id = p.poster_id )
	ORDER BY f.cat_id, f.forum_order";
if ( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, 'Could not query forums information', '', __LINE__, __FILE__, $sql);
}

$forum_data = array();
while( $row = $db->sql_fetchrow($result) )
{
	$forum_data[] = $row;
}
$db->sql_freeresult($result);

$total_forums = count($forum_data);

if ($userdata['session_logged_in'])
{
	if ($userdata['user_lastvisit'] < (time() - 5184000))
	{
		$userdata['user_lastvisit'] = time() - 5184000;
	}

	$sql = "SELECT t.forum_id, t.topic_id, p.post_time 
		FROM " . TOPICS_TABLE . " t, " . POSTS_TABLE . " p 
		WHERE p.post_id = t.topic_last_post_id 
			AND p.post_time > " . $userdata['user_lastvisit'] . " 
			AND t.topic_moved_id = 0"; 
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, 'Could not query new topic information', '', __LINE__, __FILE__, $sql);
	}

	$new_topic_data = array();
	while( $topic_data = $db->sql_fetchrow($result) )
	{
		$new_topic_data[$topic_data['forum_id']][$topic_data['topic_id']] = $topic_data['post_time'];
	}
	$db->sql_freeresult($result);
}

$admin_link = ( $userdata['user_level'] == ADMIN ) ? '<a href="admin/index.' . $phpEx . '?sid=' . $userdata['session_id'] . '">' . $lang['Admin_panel'] . '</a><br />' : ((in_array($userdata['user_level'], explode(',', $board_config['modcp_levels_used']))) ? ' <a href="modcp/index.' . $phpEx . '?sid=' . $userdata['session_id'] . '">' . $lang['Mod_CP'] . '</a><br /><br />' : '');
$adminka = ( $userdata['user_level'] == ADMIN ) ? '<a href="/viewforum.php?f=38"class="row1"><img src="/themes/profmas/ind.png" alt="*"/> Админ-форум +24</a></div>' : ((in_array($userdata['user_level'], explode(',', $board_config['modcp_levels_used']))) ? ' <a href="/viewforum.php?f=38"></a>' : '');
$adminka2 = ( $userdata['user_level'] == MOD ) ? '<a href="/viewforum.php?f=38"class="row1"><img src="/themes/profmas/ind.png" alt="*"/> Модер-форум +12</a></div>' : ((in_array($userdata['user_level'], explode(',', $board_config['modcp_levels_used']))) ? ' <a href="/viewforum.php?f=38"></a><br />' : '');


$is_auth_ary = array();
$is_auth_ary = auth(AUTH_VIEW, AUTH_LIST_ALL, $userdata, $forum_data);

$sql = ($board_config['birthday_check_day']) ? "SELECT user_id, username, user_birthday,user_level FROM " . USERS_TABLE. " WHERE user_birthday!=999999 ORDER BY username" :"";
if($result = $db->sql_query($sql)) 
{ 
	if (!empty($result)) 
	{ 
		$time_now = time();
		$this_year = create_date('Y', $time_now, $board_config['board_timezone']);
		$date_today = create_date('Ymd', $time_now, $board_config['board_timezone']);
		$date_forward = create_date('Ymd', $time_now+($board_config['birthday_check_day']*86400), $board_config['board_timezone']);
		while ($birthdayrow = $db->sql_fetchrow($result))
		{ 
			$user_birthday2 = $this_year.($user_birthday = realdate("md",$birthdayrow['user_birthday'] )); 
			if ( $user_birthday2 < $date_today ) $user_birthday2 += 10000;
			if ( $user_birthday2 > $date_today  && $user_birthday2 <= $date_forward ) 
			{ 
				$user_age = ( $this_year.$user_birthday < $date_today ) ? $this_year - realdate ('Y',$birthdayrow['user_birthday'])+1 : $this_year- realdate ('Y',$birthdayrow['user_birthday']); 
				switch ($birthdayrow['user_level'])
				{
					case ADMIN :
		      			$birthdayrow['username'] = $birthdayrow['username']; 
      					$style_color = 'style="color:#ffcc00"';
						break;
					case MOD :
		      			$birthdayrow['username'] = $birthdayrow['username']; 
      					$style_color = 'style="color:#943043"';
						break;
					default: $style_color = '';
				}
				$birthday_week_list .= ' <a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $birthdayrow['user_id']) . '"' . $style_color .'>' . $birthdayrow['username'] . ' ('.$user_age.')</a>,'; 

			} else if ( $user_birthday2 == $date_today ) { 

				$user_age = $this_year - realdate ( 'Y',$birthdayrow['user_birthday'] ); 
				switch ($birthdayrow['user_level'])
				{
					case ADMIN :
		      			$birthdayrow['username'] = $birthdayrow['username']; 
      					$style_color = 'style="color:#ffcc00"';
						break;
					case MOD :
			      		$birthdayrow['username'] = $birthdayrow['username']; 
      					$style_color = 'style="color:#943043"';
						break;
					default: $style_color = '';
				}

				$birthday_today_list .= ' <a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $birthdayrow['user_id']) . '"' . $style_color .'>' . $birthdayrow['username'] . ' ('.$user_age.')</a>,'; 
			}
			 
		}
		if ($birthday_today_list) $birthday_today_list[ strlen( $birthday_today_list)-1] = ' ';
		if ($birthday_week_list) $birthday_week_list[ strlen( $birthday_week_list)-1] = ' ';
	} 
	$db->sql_freeresult($result);
}

define('SHOW_ONLINE', true);
$page_title = $lang['Index'];
include($phpbb_root_path . 'includes/page_header.'.$phpEx);

$template->set_filenames(array(
	'body' => 'index_body.tpl')
);
$time = time();
$lastnews = mysql_result(mysql_query( 'SELECT COUNT(topic_id) FROM phpbb_topics 
WHERE forum_id = '.$CFG['news_forum'].'
AND topic_time >= '.($time-( 86400 ))),0);
if ((int)$lastnews[0] == 0 )
{	
 $lastnews = '';
}else{	
 $lastnews = '/+'.(int)$lastnews[0];
};
$news = mysql_result(mysql_query( 'SELECT COUNT(topic_id) FROM phpbb_topics 
WHERE forum_id = '.$CFG['news_forum']),0);

$read_only = read_only();
//Считаем кол-во новых файлов с момента последнего посещения 
// 
if( $userdata['session_logged_in'] ) 
{ 
$sql = "SELECT COUNT(attach_id) as total 
FROM " . ATTACHMENTS_DESC_TABLE . " 
WHERE filetime >= " . $userdata['user_lastvisit'] . ""; 
$result = $db->sql_query($sql); 
if( $result ) 
{ 
$row = $db->sql_fetchrow($result); 
$number_new_files = $row['total']; 
} 
} 
// Выводим последние 3 файла из обменника на главную

include($phpbb_root_path . 'includes/functions_obmen.'.$phpEx);

$sql = "SELECT*FROM `" . UPLOAD_FILES_TABLE . "` ORDER BY `file_time` DESC LIMIT 3";

if ( !($result = $db->sql_query($sql)) )

	{
	
	message_die(GENERAL_ERROR, 'Could not get upload_files information', '', __LINE__, __FILE__, $sql);

	}


while ($file = $db->sql_fetchrow($result))

	{


        $ext = ext_file($file['file_url']);

        $file_link = append_sid("obmen.$phpEx?mod=file&amp;id=".$file['file_id']);

        $file_name = text_obmen($file['file_name']);

        $file_size = fsize($file['file_size']);

        $file_text = mb_substr(text_obmen($file['file_text']), 0, 60);

    
$template->assign_block_vars('file_row', array(

                'FILE_LINK' => $file_link,

		'FILE_NAME' => $file_name,

		'FILE_SIZE' => $file_size,

		'FILE_TEXT' => $file_text

    ));
        }

//end
$result = mysql_query("SELECT count(file_id) AS total FROM " . phpbb_upload_files);

$total_files = mysql_fetch_array($result);

$total_files = $total_files['total'];

$template->assign_vars(array(
         'TOTAL_POSTS' => sprintf($l_total_post_s, $total_posts),
         'TOTAL_FILES' => $total_files,
         'ALLNEWS' => '('.$news.$lastnews.')',
         'LASTFILES' => $number_new_files,
	'STATISTIKA' => $statistika,
         'READ_ONLY' => $read_only,
	'L_WHOSBIRTHDAY_WEEK' => ($board_config['birthday_check_day'] > 1) ? sprintf( (($birthday_week_list) ? $lang['Birthday_week'] : $lang['Nobirthday_week']), $board_config['birthday_check_day']).$birthday_week_list : '',
	'L_WHOSBIRTHDAY_TODAY' => ($board_config['birthday_check_day']) ? ($birthday_today_list) ? $lang['Birthday_today'].$birthday_today_list : $lang['Nobirthday_today'] : '',
	'ADMIN_LINK' => $admin_link,
        'ADMINKA' => $adminka,
        
        'ADMINKA2' => $adminka2,
	'VERH' => $verh,
	'NIZ' => $niz,
        'NEW_POSTS' => $new_posts,
        'TOTALDL' => $totaldl,
	'BAN_INFO' => $ban)
);

if(!isset($HTTP_GET_VARS['news_id']))
{
	$template->assign_block_vars('welcome_text', array());

	$fetchposts = phpbb_fetch_posts($CFG['news_forum'], $CFG['number_of_news'], $CFG['news_length']);

	for ($i = 0; $i < count($fetchposts); $i++)
	{
		if( $fetchposts[$i]['striped'] == 1 )
		{
			$open_bracket = '';
			$close_bracket = '';
			$read_full = '&raquo;';
		}
		else
		{
			$open_bracket = '';
			$close_bracket = '';
			$read_full = '';
		}

		$template->assign_block_vars('fetchpost_row', array(
			'TITLE' => $fetchposts[$i]['topic_title'],
			'POSTER' => $fetchposts[$i]['username'],
			'TIME' => $fetchposts[$i]['topic_time'],
			'TEXT' => $fetchposts[$i]['post_text'],
			'REPLIES' => $fetchposts[$i]['topic_replies'],
			'U_VIEW_COMMENTS' => append_sid('viewtopic.' . $phpEx . '?t=' . $fetchposts[$i]['topic_id']),
			'U_POST_COMMENT' => append_sid('posting.' . $phpEx . '?mode=reply&amp;t=' . $fetchposts[$i]['topic_id']),
			'U_READ_FULL' => append_sid('index.' . $phpEx . '?news_id=' . $i),
			'L_READ_FULL' => $read_full,
			'OPEN' => $open_bracket,
			'CLOSE' => $close_bracket)
		);
	}
}
else
{
	$template->set_filenames(array(
	'body' => 'fullnews_body.tpl')
);
	$fetchposts = phpbb_fetch_posts($CFG['news_forum'], $CFG['number_of_news'], 0);

	$i = intval($HTTP_GET_VARS['news_id']);
$sql = "UPDATE " . TOPICS_TABLE . "
					SET topic_views = topic_views + 1
					WHERE topic_id = ".$fetchposts[$i]['topic_id'];
			if ( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "Could not update topic views.", '', __LINE__, __FILE__, $sql);
		}

	$template->assign_block_vars('fetchpost_row', array(
		'TITLE' => $fetchposts[$i]['topic_title'],
		'VIEWS' => $fetchposts[$i]['topic_views'],
		'POSTER' => $fetchposts[$i]['username'],
		'TIME' => $fetchposts[$i]['topic_time'],
		'TEXT' => $fetchposts[$i]['post_text'],
		'REPLIES' => $fetchposts[$i]['topic_replies'],
		'U_VIEW_COMMENTS' => append_sid('viewtopic.' . $phpEx . '?t=' . $fetchposts[$i]['topic_id']),
		'U_POST_COMMENT' => append_sid('posting.' . $phpEx . '?mode=reply&amp;t=' . $fetchposts[$i]['topic_id'])
		)
	);
}
if (!empty($board_config['index_announcement']))
{
	$announcement = smilies_pass($board_config['index_announcement']);
	$announcement = str_replace("\n", "\n<br/>\n", $announcement);

	$template->assign_block_vars('announcement', array(
		'ANNOUNCEMENT' => $announcement)
	);
}

$display_categories = array();

for ($i = 0; $i < $total_forums; $i++ )
{
	if ($is_auth_ary[$forum_data[$i]['forum_id']]['auth_view'])
	{
		$display_categories[$forum_data[$i]['cat_id']] = true;
	}
}

for($i = 0; $i < $total_categories; $i++)
{
	$cat_id = $category_rows[$i]['cat_id'];

	if (isset($display_categories[$cat_id]) && $display_categories[$cat_id])
	{
		$template->assign_block_vars('catrow', array(
			'CAT_DESC' => $category_rows[$i]['cat_title'],
			'U_VIEWCAT' => append_sid("index.$phpEx?" . POST_CAT_URL . "=$cat_id"))
		);

		if ( $viewcat == $cat_id || $viewcat == -1 )
		{
			for($j = 0; $j < $total_forums; $j++)
			{
				if ( $forum_data[$j]['cat_id'] == $cat_id )
				{
					$forum_id = $forum_data[$j]['forum_id'];

					if ( $is_auth_ary[$forum_id]['auth_view'] )
					{
						$posts = $forum_data[$j]['forum_posts'];

						$template->assign_block_vars('catrow.forumrow',	array(
							'FORUM_NAME' => $forum_data[$j]['forum_name'],
							'POSTS' => $forum_data[$j]['forum_posts'],
							'TOPICS' => $forum_data[$j]['forum_topics'],
							'U_VIEWFORUM' => append_sid("viewforum.$phpEx?" . POST_FORUM_URL . "=$forum_id"))
						);
					}
				}
			}
		}
	}
}
$cfg_ignore_forums = '38'; 	// id форумов которые будут фильтроваться
$cfg_nm_topics = 5;// кол-во тем для вывода
$cfg_max_topic_length = 75; // длина названия темы

$orig_word = array();
$replacement_word = array();
obtain_word_list($orig_word, $replacement_word);


$server_protocol = ($board_config['cookie_secure']) ? 'https://' : 'http://';
$server_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($board_config['server_name']));
$server_port = ($board_config['server_port'] <> 80) ? ':' . trim($board_config['server_port']) : '';
$script_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($board_config['script_path']));
$script_name = ($script_name == '') ? $script_name : '/' . $script_name;
$board_path = $server_protocol . $server_name . $server_port . $script_name;
$viewtopic_url = $board_path . '/viewtopic.' . $phpEx;
// Fetching topics of public forums
$sql = "SELECT t.topic_id, t.topic_title, t.topic_last_post_id, t.topic_replies, t.topic_replies
	FROM " . TOPICS_TABLE . " AS t, " . POSTS_TABLE . " AS p, " . FORUMS_TABLE . " AS f
	WHERE t.forum_id = f.forum_id
		AND f.auth_read = " . AUTH_ALL . "
		AND t.forum_id NOT IN(" . $cfg_ignore_forums .")
		AND p.post_id = t.topic_last_post_id
		AND t.topic_moved_id = 0
	ORDER BY p.post_time DESC LIMIT $cfg_nm_topics";

if ( !$result = $db->sql_query($sql) )
{
	message_die(GENERAL_ERROR, "Could not fetch recent topics information.", '', __LINE__, __FILE__, $sql);
}

while ( $row = $db->sql_fetchrow($result) )
{
	$full_topic_title = $topic_title = $row['topic_title'];
	if ( count($orig_word) )

	$topic_title = ( strlen($topic_title) > $cfg_max_topic_length ) ? substr($topic_title, 0, $cfg_max_topic_length) . '&hellip;' : $topic_title;
	$poster = ( $searchset[$i]['user_id'] != ANONYMOUS ) ? '<a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . 	$searchset[$i]['user_id']) . '">' : '';
	$poster .= ( $searchset[$i]['user_id'] != ANONYMOUS ) ? $searchset[$i]['username'] : ( ( $searchset[$i]['post_username'] != "" ) ? $searchset[$i]['post_username'] : $lang['Guest'] );
	$poster .= ( $searchset[$i]['user_id'] != ANONYMOUS ) ? '</a>' : '';
        $replies = $row['topic_replies'];
		$template->assign_block_vars('topicrow', array(
		'BOARD_PATH' => $board_path,
                 'REPLIES' => $replies,
		'U_LAST_POST' => $viewtopic_url . '?' . POST_POST_URL . '=' . $row['topic_last_post_id'] . '#' . $row['topic_last_post_id'],
		'TOPIC_REPLIES' => $row['topic_replies'],
		'FULL_TOPIC_TITLE' => str_replace("'", "\'", $full_topic_title),
		'U_TOPIC' => $viewtopic_url . '?' . POST_TOPIC_URL . '=' . $row['topic_id'],
		'TOPIC_TITLE' => str_replace("'", "\'", $topic_title))
		);
	}

$template->pparse('body');

include($phpbb_root_path . 'includes/page_tail.'.$phpEx);

?>