<?php
/*
=====================================================
 DataLife Engine - by SoftNews Media Group 
-----------------------------------------------------
 https://dle-news.ru/
-----------------------------------------------------
 Copyright (c) 2004-2025 SoftNews Media Group
=====================================================
 This code is protected by copyright
=====================================================
 File: main.php
=====================================================
*/

if( !defined('DATALIFEENGINE') ) {
	header( "HTTP/1.1 403 Forbidden" );
	header ( 'Location: ../../' );
	die( "Hacking attempt!" );
}

$home_url = clean_url($config['http_home_url']);

if ($home_url AND clean_url( $_SERVER['HTTP_HOST'] ) != $home_url ) {

	$replace_url = array ();
	$replace_url[0] = $home_url;
	$replace_url[1] = clean_url ( $_SERVER['HTTP_HOST'] );

} else $replace_url = false;

$tpl->load_template ( 'main.tpl' );

$tpl->set ( '{calendar}', isset($tpl->result['calendar']) ? $tpl->result['calendar'] : '' );
$tpl->set ( '{archives}', isset($tpl->result['archive']) ? $tpl->result['archive'] : '' );
$tpl->set ( '{tags}', isset($tpl->result['tags_cloud']) ? $tpl->result['tags_cloud'] : '' );
$tpl->set ( '{vote}', isset($tpl->result['vote']) ? $tpl->result['vote'] : '' );
$tpl->set ( '{login}', isset($tpl->result['login_panel']) ? $tpl->result['login_panel'] : '' );
$tpl->set ( '{speedbar}', isset($tpl->result['speedbar']) ? $tpl->result['speedbar'] : '' );

// PWA/SW disabled: keep placeholders empty (avoid leaking {pwa-head}/{pwa-body} into HTML)
$tpl->set('{pwa-head}', '');
$tpl->set('{pwa-body}', '');

// Footer website counter (unique/day, all-time, online) - only if template uses it
$need_sitecounter = (
	stripos($tpl->copy_template, '{sitecounter-') !== false
	|| stripos($tpl->copy_template, 'footer__counter') !== false
);

if ( $need_sitecounter ) {
	include_once (DLEPlugins::Check(ENGINE_DIR . '/modules/sitecounter.php'));
	if (function_exists('mt_sitecounter_set_template_vars')) {
		mt_sitecounter_set_template_vars($tpl);
	}
}

// Home: Top 50 artists blocks (same markup as /index.php?do=artists)
$need_home_top_artists = (
	$dle_module == 'main'
	AND (
		stripos($tpl->copy_template, '{home_top_artists_1}') !== false
		OR stripos($tpl->copy_template, '{home_top_artists_2}') !== false
	)
);

if ( $need_home_top_artists ) {

	$tpl->set('{home_top_artists_1}', '');
	$tpl->set('{home_top_artists_2}', '');

	$allow_cache_original = $config['allow_cache'];
	if ( !$config['allow_cache'] ) {
		$config['allow_cache'] = 1;
	}

	$cache_key = $config['skin'];
	$cached = dle_cache('artists_index', $cache_key);
	$artists_items = array();

	if ( $cached !== false ) {
		$artists_items = json_decode($cached, true);
		if (json_last_error() !== JSON_ERROR_NONE || !is_array($artists_items)) {
			$artists_items = array();
		}
	}

	if ( !count($artists_items) ) {
		$artists_display = array();
		$artists_counts = array();
		$need_fallback_counts = false;

		$normalize_artist_key = function($name) {
			$name = trim(preg_replace('/\s+/u', ' ', (string)$name));
			if ($name === '') return '';
			return function_exists('dle_strtolower') ? dle_strtolower($name) : mb_strtolower($name, 'UTF-8');
		};

		$split_artists = function($val) {
			$val = trim((string)$val);
			if ($val === '') return array();

			$parts = preg_split('/\s*(?:,|;|&|\\/|\\+|\s+and\s+|\s+feat\\.?\s+|\s+ft\\.?\s+|\s+featuring\s+)\s*/iu', $val, -1, PREG_SPLIT_NO_EMPTY);
			if (!is_array($parts) || !count($parts)) $parts = array($val);

			$out = array();
			foreach ($parts as $p) {
				$p = trim(preg_replace('/\s+/u', ' ', (string)$p));
				if ($p !== '') $out[] = $p;
			}
			return $out;
		};

		$has_multi_artist_separators = function($val) {
			return (bool)preg_match('/(?:,|;|&|\\/|\\+|\s+and\s+|\s+feat\\.?\s+|\s+ft\\.?\s+|\s+featuring\s+)/iu', (string)$val);
		};

		// Respect date limitation like engine.php
		$thisdate = date("Y-m-d H:i:s", time());
		if ($config['no_date'] AND !$config['news_future']) {
			$where_date = " AND p.date < '" . $thisdate . "'";
		} else {
			$where_date = "";
		}

		// Respect category permissions
		$allow_list = explode(',', $user_group[$member_id['user_group']]['allow_cats']);
		$not_allow_cats = explode(',', $user_group[$member_id['user_group']]['not_allow_cats']);
		$stop_list = "";
		$cat_join = "";

		if (!$user_group[$member_id['user_group']]['allow_short']) {
			if ($allow_list[0] != "all") {
				if ($config['allow_multi_category']) {
					$cat_join = "INNER JOIN (SELECT DISTINCT " . PREFIX . "_post_extras_cats.news_id FROM " . PREFIX . "_post_extras_cats WHERE cat_id IN (" . implode(',', $allow_list) . ")) c ON (p.id=c.news_id) ";
				} else {
					$stop_list = "p.category IN ('" . implode("','", $allow_list) . "') AND ";
				}
			}

			if ($not_allow_cats[0]) {
				if ($config['allow_multi_category']) {
					$stop_list = "p.id NOT IN ( SELECT DISTINCT(" . PREFIX . "_post_extras_cats.news_id) FROM " . PREFIX . "_post_extras_cats WHERE cat_id IN (" . implode(',', $not_allow_cats) . ") ) AND ";
					$cat_join = "";
				} else {
					$stop_list = "p.category NOT IN ('" . implode("','", $not_allow_cats) . "') AND ";
				}
			}
		}

		// Preferred: aggregated counts from xfsearch (fast)
		$db->query(
			"SELECT xf.tagvalue, COUNT(DISTINCT xf.news_id) as cnt " .
			"FROM " . PREFIX . "_xfsearch xf " .
			"INNER JOIN " . PREFIX . "_post p ON (p.id=xf.news_id) " .
			$cat_join .
			"WHERE {$stop_list}p.approve=1 AND xf.tagname='artistsong' AND xf.tagvalue<>''" .
			$where_date .
			" GROUP BY xf.tagvalue"
		);

		while ($row = $db->get_row()) {
			$val = trim((string)$row['tagvalue']);
			if ($val === '') continue;

			$cnt = (int)$row['cnt'];
			if ($cnt < 1) $cnt = 1;

			// If xfsearch stores multi-artist strings, counts will be wrong; fall back.
			if ($has_multi_artist_separators($val)) {
				$need_fallback_counts = true;
				foreach ($split_artists($val) as $p) {
					$key = $normalize_artist_key($p);
					if ($key === '') continue;
					if (!isset($artists_display[$key])) $artists_display[$key] = $p;
				}
				continue;
			}

			$key = $normalize_artist_key($val);
			if ($key === '') continue;
			if (!isset($artists_display[$key])) $artists_display[$key] = $val;
			if (!isset($artists_counts[$key])) $artists_counts[$key] = 0;
			$artists_counts[$key] += $cnt;
		}
		$db->free();

		// Fallback: scan xfields and split artists correctly (accurate)
		if (!count($artists_counts) OR $need_fallback_counts) {
			DLEXFields::Init();
			$artists_display = array();
			$artists_counts = array();

			$db->query(
				"SELECT p.id, p.xfields FROM " . PREFIX . "_post p " .
				$cat_join .
				"WHERE {$stop_list}p.approve=1 AND p.xfields<>'' AND p.xfields LIKE '%artistsong|%'" .
				$where_date
			);
			while ($row = $db->get_row()) {
				$xfieldsdata = DLEXFields::xfieldsdataload($row['xfields']);
				if (!isset($xfieldsdata['artistsong']) OR $xfieldsdata['artistsong'] === '') continue;
				$val = trim((string)$xfieldsdata['artistsong']);
				if ($val === '') continue;

				$per_post = array();
				foreach ($split_artists($val) as $p) {
					$key = $normalize_artist_key($p);
					if ($key === '') continue;
					$per_post[$key] = $p;
				}

				if (!count($per_post)) continue;

				foreach ($per_post as $key => $display) {
					if (!isset($artists_display[$key])) $artists_display[$key] = $display;
					if (!isset($artists_counts[$key])) $artists_counts[$key] = 0;
					$artists_counts[$key] += 1;
				}
			}
			$db->free();
		}

		foreach ($artists_display as $key => $display) {
			$artists_items[] = array(
				'name' => $display,
				'count' => isset($artists_counts[$key]) ? (int)$artists_counts[$key] : 0,
			);
		}

		usort($artists_items, function($a, $b) {
			$ac = isset($a['count']) ? (int)$a['count'] : 0;
			$bc = isset($b['count']) ? (int)$b['count'] : 0;
			if ($ac !== $bc) return ($bc <=> $ac);
			return strnatcasecmp((string)($a['name'] ?? ''), (string)($b['name'] ?? ''));
		});

		// Do not persist empty cache: it blocks the list after new content appears.
		if (count($artists_items)) {
			create_cache('artists_index', json_encode($artists_items, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), $cache_key);
		}
	}

	$config['allow_cache'] = $allow_cache_original;

	$home_top_artists_total = 20;
	$top = array_slice($artists_items, 0, $home_top_artists_total);
	$first = $top;
	$second = array();

	$render_list_items = function($items) use ($config) {
		if (!is_array($items) || !count($items)) {
			return '<li class="artists-item artists-item--empty">No artists found yet.</li>';
		}

		$html = '';
		foreach ($items as $item) {
			$name = isset($item['name']) ? (string)$item['name'] : '';
			$count = isset($item['count']) ? (int)$item['count'] : 0;
			if ($name === '') continue;
			if ($count < 0) $count = 0;

			$href = $config['http_home_url'] . 'index.php?do=artists&name=' . urlencode($name);
			$html .= '<li><a class="artists-item" href="' . $href . '"><span class="artists-item__name">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</span><span class="artists-item__count">' . $count . ' tracks</span></a></li>';
		}
		return $html;
	};

	$tpl->set('{home_top_artists_1}', $render_list_items($first));
	$tpl->set('{home_top_artists_2}', '');
}

if ( $dle_module == "showfull" AND $news_found ) {

	if( $config['related_news'] AND RELATED_IDS AND strpos( $tpl->copy_template, "related-news" ) !== false ) {
		
		if( !is_string($related_buffer) ) {
			include_once(DLEPlugins::Check(ENGINE_DIR . '/modules/show.related.php'));
		}
		
		if ($related_buffer) {
			$tpl->set('[related-news]', "");
			$tpl->set('[/related-news]', "");
		} else $tpl->set_block("'\\[related-news\\](.*?)\\[/related-news\\]'si", "");

		$tpl->set('{related-news}', $related_buffer);

	} else {

		$tpl->set('{related-news}', '');
		$tpl->set_block("'\\[related-news\\](.*?)\\[/related-news\\]'si", "");
	}

	if( strpos( $tpl->copy_template, "[xf" ) !== false OR strpos( $tpl->copy_template, "[ifxf" ) !== false ) {

		$full = ['id' => 'main', 'xfields' => $xfieldsdata];
		DLEXFields::Compile($full, $tpl);

		if (stripos ( $tpl->copy_template, "[hide" ) !== false ) {
			
			$tpl->copy_template = preg_replace_callback ( "#\[hide(.*?)\](.+?)\[/hide\]#is", 
				function ($matches) use ($member_id, $user_group, $lang) {
					
					$matches[1] = str_replace(array("=", " "), "", $matches[1]);
					$matches[2] = $matches[2];
	
					if( $matches[1] ) {
						
						$groups = explode( ',', $matches[1] );
	
						if( in_array( $member_id['user_group'], $groups ) OR $member_id['user_group'] == "1") {
							return $matches[2];
						} else return "<div class=\"quote dlehidden\">" . $lang['news_regus'] . "</div>";
						
					} else {
						
						if( $user_group[$member_id['user_group']]['allow_hide'] ) return $matches[2]; else return "<div class=\"quote dlehidden\">" . $lang['news_regus'] . "</div>";
						
					}
	
			}, $tpl->copy_template );
		}


		if( $config['files_allow'] ) if( strpos( $tpl->copy_template, "[attachment=" ) !== false ) {
			$tpl->copy_template = show_attach( $tpl->copy_template, NEWS_ID );
		}

	}
		
} else {
	
	if( strpos( $tpl->copy_template, "related-news" ) !== false ) {
		$tpl->set( '{related-news}', "" );
		$tpl->set_block( "'\\[related-news\\](.*?)\\[/related-news\\]'si", "" );
	}
	
	if( strpos( $tpl->copy_template, "[xf" ) !== false ) {
		$tpl->copy_template = preg_replace( "'\\[xfnotgiven_(.*?)\\](.*?)\\[/xfnotgiven_(.*?)\\]'is", "", $tpl->copy_template );
		$tpl->copy_template = preg_replace( "'\\[xfgiven_(.*?)\\](.*?)\\[/xfgiven_(.*?)\\]'is", "", $tpl->copy_template );
		$tpl->copy_template = preg_replace( "'\\[xfvalue_(.*?)\\]'i", "", $tpl->copy_template );
	}
	
	if( strpos( $tpl->copy_template, "[ifxfvalue" ) !== false ) {
		$tpl->copy_template = preg_replace( "#\\[ifxfvalue(.+?)\\](.+?)\\[/ifxfvalue\\]#is", "", $tpl->copy_template );
	}

}

if ($config['allow_skin_change']) {
	$tpl->set('{changeskin}', ChangeSkin($config['skin']));
	$tpl->set('[changeskin]', '');
	$tpl->set('[/changeskin]', '');
} else {
	$tpl->set('{changeskin}', '');
	$tpl->set_block("'\\[changeskin\\](.*?)\\[/changeskin\\]'si", "");
}

if (count ( $banners ) and $config['allow_banner']) {

	foreach ( $banners as $name => $value ) {
		$tpl->copy_template = str_replace ( "{banner_" . $name . "}", $value, $tpl->copy_template );
		if ( $value ) {
			$tpl->copy_template = str_replace ( "[banner_" . $name . "]", "", $tpl->copy_template );
			$tpl->copy_template = str_replace ( "[/banner_" . $name . "]", "", $tpl->copy_template );
		}
	}

}

$tpl->set_block ( "'{banner_(.*?)}'si", "" );
$tpl->set_block ( "'\\[banner_(.*?)\\](.*?)\\[/banner_(.*?)\\]'si", "" );

if ($config['rss_informer'] AND count ($informers) ) {
	foreach ( $informers as $name => $value ) {
		$tpl->copy_template = str_replace ( "{inform_" . $name . "}", $value, $tpl->copy_template );
	}
}

if (stripos ( $tpl->copy_template, "[category=" ) !== false) {
	$tpl->copy_template = preg_replace_callback ( "#\\[(category)=(.+?)\\](.*?)\\[/category\\]#is", "check_category", $tpl->copy_template );
}

if (stripos ( $tpl->copy_template, "[not-category=" ) !== false) {
	$tpl->copy_template = preg_replace_callback ( "#\\[(not-category)=(.+?)\\](.*?)\\[/not-category\\]#is", "check_category", $tpl->copy_template );
}

if (stripos ( $tpl->copy_template, "[static=" ) !== false) {
	$tpl->copy_template = preg_replace_callback ( "#\\[(static)=(.+?)\\](.*?)\\[/static\\]#is", "check_static", $tpl->copy_template );
}

if (stripos ( $tpl->copy_template, "[not-static=" ) !== false) {
	$tpl->copy_template = preg_replace_callback ( "#\\[(not-static)=(.+?)\\](.*?)\\[/not-static\\]#is", "check_static", $tpl->copy_template );
}

if (stripos ( $tpl->copy_template, "{customcomments" ) !== false) {
	$tpl->copy_template = preg_replace_callback ( "#\\{customcomments(.+?)\\}#i", "custom_comments", $tpl->copy_template );
}

if (stripos ( $tpl->copy_template, "{custom" ) !== false) {
	$tpl->copy_template = preg_replace_callback ( "#\\{custom(.+?)\\}#i", "custom_print", $tpl->copy_template );
}

if ( ($allow_active_news AND $news_found AND $config['allow_change_sort'] AND $dle_module != "userinfo") OR defined('CUSTOMSORT')) {

	$tpl->set ( '[sort]', "" );
	$tpl->set ( '{sort}', news_sort ( $do ) );
	$tpl->set ( '[/sort]', "" );

} else {

	$tpl->set_block ( "'\\[sort\\](.*?)\\[/sort\\]'si", "" );

}

$tpl->set('{topnews}', isset($tpl->result['topnews']) ? $tpl->result['topnews'] : '');

if( $vk_url ) {
	$tpl->set( '[vk]', "" );
	$tpl->set( '[/vk]', "" );
	$tpl->set( '{vk_url}', $vk_url );	
} else {
	$tpl->set_block( "'\\[vk\\](.*?)\\[/vk\\]'si", "" );
	$tpl->set( '{vk_url}', '' );	
}
if( $odnoklassniki_url ) {
	$tpl->set( '[odnoklassniki]', "" );
	$tpl->set( '[/odnoklassniki]', "" );
	$tpl->set( '{odnoklassniki_url}', $odnoklassniki_url );
} else {
	$tpl->set_block( "'\\[odnoklassniki\\](.*?)\\[/odnoklassniki\\]'si", "" );
	$tpl->set( '{odnoklassniki_url}', '' );	
}
if( $facebook_url ) {
	$tpl->set( '[facebook]', "" );
	$tpl->set( '[/facebook]', "" );
	$tpl->set( '{facebook_url}', $facebook_url );	
} else {
	$tpl->set_block( "'\\[facebook\\](.*?)\\[/facebook\\]'si", "" );
	$tpl->set( '{facebook_url}', '' );	
}
if( $google_url ) {
	$tpl->set( '[google]', "" );
	$tpl->set( '[/google]', "" );
	$tpl->set( '{google_url}', $google_url );
} else {
	$tpl->set_block( "'\\[google\\](.*?)\\[/google\\]'si", "" );
	$tpl->set( '{google_url}', '' );	
}
if( $mailru_url ) {
	$tpl->set( '[mailru]', "" );
	$tpl->set( '[/mailru]', "" );
	$tpl->set( '{mailru_url}', $mailru_url );	
} else {
	$tpl->set_block( "'\\[mailru\\](.*?)\\[/mailru\\]'si", "" );
	$tpl->set( '{mailru_url}', '' );	
}
if( $yandex_url ) {
	$tpl->set( '[yandex]', "" );
	$tpl->set( '[/yandex]', "" );
	$tpl->set( '{yandex_url}', $yandex_url );
} else {
	$tpl->set_block( "'\\[yandex\\](.*?)\\[/yandex\\]'si", "" );
	$tpl->set( '{yandex_url}', '' );
}

$config['http_home_url'] = explode(basename($_SERVER['PHP_SELF']), $_SERVER['PHP_SELF']);
$config['http_home_url'] = reset ( $config['http_home_url'] );

if ( !$user_group[$member_id['user_group']]['allow_admin'] ) $config['admin_path'] = "";
if ($config['thumb_gallery'] and ($dle_module == "showfull" or $dle_module == "static")) $config['thumb_gallery'] = 1; else $config['thumb_gallery'] = 0;

$ajax .= <<<HTML
{$twofactor_alert}<script>
<!--
var dle_root       = '{$config['http_home_url']}';
var dle_admin      = '{$config['admin_path']}';
var dle_login_hash = '{$dle_login_hash}';
var dle_group      = {$member_id['user_group']};
var dle_skin       = '{$config['skin']}';
var dle_wysiwyg    = {$config['allow_comments_wysiwyg']};
var menu_short     = '{$lang['menu_short']}';
var menu_full      = '{$lang['menu_full']}';
var menu_profile   = '{$lang['menu_profile']}';
var menu_send      = '{$lang['menu_send']}';
var menu_uedit     = '{$lang['menu_uedit']}';
var dle_info       = '{$lang['p_info']}';
var dle_confirm    = '{$lang['p_confirm']}';
var dle_prompt     = '{$lang['p_prompt']}';
var dle_req_field  = ["{$lang['req_field_1']}", "{$lang['req_field_2']}", "{$lang['req_field_3']}"];
var dle_del_agree  = '{$lang['news_delcom']}';
var dle_spam_agree = '{$lang['mark_spam']}';
var dle_c_title    = '{$lang['complaint_title']}';
var dle_complaint  = '{$lang['add_to_complaint']}';
var dle_mail       = '{$lang['reply_mail']}';
var dle_big_text   = '{$lang['big_text']}';
var dle_orfo_title = '{$lang['orfo_title']}';
var dle_p_send     = '{$lang['p_send']}';
var dle_p_send_ok  = '{$lang['p_send_ok']}';
var dle_save_ok    = '{$lang['n_save_ok']}';
var dle_reply_title= '{$lang['reply_comments']}';
var dle_tree_comm  = '{$dle_tree_comments}';
var dle_del_news   = '{$lang['news_delnews']}';
var dle_sub_agree  = '{$lang['subscribe_info_3']}';
var dle_unsub_agree  = '{$lang['subscribe_info_4']}';
var dle_captcha_type  = '{$config['allow_recaptcha']}';
var dle_share_interesting  = ["{$lang['share_i_1']}", "{$lang['share_i_2']}", "{$lang['share_i_3']}", "{$lang['share_i_4']}", "{$lang['share_i_5']}", "{$lang['share_i_6']}"];
var DLEPlayerLang     = {prev: '{$lang['player_prev']}',next: '{$lang['player_next']}',play: '{$lang['player_play']}',pause: '{$lang['player_pause']}',mute: '{$lang['player_mute']}', unmute: '{$lang['player_unmute']}', settings: '{$lang['player_settings']}', enterFullscreen: '{$lang['player_fullscreen']}', exitFullscreen: '{$lang['player_efullscreen']}', speed: '{$lang['player_speed']}', normal: '{$lang['player_normal']}', quality: '{$lang['player_quality']}', pip: '{$lang['player_pip']}'};
var DLEGalleryLang    = {CLOSE: '{$lang['thumb_closetitle']}', NEXT: '{$lang['thumb_nexttitle']}', PREV: '{$lang['thumb_previoustitle']}', ERROR: '{$lang['all_err_1']}', IMAGE_ERROR: '{$lang['thumb_imageerror']}', TOGGLE_AUTOPLAY: '{$lang['thumb_playtitle']}', TOGGLE_SLIDESHOW: '{$lang['thumb_playtitle']}', TOGGLE_FULLSCREEN: '{$lang['thumb_fullscreen']}', TOGGLE_THUMBS: '{$lang['thumb_thtoggle']}', TOGGLE_FULL: '{$lang['thumb_thzoom']}', ITERATEZOOM: '{$lang['thumb_thzoom']}', DOWNLOAD: '{$lang['thumb_thdownload']}' };
var DLEGalleryMode    = {$config['thumb_gallery']};
var DLELazyMode       = {$config['image_lazy']};\n
HTML;

if ($user_group[$member_id['user_group']]['allow_all_edit']) {

	$ajax .= <<<HTML
var dle_notice     = '{$lang['btn_notice']}';
var dle_p_text     = '{$lang['p_text']}';
var dle_del_msg    = '{$lang['p_message']}';
var allow_dle_delete_news   = true;\n
HTML;

} else {

	$ajax .= <<<HTML
var allow_dle_delete_news   = false;\n
HTML;

}

if ($config['fast_search'] AND $user_group[$member_id['user_group']]['allow_search']) {

	$ajax .= <<<HTML
var dle_search_delay   = false;
var dle_search_value   = '';
HTML;

	$onload_scripts[] = "FastSearch();";

}

if ( defined('DLE_PHP_MIN') AND !DLE_PHP_MIN ) {
	$lang['stat_phperror'] = str_replace('{minversion}', DLE_PHP_MIN_VERSION, $lang['stat_phperror']);
	$lang['stat_phperror'] = str_replace('{version}', PHP_VERSION, $lang['stat_phperror']);

	$onload_scripts[] = "DLEPush.error('{$lang['stat_phperror']}');";
}

$show_error_info = false;

if( $_SERVER['QUERY_STRING'] AND !$tpl->result['content'] AND !$tpl->result['info'] AND stripos ( $tpl->copy_template, "{content}" ) !== false ) {
	$show_error_info = true;
}

if($dle_module == "main" AND $config['start_site'] == 2 ) {
	$show_error_info = false;
}

if( $show_error_info ) {

	header( "HTTP/1.0 404 Not Found" );
	$need_404 = false;
	
	if( $config['own_404'] AND file_exists(ROOT_DIR . '/404.html') ) {
		header("Content-type: text/html; charset=utf-8");
		echo file_get_contents( ROOT_DIR . '/404.html' );
		die();
		
	} else msgbox( $lang['all_err_1'], $lang['news_err_27'] );

}

if($need_404) {
	@header( "HTTP/1.0 404 Not Found" );
}

if( is_array($tpl->onload_scripts) AND count($tpl->onload_scripts) ) {
	$onload_scripts = array_merge($onload_scripts, $tpl->onload_scripts);
}

if ( count($onload_scripts) ) {
	
	$onload_scripts =implode("\n", $onload_scripts);

	$ajax .= <<<HTML

jQuery(function($){
{$onload_scripts}
});
HTML;

} else $onload_scripts="";

$ajax .= <<<HTML

//-->
</script>
HTML;

if( ($tpl->result['content'] AND isset($tpl->result['navigation']) AND $tpl->result['navigation']) OR defined('CUSTOMNAVIGATION') ) {

	$tpl->set( '[navigation]', "" );
	$tpl->set( '[/navigation]', "" );
	$tpl->set_block( "'\\[not-navigation\\](.*?)\\[/not-navigation\\]'si", "" );
		
	if( stripos ( $tpl->copy_template, "{navigation}" ) !== false )	{

		$tpl->result['content'] = str_replace ( '{newsnavigation}', '', $tpl->result['content'] );
		$tpl->copy_template = str_replace ( '{newsnavigation}', '', $tpl->copy_template );
			
		if( isset($tpl->result['navigation']) AND $tpl->result['navigation'] AND stripos ( $tpl->copy_template, "{content}" ) !== false ) {
			
			$tpl->set( '{navigation}', $tpl->result['navigation'] );
			
		} else {
			
			$tpl->set( '{navigation}', $custom_navigation );
			
		}

	} else {
		
		if (isset($tpl->result['navigation']) AND $tpl->result['navigation'] AND stripos($tpl->copy_template, "{content}") !== false) {

			$tpl->result['content'] = str_replace('{newsnavigation}', $tpl->result['navigation'], $tpl->result['content']);

		} else {

			$tpl->copy_template = str_replace('{newsnavigation}', $custom_navigation, $tpl->copy_template);
		}

	}

} else {
	
	$tpl->set( '{navigation}', "" );
	$tpl->set( '[not-navigation]', "" );
	$tpl->set( '[/not-navigation]', "" );
	$tpl->set_block( "'\\[navigation\\](.*?)\\[/navigation\\]'si", "" );
	
}

$tpl->set ( '{AJAX}', $ajax );
$tpl->set ( '{info}',  $tpl->result['info'] );
$tpl->set ( '{content}', $tpl->result['content'] );
$tpl->compile ( 'main' );

if (strpos($tpl->result['main'], "<pre") !== false) {

	$js_array[] = "public/prism/prism.js";
}

if ((strpos($tpl->result['main'], "highslide") !== false) AND $dle_module != "addnews") {

	$js_array[] = "public/fancybox/fancybox.js";
}

if (strpos($tpl->result['main'], "data-src=") !== false) {
	$js_array[] = "public/js/lazyload.js";
}

if (strpos($tpl->result['main'], "share-content") !== false) {

	$js_array[] = "public/masha/masha.js";
}

if (strpos($tpl->result['main'], "dleplyrplayer") !== false) {
	if (strpos($tpl->result['main'], ".m3u8") !== false) {
		$js_array[] = "public/html5player/hls.js";
	}
	$css_array[] = "public/html5player/plyr.css";
	$js_array[] = "public/html5player/plyr.js";
} elseif (strpos($tpl->result['main'], "dleaudioplayer") !== false OR strpos($tpl->result['main'], "dlevideoplayer") !== false) {

	$css_array[] = "public/html5player/player.css";
	$js_array[] = "public/html5player/player.js";
}

if ($user_group[$member_id['user_group']]['allow_pm']) {
	$allow_comments_ajax = true;
}

if ($allow_comments_ajax AND $dle_module != "addnews") {

	$js_array[] = "public/editor/tiny_mce/tinymce.min.js";
}


$js_array = build_css($css_array, $config) . "\n" . build_js($js_array, $config);

$schema = DLESEO::CompileSchema();

if ($schema) {
	$js_array .= "\n<script type=\"application/ld+json\">" . DLESEO::CompileSchema() . "</script>";
}

if (stripos($tpl->result['main'], "{jsfiles}") !== false) {
	$tpl->result['main'] = preg_replace('/' . preg_quote('{headers}', '/') . '/', $metatags, $tpl->result['main'], 1);
	$tpl->result['main'] = preg_replace('/' . preg_quote('{jsfiles}', '/') . '/', $js_array, $tpl->result['main'], 1);
} else {
	$tpl->result['main'] = preg_replace('/' . preg_quote('{headers}', '/') . '/', $metatags . "\n" . $js_array, $tpl->result['main'], 1);
}


$tpl->result['main'] = str_replace(array("_&#123;_", "_&#91;_"), array("{", "["), $tpl->result['main']);

if( $is_logged AND stripos ( $tpl->result['main'], "-favorites-" ) !== false) {
	
	$fav_arr = explode(',', $member_id['favorites'] );
	
	foreach( $fav_arr as $fav_id ) {
		$tpl->result['main'] = str_replace ( "{-favorites-{$fav_id}}", "<a data-fav-id=\"{$fav_id}\" class=\"favorite-link del-favorite\" href=\"{$_SERVER['PHP_SELF']}?do=favorites&amp;doaction=del&amp;id={$fav_id}\"><img src=\"{$config['http_home_url']}templates/{$config['skin']}/dleimages/minus_fav.gif\" onclick=\"doFavorites('{$fav_id}', 'minus', 0); return false;\" title=\"{$lang['news_minfav']}\" alt=\"\"></a>", $tpl->result['main'] );
		$tpl->result['main'] = str_replace ( "[del-favorites-{$fav_id}]", "<span data-favorites-del=\"{$fav_id}\" style=\"display:none\"></span><a onclick=\"doFavorites('{$fav_id}', 'minus', 1, 'short'); return false;\" href=\"{$_SERVER['PHP_SELF']}?do=favorites&amp;doaction=del&amp;id={$fav_id}\">", $tpl->result['main'] );
		$tpl->result['main'] = str_replace ( "[/del-favorites-{$fav_id}]", "</a>", $tpl->result['main'] );
		$tpl->result['main'] = preg_replace( "'\\[add-favorites-{$fav_id}\\](.*?)\\[/add-favorites-{$fav_id}\\]'is", "<span data-favorites-add=\"{$fav_id}\" style=\"display:none\"></span>", $tpl->result['main'] );
	}
	
	$tpl->result['main'] = preg_replace( "'\\{-favorites-(\d+)\\}'i", "<a data-fav-id=\"\\1\" class=\"favorite-link add-favorite\" href=\"{$_SERVER['PHP_SELF']}?do=favorites&amp;doaction=add&amp;id=\\1\"><img src=\"{$config['http_home_url']}templates/{$config['skin']}/dleimages/plus_fav.gif\" onclick=\"doFavorites('\\1', 'plus', 0); return false;\" title=\"{$lang['news_addfav']}\" alt=\"\"></a>", $tpl->result['main'] );
	$tpl->result['main'] = preg_replace( "'\\[add-favorites-(\d+)\\]'i", "<span data-favorites-add=\"\\1\" style=\"display:none\"></span><a onclick=\"doFavorites('\\1', 'plus', 1, 'short'); return false;\" href=\"{$_SERVER['PHP_SELF']}?do=favorites&amp;doaction=add&amp;id=\\1\">", $tpl->result['main'] );
	$tpl->result['main'] = preg_replace( "'\\[/add-favorites-(\d+)\\]'i", "</a>", $tpl->result['main'] );
	$tpl->result['main'] = preg_replace( "'\\[del-favorites-(\d+)\\](.*?)\\[/del-favorites-(\d+)\\]'si", "<span data-favorites-del=\"\\1\" style=\"display:none\"></span>", $tpl->result['main'] );

}

if( stripos ( $tpl->result['main'], '[custom' ) !== false OR stripos ( $tpl->result['main'], '[not-custom' ) !== false) {
	$tpl->result['main'] = preg_replace_callback("#\\[(custom|not-custom)=(.+?)\\](.*?)\[/\\1\]#is",
		function ($matches) use ($custom_blocks_names) {

			$matches[1] = trim($matches[1]);
			$matches[2] = trim($matches[2]);

			if ( $matches[1] == 'custom' ) {
				if( isset($custom_blocks_names[$matches[2]]) AND $custom_blocks_names[$matches[2]] ) return $matches[3];
				else return '';
			}

			if ($matches[1] == 'not-custom') {
				if (isset($custom_blocks_names[$matches[2]]) AND $custom_blocks_names[$matches[2]]) return '';
				else return $matches[3];
			}

			return $matches[0];

		}, $tpl->result['main']);
}

if (stripos($tpl->result['main'], '[customcomments') !== false or stripos($tpl->result['main'], '[not-customcomments') !== false) {
	$tpl->result['main'] = preg_replace_callback(
		"#\\[(customcomments|not-customcomments)=(.+?)\\](.*?)\[/\\1\]#is",
		function ($matches) use ($custom_comments_blocks_names) {

			$matches[1] = trim($matches[1]);
			$matches[2] = trim($matches[2]);

			if ($matches[1] == 'customcomments') {
				if (isset($custom_comments_blocks_names[$matches[2]]) AND $custom_comments_blocks_names[$matches[2]]) return $matches[3];
				else return '';
			}

			if ($matches[1] == 'not-customcomments') {
				if (isset($custom_comments_blocks_names[$matches[2]]) AND $custom_comments_blocks_names[$matches[2]]) return '';
				else return $matches[3];
			}

			return $matches[0];
		},
		$tpl->result['main']
	);
}

if ($config['allow_links'] and isset($replace_links['all']) ) $tpl->result['main'] = replace_links ( $tpl->result['main'], $replace_links['all'] );

$tpl->result['main'] = str_ireplace( '{THEME}', $config['http_home_url'] . 'templates/' . $config['skin'], $tpl->result['main'] );

if ( is_array($replace_url) ) $tpl->result['main'] = str_replace ( $replace_url[0]."/", $replace_url[1]."/", $tpl->result['main'] );

if($remove_canonical) {
	$tpl->result['main'] = preg_replace( "#<link rel=['\"]canonical['\"](.+?)>#i", "", $tpl->result['main'] );
}

$tpl->result['main'] = str_replace ( 'src="http://'.$_SERVER['HTTP_HOST'].'/', 'src="/', $tpl->result['main'] );
$tpl->result['main'] = str_replace ( 'srcset="http://'.$_SERVER['HTTP_HOST'].'/', 'srcset="/', $tpl->result['main'] );
$tpl->result['main'] = str_replace ( 'src="https://'.$_SERVER['HTTP_HOST'].'/', 'src="/', $tpl->result['main'] );
$tpl->result['main'] = str_replace ( 'srcset="https://'.$_SERVER['HTTP_HOST'].'/', 'srcset="/', $tpl->result['main'] );

echo $tpl->result['main'];

$tpl->global_clear();

$db->close();

echo "\n<!-- DataLife Engine Copyright SoftNews Media Group (https://dle-news.ru) -->\r\n";

GzipOut();

?>