<?php
/*
=====================================================
 DataLife Engine - by SoftNews Media Group
-----------------------------------------------------
 https://dle-news.ru/
-----------------------------------------------------
 Copyright (c) 2004-2025 SoftNews Media Group
=====================================================
 File: mediatags.php
-----------------------------------------------------
 Use: Media tags index + tag items (wallpapers/ringtones/videos)
=====================================================
*/

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

$nocache = false;
if (isset($_REQUEST['nocache']) AND $_REQUEST['nocache']) {
	$nocache = true;
}

$type_param = isset($_REQUEST['type']) ? (string)$_REQUEST['type'] : '';
$type_param = trim(strip_tags(rawurldecode($type_param)));
$type_param = preg_replace('/\s+/u', ' ', $type_param);

$fixed_do = '';
if (isset($do) && is_string($do)) {
	if ($do === 'wallpapertags' || $do === 'ringtonetags' || $do === 'videotags') {
		$fixed_do = $do;
	}
}

$tag_param = isset($_REQUEST['tag']) ? (string)$_REQUEST['tag'] : '';
if ($tag_param === '' && isset($_REQUEST['name'])) {
	$tag_param = (string)$_REQUEST['name'];
}
$tag_param = trim(strip_tags(rawurldecode($tag_param)));
$tag_param = preg_replace('/\s+/u', ' ', $tag_param);

$allowed_types = array('wallpapers', 'ringtones', 'videos');
if ($type_param === '') {
	$type_param = 'wallpapers';
}

$type_param = function_exists('dle_strtolower') ? dle_strtolower($type_param) : mb_strtolower($type_param, 'UTF-8');
if (!in_array($type_param, $allowed_types, true)) {
	$type_param = 'wallpapers';
}

// If using a dedicated route, force its type and prefer that URL style.
if ($fixed_do) {
	if ($fixed_do === 'wallpapertags') $type_param = 'wallpapers';
	elseif ($fixed_do === 'ringtonetags') $type_param = 'ringtones';
	elseif ($fixed_do === 'videotags') $type_param = 'videos';
}

$type_labels = array(
	'wallpapers' => 'Wallpapers',
	'ringtones' => 'Ringtones',
	'videos' => 'Live Wallpapers',
);

$type_item_labels = array(
	'wallpapers' => array('singular' => 'wallpaper', 'plural' => 'wallpapers'),
	'ringtones' => array('singular' => 'ringtone', 'plural' => 'ringtones'),
	'videos' => array('singular' => 'live wallpaper', 'plural' => 'live wallpapers'),
);

$get_item_label = static function (string $type, int $count) use ($type_item_labels): string {
	$labels = $type_item_labels[$type] ?? array('singular' => 'item', 'plural' => 'items');
	return ($count === 1) ? $labels['singular'] : $labels['plural'];
};

$current_year = date('Y');

$seo_desc_templates = array(
	'wallpapers' => 'Download free HD & 4K Wallpapers %s. Browse trending tags and find backgrounds for iPhone, Android, and desktop.',
	'ringtones' => 'Download new MP3 Ringtones %s. Browse trending tags and get the latest tones for iPhone and Android.',
	'videos' => 'Download 4K Live Wallpapers %s. Browse trending tags and get the latest animated video wallpapers for your phone.',
);

$seo_tag_desc_templates = array(
	'wallpapers' => 'Download Wallpapers %s tagged “%s”. Free HD & 4K backgrounds for iPhone, Android, and desktop.',
	'ringtones' => 'Download Ringtones %s tagged “%s”. New MP3 tones and sounds — free download in one click.',
	'videos' => 'Download Live Wallpapers %s tagged “%s”. 4K animated video wallpapers for your phone — free download.',
);

$type_switch = '';
foreach ($allowed_types as $t) {
	if ($fixed_do) {
		$do_map = array('wallpapers' => 'wallpapertags', 'ringtones' => 'ringtonetags', 'videos' => 'videotags');
		$href = $config['http_home_url'] . 'index.php?do=' . urlencode($do_map[$t]);
	} else {
		$href = $config['http_home_url'] . 'index.php?do=mediatags&type=' . urlencode($t);
	}
	$label = isset($type_labels[$t]) ? $type_labels[$t] : $t;
	$active = ($t === $type_param) ? ' is-active' : '';
	$type_switch .= '<a class="btn' . $active . '" href="' . $href . '">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</a> ';
}

$base_tag = $type_param;

// ------------------------------
// Shared restrictions logic (aligned with artists.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 = "";
}

$fixed = $config['allow_fixed'] ? "fixed desc, " : "";

$news_sort_by = $config['news_sort'] ? $config['news_sort'] : "date";
$news_direction_by = $config['news_msort'] ? $config['news_msort'] : "DESC";

$allow_list = explode ( ',', $user_group[$member_id['user_group']]['allow_cats'] );
$stop_list = "";
$cat_join = "";
$cat_join_count = "";
$extra_join = "LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) ";

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) ";
		$cat_join_count = "p " . $cat_join;

	} else {

		$stop_list = "category IN ('" . implode ( "','", $allow_list ) . "') AND ";

	}

}

$not_allow_cats = explode ( ',', $user_group[$member_id['user_group']]['not_allow_cats'] );

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_count = "p ";

	} else {

		$stop_list = "category NOT IN ('" . implode ( "','", $not_allow_cats ) . "') AND ";

	}

}

if( $config['user_in_news'] ) {

	$user_select = ", u.email, u.name, u.user_id, u.news_num, u.comm_num as user_comm_num, u.user_group, u.lastdate, u.reg_date, u.banned, u.allow_mail, u.info, u.signature, u.foto, u.fullname, u.land, u.favorites, u.pm_all, u.pm_unread, u.time_limit, u.xfields as user_xfields ";
	$user_join = "LEFT JOIN " . USERPREFIX . "_users u ON (e.user_id=u.user_id) ";

} else { $user_select = ""; $user_join = ""; }

if ($user_group[$member_id['user_group']]['allow_short']) { $stop_list = ""; $cat_join = ""; $cat_join_count = ""; }

if( !in_array($news_sort_by, array('rating', 'news_read', 'editdate')) ) $extra_join = '';

$config['news_number'] = intval($config['news_number']);
if ($config['news_number'] < 1) $config['news_number'] = 1;

// ------------------------------
// Tag detail: show items for a tag within a type
// ------------------------------
if ($tag_param !== '') {

	$tag_norm = function_exists('dle_strtolower') ? dle_strtolower($tag_param) : mb_strtolower($tag_param, 'UTF-8');
	$tag_norm = trim($tag_norm);
	if ($tag_norm === '') {
		$tag_param = '';
	} else {
		$tag_title = $tag_norm;
		if (function_exists('dle_substr')) {
			$tag_title = dle_substr($tag_title, 0, 80);
		} else {
			$tag_title = mb_substr($tag_title, 0, 80, 'UTF-8');
		}

			// Set $metatags['title'] after we know $items_total, so we can include the count.
			// Set $metatags['description'] after we know $items_total, so we can match the on-page caption text.
			$metatags['keywords'] = $tag_title . ', download ' . strtolower($type_labels[$type_param]) . ' ' . $current_year . ', ' . strtolower($type_labels[$type_param]) . ' ' . $current_year;

		if ($fixed_do) {
			$navigation_first_page = $config['http_home_url'] . "index.php?do=" . urlencode($fixed_do) . "&tag=" . urlencode($tag_norm);
		} else {
			$navigation_first_page = $config['http_home_url'] . "index.php?do=mediatags&type=" . urlencode($type_param) . "&tag=" . urlencode($tag_norm);
		}
		$url_page = $navigation_first_page . "&cstart={cstart}";
		$canonical = $navigation_first_page;

		$cstart = isset($_GET['cstart']) ? intval($_GET['cstart']) : 0;
		if ($cstart < 1) $cstart = 0;
		if ($cstart > 9999999) $cstart = 9999999;
		if ($cstart) {
			$cstart = ($cstart - 1) * $config['news_number'];
		}

		$tag_sql = $db->safesql($tag_norm);
		$base_sql = $db->safesql($base_tag);

		$sql_select_ids = "SELECT DISTINCT p.id FROM " . PREFIX . "_post p " .
			"INNER JOIN " . PREFIX . "_tags t ON (t.news_id=p.id AND t.tag='{$tag_sql}') " .
			"INNER JOIN " . PREFIX . "_tags b ON (b.news_id=p.id AND b.tag='{$base_sql}') " .
			"{$cat_join}{$extra_join}WHERE {$stop_list}p.approve=1{$where_date} " .
			"ORDER BY " . $fixed . $news_sort_by . " " . $news_direction_by . " " .
			"LIMIT " . $cstart . "," . $config['news_number'];

		$sql_count = "SELECT COUNT(DISTINCT p.id) as count FROM " . PREFIX . "_post p " .
			"INNER JOIN " . PREFIX . "_tags t ON (t.news_id=p.id AND t.tag='{$tag_sql}') " .
			"INNER JOIN " . PREFIX . "_tags b ON (b.news_id=p.id AND b.tag='{$base_sql}') " .
			"{$cat_join}WHERE {$stop_list}p.approve=1";

		$sql_select_ids = $db->super_query($sql_select_ids, true);
		$items_total = 0;

		if (count($sql_select_ids)) {

			$temp_arr = array();
			foreach ($sql_select_ids as $value) {
				$temp_arr[] = $value['id'];
			}
			$sql_ids_in = implode(',', $temp_arr);

			$count_row = $db->super_query($sql_count . $where_date);
			$items_total = isset($count_row['count']) ? (int)$count_row['count'] : 0;
			if ($items_total < 0) $items_total = 0;

			$tag_desc_suffix = '';
			if ($type_param === 'ringtones') {
				$tag_desc_suffix = ' Preview MP3 tones, download in one click, and explore similar tags for more new ringtones.';
			} elseif ($type_param === 'videos') {
				$tag_desc_suffix = ' Get 4K animated video live wallpapers for your phone and explore similar tags for more.';
			} else {
				$tag_desc_suffix = ' Browse more tags to find free HD & 4K backgrounds for iPhone, Android, and desktop.';
			}

			$page_title = ($items_total > 0)
				? ('Download ' . $items_total . ' ' . $tag_title . ' ' . $type_labels[$type_param] . ' ' . $current_year)
				: ('Download ' . $tag_title . ' ' . $type_labels[$type_param] . ' ' . $current_year);
			$metatags['title'] = $page_title;
			$metatags['header_title'] = $page_title;

			$metatags['description'] = (($items_total > 0)
				? ('Download ' . $items_total . ' ' . $tag_title . ' ' . $type_labels[$type_param] . ' ' . $current_year . '.')
				: ('Download ' . $tag_title . ' ' . $type_labels[$type_param] . ' ' . $current_year . '.'))
				. $tag_desc_suffix;

			$sql_select = "SELECT p.id, p.autor, p.date, p.short_story, CHAR_LENGTH(p.full_story) as full_story, p.xfields, p.title, p.descr, p.keywords, p.category, p.alt_name, p.comm_num, p.allow_comm, p.allow_main, p.approve, p.fixed, p.symbol, p.tags, e.news_read, e.allow_rate, e.rating, e.vote_num, e.votes, e.view_edit, e.disable_index, e.editdate, e.editor, e.reason {$user_select}FROM " . PREFIX . "_post p LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) {$user_join}";
			$sql_select .= "WHERE p.id IN ({$sql_ids_in}) ORDER BY FIND_IN_SET(p.id, '" . $sql_ids_in . "')";

			// Ensure we render only this module output (avoid mixing with any prior content)
			$prev_category_id = isset($category_id) ? $category_id : 0;
			$prev_view_template = isset($view_template) ? $view_template : '';
			// Force shortstory.tpl (MovieTor card layout) regardless of any category short_tpl overrides.
			$category_id = 0;
			$view_template = '';
			$tpl->result['content'] = '';
			$tpl->result['navigation'] = '';
			include_once (DLEPlugins::Check(ENGINE_DIR . '/modules/show.short.php'));
			$items_html = (string)($tpl->result['content'] ?? '');
			$nav_html = (string)($tpl->result['navigation'] ?? '');
			$items_html = str_replace('{newsnavigation}', '', $items_html);
			// show.short.php compiles into $tpl->result['content'] (append mode); clear it before compiling our page wrapper.
			$tpl->result['content'] = '';
			$tpl->result['navigation'] = '';
			$category_id = $prev_category_id;
			$view_template = $prev_view_template;

			$tpl->load_template('mediatags.tpl');
			$tpl->set('{title}', htmlspecialchars($tag_title . ' ' . $type_labels[$type_param], ENT_QUOTES, 'UTF-8'));
			$tpl->set('{year}', htmlspecialchars($current_year, ENT_QUOTES, 'UTF-8'));
			$tpl->set('{description}', htmlspecialchars('Download ' . $items_total . ' ' . $tag_title . ' ' . $type_labels[$type_param] . ' ' . $current_year . '.' . $tag_desc_suffix, ENT_QUOTES, 'UTF-8'));
			$tpl->set('{type-switch}', $type_switch);
			$tpl->set('{items}', $items_html);
			$tpl->set('{navigation}', $nav_html);
			$tpl->set('{type}', htmlspecialchars($type_param, ENT_QUOTES, 'UTF-8'));
			$tpl->compile('content');
			$tpl->clear();
			$tpl->result['navigation'] = '';

		} else {
			$page_title = 'Download ' . $tag_title . ' ' . $type_labels[$type_param] . ' ' . $current_year;
			$metatags['title'] = $page_title;
			$metatags['header_title'] = $page_title;
			$metatags['description'] = 'Download ' . $tag_title . ' ' . $type_labels[$type_param] . ' ' . $current_year . '.';
			$tpl->load_template('mediatags.tpl');
			$tpl->set('{title}', htmlspecialchars($tag_title . ' ' . $type_labels[$type_param], ENT_QUOTES, 'UTF-8'));
			$tpl->set('{year}', htmlspecialchars($current_year, ENT_QUOTES, 'UTF-8'));
			$tpl->set('{description}', htmlspecialchars('No items found for this tag.', ENT_QUOTES, 'UTF-8'));
			$tpl->set('{type-switch}', $type_switch);
			$tpl->set('{items}', '<div class="message-info message-info--yellow">No items found.</div>');
			$tpl->set('{navigation}', '');
			$tpl->set('{type}', htmlspecialchars($type_param, ENT_QUOTES, 'UTF-8'));
			$tpl->compile('content');
			$tpl->clear();
		}

		return;
	}
}

// ------------------------------
// Tag list for a type (no tag specified)
// ------------------------------
$page = isset($_GET['cstart']) ? intval($_GET['cstart']) : 1;
if ($page < 1) $page = 1;
if ($page > 9999999) $page = 9999999;

$per_page = 60;
$offset = ($page - 1) * $per_page;

$base_sql = $db->safesql($base_tag);

// Exclude base tags from the keyword list
$exclude_tags = array('wallpapers', 'ringtones', 'videos');
$exclude_sql = array();
foreach ($exclude_tags as $t) {
	$exclude_sql[] = "'" . $db->safesql($t) . "'";
}
$exclude_sql = implode(',', $exclude_sql);

// If there are no keyword tags for this media type, fall back to showing
// an "All items" listing (tag = base tag). This prevents empty pages for
// installs where posts were tagged only with the base tag (e.g. "videos").
$count_row = $db->super_query(
	"SELECT COUNT(DISTINCT t.tag) as count FROM " . PREFIX . "_tags t " .
	"INNER JOIN " . PREFIX . "_tags b ON (b.news_id=t.news_id AND b.tag='{$base_sql}') " .
	"INNER JOIN " . PREFIX . "_post p ON (p.id=t.news_id) " .
	"{$cat_join}WHERE {$stop_list}p.approve=1{$where_date} AND t.tag<>'' AND t.tag NOT IN ({$exclude_sql})"
);
$total_tags = isset($count_row['count']) ? (int)$count_row['count'] : 0;
if ($total_tags < 0) $total_tags = 0;

if ($total_tags === 0) {
	$tag_norm = $base_tag;
	$tag_title = 'All ' . $type_labels[$type_param];
	$metatags['title'] = $tag_title;
	$metatags['header_title'] = $tag_title;
	$desc_tpl = isset($seo_desc_templates[$type_param]) ? $seo_desc_templates[$type_param] : 'Download %s — browse popular tags and download in one click.';
	$metatags['description'] = sprintf($desc_tpl, $current_year);
	$metatags['keywords'] = 'download ' . strtolower($type_labels[$type_param]) . ' ' . $current_year . ', ' . strtolower($type_labels[$type_param]) . ' ' . $current_year . ', ' . strtolower($type_labels[$type_param]);

	if ($fixed_do) {
		$navigation_first_page = $config['http_home_url'] . "index.php?do=" . urlencode($fixed_do);
	} else {
		$navigation_first_page = $config['http_home_url'] . "index.php?do=mediatags&type=" . urlencode($type_param);
	}
	$url_page = $navigation_first_page . "&cstart={cstart}";
	$canonical = $navigation_first_page;

	$cstart = isset($_GET['cstart']) ? intval($_GET['cstart']) : 0;
	if ($cstart < 1) $cstart = 0;
	if ($cstart > 9999999) $cstart = 9999999;
	if ($cstart) {
		$cstart = ($cstart - 1) * $config['news_number'];
	}

	$tag_sql = $db->safesql($tag_norm);
	$base_sql2 = $db->safesql($base_tag);

	$sql_select_ids = "SELECT DISTINCT p.id FROM " . PREFIX . "_post p " .
		"INNER JOIN " . PREFIX . "_tags t ON (t.news_id=p.id AND t.tag='{$tag_sql}') " .
		"INNER JOIN " . PREFIX . "_tags b ON (b.news_id=p.id AND b.tag='{$base_sql2}') " .
		"{$cat_join}{$extra_join}WHERE {$stop_list}p.approve=1{$where_date} " .
		"ORDER BY " . $fixed . $news_sort_by . " " . $news_direction_by . " " .
		"LIMIT " . $cstart . "," . $config['news_number'];

	$sql_count = "SELECT COUNT(DISTINCT p.id) as count FROM " . PREFIX . "_post p " .
		"INNER JOIN " . PREFIX . "_tags t ON (t.news_id=p.id AND t.tag='{$tag_sql}') " .
		"INNER JOIN " . PREFIX . "_tags b ON (b.news_id=p.id AND b.tag='{$base_sql2}') " .
		"{$cat_join}WHERE {$stop_list}p.approve=1";

	$sql_select_ids = $db->super_query($sql_select_ids, true);
	$items_total = 0;

	if (count($sql_select_ids)) {
		$temp_arr = array();
		foreach ($sql_select_ids as $value) {
			$temp_arr[] = $value['id'];
		}
		$sql_ids_in = implode(',', $temp_arr);

		$count_row2 = $db->super_query($sql_count . $where_date);
		$items_total = isset($count_row2['count']) ? (int)$count_row2['count'] : 0;
		if ($items_total < 0) $items_total = 0;

		$sql_select = "SELECT p.id, p.autor, p.date, p.short_story, CHAR_LENGTH(p.full_story) as full_story, p.xfields, p.title, p.descr, p.keywords, p.category, p.alt_name, p.comm_num, p.allow_comm, p.allow_main, p.approve, p.fixed, p.symbol, p.tags, e.news_read, e.allow_rate, e.rating, e.vote_num, e.votes, e.view_edit, e.disable_index, e.editdate, e.editor, e.reason {$user_select}FROM " . PREFIX . "_post p LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) {$user_join}";
		$sql_select .= "WHERE p.id IN ({$sql_ids_in}) ORDER BY FIND_IN_SET(p.id, '" . $sql_ids_in . "')";

		$prev_category_id = isset($category_id) ? $category_id : 0;
		$prev_view_template = isset($view_template) ? $view_template : '';
		$category_id = 0;
		$view_template = '';
		$tpl->result['content'] = '';
		$tpl->result['navigation'] = '';
		include_once (DLEPlugins::Check(ENGINE_DIR . '/modules/show.short.php'));
		$items_html = (string)($tpl->result['content'] ?? '');
		$nav_html = (string)($tpl->result['navigation'] ?? '');
		$items_html = str_replace('{newsnavigation}', '', $items_html);
		$tpl->result['content'] = '';
		$tpl->result['navigation'] = '';
		$category_id = $prev_category_id;
		$view_template = $prev_view_template;

		$tpl->load_template('mediatags.tpl');
		$tpl->set('{title}', htmlspecialchars($tag_title, ENT_QUOTES, 'UTF-8'));
		$tpl->set('{year}', htmlspecialchars($current_year, ENT_QUOTES, 'UTF-8'));
		$item_label = $get_item_label($type_param, (int)$items_total);
		$tpl->set('{description}', htmlspecialchars('Download ' . $type_labels[$type_param] . ' ' . $current_year . '. ' . $items_total . ' ' . $item_label . ' available.', ENT_QUOTES, 'UTF-8'));
		$tpl->set('{type-switch}', $type_switch);
		$tpl->set('{items}', $items_html);
		$tpl->set('{navigation}', $nav_html);
		$tpl->set('{type}', htmlspecialchars($type_param, ENT_QUOTES, 'UTF-8'));
		$tpl->compile('content');
		$tpl->clear();
		$tpl->result['navigation'] = '';
	} else {
		$tpl->load_template('mediatags.tpl');
		$tpl->set('{title}', htmlspecialchars($tag_title, ENT_QUOTES, 'UTF-8'));
		$tpl->set('{year}', htmlspecialchars($current_year, ENT_QUOTES, 'UTF-8'));
		$tpl->set('{description}', htmlspecialchars('No items found.', ENT_QUOTES, 'UTF-8'));
		$tpl->set('{type-switch}', $type_switch);
		$tpl->set('{items}', '<div class="message-info message-info--yellow">No items found.</div>');
		$tpl->set('{navigation}', '');
		$tpl->set('{type}', htmlspecialchars($type_param, ENT_QUOTES, 'UTF-8'));
		$tpl->compile('content');
		$tpl->clear();
	}

	return;
}

$sql_list = "SELECT t.tag, COUNT(DISTINCT t.news_id) as count FROM " . PREFIX . "_tags t " .
	"INNER JOIN " . PREFIX . "_tags b ON (b.news_id=t.news_id AND b.tag='{$base_sql}') " .
	"INNER JOIN " . PREFIX . "_post p ON (p.id=t.news_id) " .
	"{$cat_join}WHERE {$stop_list}p.approve=1{$where_date} AND t.tag<>'' AND t.tag NOT IN ({$exclude_sql}) " .
	"GROUP BY t.tag ORDER BY count DESC LIMIT {$offset},{$per_page}";

$sql_count_tags = "SELECT COUNT(DISTINCT t.tag) as count FROM " . PREFIX . "_tags t " .
	"INNER JOIN " . PREFIX . "_tags b ON (b.news_id=t.news_id AND b.tag='{$base_sql}') " .
	"INNER JOIN " . PREFIX . "_post p ON (p.id=t.news_id) " .
	"{$cat_join}WHERE {$stop_list}p.approve=1{$where_date} AND t.tag<>'' AND t.tag NOT IN ({$exclude_sql})";

$items = '';
$db->query($sql_list);
while ($row = $db->get_row()) {
	$tag = isset($row['tag']) ? (string)$row['tag'] : '';
	$count = isset($row['count']) ? (int)$row['count'] : 0;
	$tag = trim($tag);
	if ($tag === '') continue;
	if ($count < 0) $count = 0;

	$href = $config['http_home_url'] . 'index.php?do=mediatags&type=' . urlencode($type_param) . '&tag=' . urlencode($tag);
	if ($fixed_do) {
		$href = $config['http_home_url'] . 'index.php?do=' . urlencode($fixed_do) . '&tag=' . urlencode($tag);
	}
	$tag_safe = htmlspecialchars($tag, ENT_QUOTES, 'UTF-8');
	$item_label = $get_item_label($type_param, (int)$count);
	$items .= '<article class="mt-card">'
		. '<div class="mt-card__body">'
		. '<h3 class="mt-card__title ws-nowrap"><a href="' . $href . '">' . $tag_safe . '</a></h3>'
		. '<div class="mt-card__meta ws-nowrap">' . $count . ' ' . htmlspecialchars($item_label, ENT_QUOTES, 'UTF-8') . '</div>'
		. '</div>'
		. '</article>';
}
$db->free();

$count_row = $db->super_query($sql_count_tags);
$total_tags = isset($count_row['count']) ? (int)$count_row['count'] : 0;
if ($total_tags < 0) $total_tags = 0;
$total_pages = ($per_page > 0) ? (int)ceil($total_tags / $per_page) : 1;
if ($total_pages < 1) $total_pages = 1;

$navigation = '';
if ($total_pages > 1) {
	$base = $config['http_home_url'] . 'index.php?do=mediatags&type=' . urlencode($type_param) . '&cstart=';
	if ($fixed_do) {
		$base = $config['http_home_url'] . 'index.php?do=' . urlencode($fixed_do) . '&cstart=';
	}

	$pages = '';
	$max_pages = ($tpl->smartphone) ? 5 : 10;

	if ($total_pages <= $max_pages) {
		for ($j = 1; $j <= $total_pages; $j++) {
			if ($j == $page) $pages .= "<span>{$j}</span> ";
			else $pages .= "<a href=\"{$base}{$j}\">{$j}</a> ";
		}
	} else {
		$start = 1;
		$end = $max_pages;

		if ($page > (int)floor($max_pages / 2)) {
			$start = $page - (int)floor($max_pages / 2);
			$end = $start + ($max_pages - 1);
			if ($end > $total_pages) {
				$end = $total_pages;
				$start = $end - ($max_pages - 1);
				if ($start < 1) $start = 1;
			}
		}

		if ($start > 1) {
			$pages .= "<a href=\"{$base}1\">1</a> <span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
		}

		for ($j = $start; $j <= $end; $j++) {
			if ($j == $page) $pages .= "<span>{$j}</span> ";
			else $pages .= "<a href=\"{$base}{$j}\">{$j}</a> ";
		}

		if ($end < $total_pages) {
			$pages .= "<span class=\"nav_ext\">{$lang['nav_trennen']}</span> <a href=\"{$base}{$total_pages}\">{$total_pages}</a>";
		}
	}

	$prev_link = ($page > 1) ? '<a href="' . $base . ($page - 1) . '"><i class="pagination__btn pagination__btn--prev fal fa-arrow-left"></i></a>' : '<span><i class="pagination__btn pagination__btn--prev fal fa-arrow-left"></i></span>';
	$next_link = ($page < $total_pages) ? '<a href="' . $base . ($page + 1) . '"><i class="pagination__btn pagination__btn--next fal fa-arrow-right"></i></a>' : '<span><i class="pagination__btn pagination__btn--next fal fa-arrow-right"></i></span>';

	$navigation = '<div class="pagination ignore-select d-flex jc-center" id="pagination"><div class="pagination__pages d-flex flex-1">' . $pages . '</div>' . $prev_link . $next_link . '</div>';
}

$desc_tpl = isset($seo_desc_templates[$type_param]) ? $seo_desc_templates[$type_param] : 'Download %s — browse popular tags and download in one click.';
$desc = sprintf($desc_tpl, $current_year);

$page_title = 'Download ' . $type_labels[$type_param] . ' ' . $current_year;
$metatags['title'] = $page_title;
$metatags['header_title'] = $page_title;
$metatags['description'] = $desc;
$metatags['keywords'] = 'download ' . strtolower($type_labels[$type_param]) . ' ' . $current_year . ', ' . strtolower($type_labels[$type_param]) . ' ' . $current_year . ', free downloads';

$tpl->load_template('mediatags.tpl');
$tpl->set('{title}', htmlspecialchars($type_labels[$type_param], ENT_QUOTES, 'UTF-8'));
$tpl->set('{year}', htmlspecialchars($current_year, ENT_QUOTES, 'UTF-8'));
$tpl->set('{description}', htmlspecialchars($desc, ENT_QUOTES, 'UTF-8'));
$tpl->set('{type-switch}', $type_switch);
$tpl->set('{items}', $items ? $items : '<div class="message-info message-info--yellow">No tags found.</div>');
$tpl->set('{navigation}', $navigation);
$tpl->set('{type}', htmlspecialchars($type_param, ENT_QUOTES, 'UTF-8'));
$tpl->compile('content');
$tpl->clear();

?>
