<?php

if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('SMF'))
	require_once(dirname(__FILE__) . '/SSI.php');
elseif (!defined('SMF'))
	die('<b>Error:</b> Cannot install - please verify you put this in the same place as SMF\'s SSI.php.');

function smf_bannerBar_admin(&$admin_areas)
{
	global $txt;
	loadLanguage('smf_bannerBar');

	if (!allowedTo('admin_forum'))
		fatal_lang_error('smf_bannerBar_ErrorMessage', false);

	$admin_areas['config']['areas']['modsettings']['subsections'] += array(
		'bannerBar' => array($txt['smf_bannerBar_title']),
	);

}

function smf_bannerBar_mod(&$subActions)
{
	global $txt;
	loadLanguage('smf_bannerBar');

	$subActions['bannerBar'] = 'smf_bannerBar_settings';
}

function smf_bannerBar_remove_theme(&$subActions)
{
	global $context, $modSettings, $smcFunc;
	if (allowedTo('admin_forum')) {
		$version = version_compare((!empty($modSettings['smfVersion']) ? substr($modSettings['smfVersion'], 0, 3) : '2.0'), '2.1', '<') ? 'v2.0' : 'v2.1';
		if (isset($_GET['sa']) && $_GET['sa'] == 'remove') {
			checkSession('get');
			if ($version == 'v2.1') {
				//validateToken('admin-tr', 'request');
			}
			$themeID = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
			if ($themeID != 1) {
				$txtKeyHtml = 'bannerBarAlt_' . strval(intval($themeID));
				$txtKeyColor = 'bannerBarColor_' . strval(intval($themeID));
				$txtKeyTxtColor = 'bannerBarTxt_' . strval(intval($themeID));
				$txtKeyWidth = 'bannerBarWidth_' . strval(intval($id_theme));
				$txtKeyHeight = 'bannerBarHeight_' . strval(intval($id_theme));
				$variables = array($txtKeyHtml, $txtKeyColor, $txtKeyTxtColor, $txtKeyWidth, $txtKeyHeight);
				// Remove it from the settings table.
				$smcFunc['db_query']('', '
					DELETE FROM {db_prefix}settings
					WHERE variable IN ({array_string:variables})',
					array(
						'variables' => $variables,
					)
				);
			}
		}
	}
}

function smf_bannerBar_settings($return_config = false)
{
	global $txt, $context, $scripturl, $modSettings, $settings;
	loadLanguage('smf_bannerBar');

	if (!allowedTo('admin_forum'))
		fatal_lang_error('smf_bannerBar_ErrorMessage', false);

	$smf_version = version_compare((!empty($modSettings['smfVersion']) ? substr($modSettings['smfVersion'], 0, 3) : '2.0'), '2.1', '<') ? 'v2.0' : 'v2.1';
	$context['bannerBar_images'] = smf_bannerBar_getImageList('bannerbar');
	clearstatcache();
	$bannerBar_images = $context['bannerBar_images'];
	$opt = array_shift($bannerBar_images);
	$bannerBar_images = json_encode($bannerBar_images);
	$imgArray = array("bannerBar_topLeft", "bannerBar_topRight", "bannerBar_bottomLeft", "bannerBar_bottomRight");
	foreach ($imgArray as $img) {
		$modSettings[$img . 'Path'] = !empty($modSettings[$img . 'Path']) ? $modSettings[$img . 'Path'] : '';
	}

	if ($smf_version == 'v2.1')
	{
		$modSettings['cookieTime'] = 3153600;
		createToken('admin', 'post');
	}

	$config_vars = array(
		'',
		array('check', 'bannerBar_enable'),
		array('check', 'bannerBar_horizontal'),
		array('large_text', 'bannerBar_text', '5'),
		array('large_text', 'bannerBar_css_text', '5'),
		array('large_text', 'bannerBar_actions', '5'),
		'',
		$txt['smf_bannerBarMarqueeSettings'],
		'',
		array('check', 'bannerBar_marquee_enable'),
		array('check', 'bannerBar_marquee_stop'),
		array('select', 'bannerBar_marquee_dir', explode('|', $txt['bannerBar_marquee_directions'])),
		array('int', 'bannerBar_marquee_speed'),
		'',
		array('title', 'smf_bannerBarImages'),
		'',
		array('check', 'bannerBarCorners'),
		array('int', 'bannerBarImageheight'),
		array('int', 'bannerBarImageWidth'),
		array('text', 'bannerBarImageSize'),
		array('select', 'bannerBar_topLeft', $context['bannerBar_images']),
		array('select', 'bannerBar_topRight', $context['bannerBar_images']),
		array('select', 'bannerBar_bottomLeft', $context['bannerBar_images']),
		array('select', 'bannerBar_bottomRight', $context['bannerBar_images']),
		'',
		array('title', 'smf_bannerBarThemeSettings'),
		'',
	);
	list($config_vars_extra, $html_headers) = smf_bannerBar_themeFixAdmin();
	$config_vars = array_merge($config_vars, $config_vars_extra);

	$context['html_headers'] .= '
		<script type="text/javascript">
			function smf_bannerBar_alterAdmin() {
				' . $html_headers . '
				var i = 0, indx, bannerBarIdx, bannerBar_corners = ["bannerBar_topLeft", "bannerBar_topRight", "bannerBar_bottomLeft", "bannerBar_bottomRight"];
				var modSettingsImgs = ["' . $modSettings['bannerBar_topLeftPath'] . '", "' . $modSettings['bannerBar_topRightPath'] . '", "' . $modSettings['bannerBar_bottomLeftPath'] .'", "' . $modSettings['bannerBar_bottomRightPath'] .'"];
				var bannerBarPhpCorners = ' . $bannerBar_images . ', bannerDefault, bannerBar_defaults = ["top-left.png", "top-right.png", "bottom-left.png", "bottom-right.png"];
				for(i=0;i<bannerBar_corners.length;i++) {
					bannerBarIdx = document.getElementById(bannerBar_corners[i]);
					if (isNaN(bannerBarIdx.value) && bannerBarIdx.options[i+1].innerHTML != modSettingsImgs[i]) {
						if (bannerBarPhpCorners.includes(modSettingsImgs[i])) {
							bannerDefault = modSettingsImgs[i];
							indx = bannerBarPhpCorners.indexOf(bannerDefault);
							bannerBarIdx.value = indx > -1 ? indx + 1 : 0;
						}
						else {
							bannerDefault = bannerBar_defaults[i];
							indx = bannerBarPhpCorners.indexOf(bannerDefault);
							bannerBarIdx.value = indx > -1 ? indx + 1 : 0;
						}
					}
					else if (modSettingsImgs[i] == "") {
						bannerDefault = bannerBar_defaults[i];
						indx = bannerBarPhpCorners.indexOf(bannerDefault);
						bannerBarIdx.value = indx > -1 ? indx + 1 : 0;
					}
				}
				var bannerFileInput = document.createElement("input"), bannerTarget = document.getElementById("setting_bannerBar_topLeft"), bannerBar_css_text = document.getElementById("bannerBar_css_text");
				var bannerTargetParent = bannerTarget.closest(".settings"), bannerInsertText = "' . $txt['bannerBar_fileText'] . '";
				var bannerInsertDL = document.createElement("dl"), bannerInsertDT = document.createElement("dt"), bannerInsertDD = document.createElement("dd");
				var bannerBarImageheight = document.getElementById("bannerBarImageheight"), bannerBarImageWidth = document.getElementById("bannerBarImageWidth");
				var bannerBarImageSize = document.getElementById("bannerBarImageSize");
				bannerBarImageSize.value = parseFloat(bannerBarImageSize.value) == "NaN" || parseFloat(bannerBarImageSize.value) < 0 || parseFloat(bannerBarImageSize.value) < 0 > 50 ? 1 : parseFloat(bannerBarImageSize.value);
				bannerBarImageheight.value = parseInt(bannerBarImageheight.value) < 10 ? 14 : parseInt(bannerBarImageheight.value);
				bannerBarImageheight.value > 40 ? 40 : bannerBarImageheight.value;
				bannerBarImageWidth.value = parseInt(bannerBarImageWidth.value) < 10 ? 14 : parseInt(bannerBarImageWidth.value);
				bannerBarImageWidth.value > 40 ? 40 : bannerBarImageWidth.value;
				bannerInsertDL.className = "settings";
				bannerInsertDL.append(bannerInsertDT);
				bannerInsertDL.append(bannerInsertDD);
				bannerInsertDT.innerHTML = bannerInsertText;
				bannerFileInput.type = "file";
				bannerFileInput.name = "bannerFileInput[]";
				bannerFileInput.id = "bannerFileInput";
				bannerFileInput.multiple = "multiple";
				bannerFileInput.accept = "image/gif, image/jpeg, image/png, image/jpg";
				bannerInsertDD.append(bannerFileInput);
				bannerTargetParent.parentNode.prepend(bannerInsertDL);
				document.getElementById("admin_form_wrapper").enctype = "multipart/form-data";' . (isset($_REQUEST['fileTransfer']) && in_array($_REQUEST['fileTransfer'], array('success', 'fail')) ? '
				var bannerAdminForm = document.getElementById("admin_form_wrapper"), bannerInsertDiv1 = document.createElement("DIV"), bannerInsertDiv2 = document.createElement("DIV");
				bannerInsertDiv2.className = "centertext alert";
				bannerInsertDiv2.id = "bannerInsertDiv2";
				bannerInsertDiv1.className = "centertext";
				bannerInsertDiv1.style = "padding: 0em;min-height: 2em;height: 2em;";
				bannerInsertDiv2.style = "font-size: x-large;display: inline;";
				bannerInsertDiv2.innerHTML = "' . $txt['bannerBar_fileTransfer_' . $_REQUEST['fileTransfer']] . '";
				bannerInsertDiv1.append(bannerInsertDiv2);
				bannerAdminForm.prepend(bannerInsertDiv1);
				if (bannerBar_css_text && bannerBar_css_text.value) {
					var reg = /^([A-Za-z\-]+?:\s*?[0-9A-Za-z\-%]+?;\s*?)*?$/;
					if (!reg.test(bannerBar_css_text.value)) {
						bannerBar_css_text.value = "";
					}
				}
				setTimeout(function(){
					document.getElementById("bannerInsertDiv2").style = "display: none;";
				}, 5000);
				' : '') . '
			}
			if (window.addEventListener)
				window.addEventListener("load", smf_bannerBar_alterAdmin, false);
			else if (window.attachEvent)
				window.attachEvent("onload", smf_bannerBar_alterAdmin);
		</script>';
	// ^([A-Za-z\-]+?:\s*?[0-9A-Za-z\-%]+?;\s*?)*?$
	if ($return_config)
		return $config_vars;

	if (empty($config_vars))
	{
		$context['settings_save_dont_show'] = true;
		$context['settings_message'] = '<div style="text-align: center">' . $txt['modification_no_misc_settings'] . '</div>';

		return prepareDBSettingContext($config_vars);
	}

	if (isset($_GET['save']))
	{
		if (isset($_FILES) && isset($_FILES['bannerFileInput'])) {
			$height = !empty($modSettings['bannerBarImageheight']) ? intval($modSettings['bannerBarImageheight']) : 14;
			$width = !empty($modSettings['bannerBarImageWidth']) ? intval($modSettings['bannerBarImageWidth']) : 14;
			$height = $height < 10 || $height > 40 ? 14 : $height;
			$width = $width < 10 || $width > 40 ? 14 : $width;
			$files = array_filter($_FILES['bannerFileInput']['name']);
			$total_count = count($_FILES['bannerFileInput']['name']);
			$success = false;
			for($i=0 ; $i < $total_count ; $i++) {
				$tmpFilePath = $_FILES['bannerFileInput']['tmp_name'][$i];
				if ($tmpFilePath != ""){
					$newFilePath = $settings['default_theme_dir'] . '/images/bannerbar/' . basename($_FILES['bannerFileInput']['name'][$i]);
					if(move_uploaded_file($tmpFilePath, $newFilePath)) {
						$success = true;
						clearstatcache($newFilePath);
						@chmod($newFilePath, 0666);
						smf_bannerBar_imageResize($newFilePath, $newFilePath, $width, $height, 0);
					}
				}
			}
			if (!empty($success)) {
				redirectexit($scripturl . '?action=admin;area=modsettings;sa=bannerBar;fileTransfer=success');
			}
			//redirectexit($scripturl . '?action=admin;area=modsettings;sa=bannerBar;fileTransfer=fail');
		}

		$addConfigVars = array();
		foreach ($imgArray as $img) {
			$_POST[$img . 'Path'] = isset($_POST[$img]) && $_POST[$img] != 0 ? $context['bannerBar_images'][$_POST[$img]] : '';
			$addConfigVars[] = array('text', $img . 'Path', '5');
		}
		$config_vars = array_merge($config_vars, $addConfigVars);
		if (isset($_POST['bannerBar_marquee_speed'])) {
			$_POST['bannerBar_marquee_speed'] = intval($_POST['bannerBar_marquee_speed']);
			$_POST['bannerBar_marquee_speed'] = $_POST['bannerBar_marquee_speed'] < 5 ? 20 : ($_POST['bannerBar_marquee_speed'] > 50 ? 50 : $_POST['bannerBar_marquee_speed']);
		}
		if (isset($_POST['bannerBarImageSize'])) {
			$_POST['bannerBarImageSize'] = preg_replace("/[^0-9.]+/", "", $_POST['bannerBarImageSize']);
			$_POST['bannerBarImageSize'] = $_POST['bannerBarImageSize'] > 50 || $_POST['bannerBarImageSize'] < 0 ? 1 : round($_POST['bannerBarImageSize'], 2);
		}
		if (isset($_POST['bannerBar_actions'])) {
			$_POST['bannerBar_actions'] = preg_replace('/\s/', '', $_POST['bannerBar_actions']);
			$_POST['bannerBar_actions'] = preg_replace('/[^A-Za-z0-9,_~|]/', '', $_POST['bannerBar_actions']);
			$_POST['bannerBar_actions'] = str_replace(',', ', ', $_POST['bannerBar_actions']);
		}
		if (isset($_POST['bannerBar_css_text'])) {
			$_POST['bannerBar_css_text'] = strtolower($_POST['bannerBar_css_text']);
			$_POST['bannerBar_css_text'] = preg_replace('!\s+!', ' ', $_POST['bannerBar_css_text']);
			$_POST['bannerBar_css_text'] = preg_replace("/[^0-9a-z.:;\-_{} \n\r]+/", "", $_POST['bannerBar_css_text']);
			$_POST['bannerBar_css_text'] = str_replace('}', '}' . chr(13), ' ' . trim($_POST['bannerBar_css_text']));
		}
		smf_bannerBar_themeFixAdminSave();
		checkSession();
		saveDBSettings($config_vars);
		writeLog();
		redirectexit($scripturl . '?action=admin;area=modsettings;sa=bannerBar');
	}

	$context['post_url'] = $scripturl . '?action=admin;area=modsettings;save;sa=bannerBar';
	$context['page_title'] = $txt['smf_bannerBar_title'] . ' - ' . $txt['settings'];
	$context['settings_title'] = $txt['smf_bannerBar_title'] . ' - ' . $txt['settings'];
	$context['sub_template'] = 'show_settings';

	prepareDBSettingContext($config_vars);
}

function smf_bannerBar_imageResize($src, $dst, $width, $height, $crop=0)
{
	if(!list($w, $h) = getimagesize($src))
		return false;

	$type = strtolower(substr(strrchr($src,"."),1));
	$type = $type == 'jpeg' ? 'jpg' : $type;

	if (!in_array($type, array('gif', 'jpg', 'png')))
		return false;

	switch($type)
	{
		case 'gif':
			$img = imagecreatefromgif($src);
			break;
		case 'png':
			$img = imagecreatefrompng($src);
			break;
		default:
			$img = imagecreatefromjpeg($src);
	}

	if($crop)
	{
		if($w < $width or $h < $height)
			return false;
		$ratio = max($width/$w, $height/$h);
		$h = $height / $ratio;
		$x = ($w - $width / $ratio) / 2;
		$w = $width / $ratio;
	}
	else
	{
		if($w < $width and $h < $height)
			return false;
		$ratio = min($width/$w, $height/$h);
		$width = $w * $ratio;
		$height = $h * $ratio;
		$x = 0;
	}

	$new = imagecreatetruecolor($width, $height);

	imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
	imagealphablending($new, false);
	imagesavealpha($new, true);
	imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);

	switch($type)
	{
		case 'gif':
			imagegif($new, $dst);
			break;
		case 'png':
			imagepng($new, $dst);
			break;
		default:
			imagejpeg($new, $dst);
	}

	return true;
}

function smf_bannerBar_themeIds($themedir = '')
{
	global $boarddir;
	$ids = array();
	$themedir = trim(basename($themedir));
	$themedir = $boarddir . '/Themes/' . preg_replace('~[^A-Za-z0-9 _/.\-]~', '', $themedir);
	if(!empty($themedir) && file_exists($themedir . '/index.template.php')) {
		$html = file_get_contents($themedir . '/index.template.php');
		$doc = new DOMDocument();
		libxml_use_internal_errors(true);
		$doc->loadHTML($html);
		$xpath = new DOMXpath($doc);
		$divs = $xpath->query('//div[@id]');
		foreach ($divs as $div) {
			$matches = [$div->getAttribute('id')];
			if (strpos($matches[0], '$') === FALSE && stripos($matches[0], 'errors') === FALSE)
				$ids[] = $matches[0];
		}
	}
	return $ids;
}

function smf_bannerBar_themeFixAdmin()
{
	global $smcFunc, $modSettings, $context, $txt;

	list($html_headers, $themeArray, $available_themes, $x, $bannerBarAltVal, $bannerBarCssVal) = array('', array(), array(), 0, 'content_section', '1rem 0.5rem 1rem 0.5rem');
	$request = $smcFunc['db_query']('', '
		SELECT id_theme, variable, value
		FROM {db_prefix}themes
		WHERE variable IN ({string:name}, {string:theme_url}, {string:theme_dir}, {string:images_url})
			AND id_theme IN ({array_string:known_themes})
			AND id_theme != {int:default_theme}',
		array(
			'default_theme' => 0,
			'name' => 'name',
			'theme_url' => 'theme_url',
			'theme_dir' => 'theme_dir',
			'images_url' => 'images_url',
			'known_themes' => explode(',', $modSettings['knownThemes']),
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$available_themes[$row['id_theme']][$row['variable']] = $row['value'];
	}
	$smcFunc['db_free_result']($request);
	ksort($available_themes);
	$context['html_headers'] .= '
		<script type="text/javascript">
			function bannerBarSaveFunc() {';
	foreach ($available_themes as $id_theme => $theme_data)
	{
		list($bannerBarAltVal, $bannerBarCssVal) = smf_bannerBar_themeDefaults($theme_data['name']);
		$theme_ids = array();
		$onclickId = '<span class="bannerBarAltDiv" onclick="bannerBarAltText(' . $id_theme . ', \'' . $bannerBarAltVal . '\')">' . sprintf($txt['bannerBarAltText'], '<span class="bannerBarAltText">' . $bannerBarAltVal . '</span>') . '</span>';
		$onclickCss = '<span class="bannerBarAltDiv" onclick="bannerBarCssText(' . $id_theme . ', \'' . $bannerBarCssVal . '\')">' . sprintf($txt['bannerBarAltText'], '<span class="bannerBarAltText">' . $bannerBarCssVal . '</span>') . '</span>';
		$themeArray[] = $theme_data['name'];
		$themeArray[] = '';
		$txtKeyContainer = 'bannerBarContainer_' . strval(intval($id_theme));
		$txtKeyAlt = 'bannerBarAlt_' . strval(intval($id_theme));
		$txtKeyCss = 'bannerBarCss_' . strval(intval($id_theme));
		$txtKeyColor = 'bannerBarColor_' . strval(intval($id_theme));
		$txtKeyTxtColor = 'bannerBarTxt_' . strval(intval($id_theme));
		$txtKeyWidth = 'bannerBarWidth_' . strval(intval($id_theme));
		$txtKeyHeight = 'bannerBarHeight_' . strval(intval($id_theme));

		$txt[$txtKeyContainer] = $txt['bannerBarContainerType'];
		$txt[$txtKeyAlt] = $txt['smf_bannerBarThemeSelect'];
		$txt[$txtKeyCss] = $txt['smf_bannerBarThemeOuterCSS'];
		$txt[$txtKeyColor] = $txt['smf_bannerBarThemeBG'];
		$txt[$txtKeyTxtColor] = $txt['smf_bannerBarThemeText'];
		$txt[$txtKeyWidth] = $txt['bannerBarContainerWidth'];
		$txt[$txtKeyHeight] = $txt['bannerBarContainerHeight'];

		$html_headers.= '
				var ' . $txtKeyWidth . ' = document.getElementById("' . $txtKeyWidth . '");
				var ' . $txtKeyHeight . ' = document.getElementById("' . $txtKeyHeight . '");
				' . $txtKeyHeight . '.value = parseFloat(' . $txtKeyHeight . '.value) == "NaN" || parseFloat(' . $txtKeyHeight . '.value) == 0 ? 3 : parseFloat(' . $txtKeyHeight . '.value);
				' . $txtKeyWidth . '.value = ' . $txtKeyWidth . '.value == 0 ? 100 : ' . $txtKeyWidth . '.value;';
		if (!empty($theme_data['theme_dir'])) {
			$theme_ids[] = $txt['bannerBarSelect'];
			$theme_ids += smf_bannerBar_themeIds($theme_data['theme_dir']);
			$select = $theme_data['name'] . '_' . rand(99, 9999);
			if (!empty($theme_ids) && is_array($theme_ids) && count($theme_ids) > 1) {
				$output = '<select name="' . $select . '" id="' . $select . '" onchange="bannerBarAltText(' . $id_theme . ', this.value)">';
				foreach ($theme_ids as $num => $themeid) {
					if ($num == 0) {
						$output .= '<option value="">' . $themeid . '</option>';
					}
					else {
						$recommended = !empty($bannerBarAltVal) && $bannerBarAltVal == $themeid ? '[ ' . $themeid . ' ]' : $themeid;
						$selected = !empty($modSettings[$txtKeyAlt]) && $themeid == $modSettings[$txtKeyAlt] ? ' selected="selected"' : '';
						$output .= '<option value="' . $themeid . '"' . $selected . '>' . $recommended . '</option>';
					}
				}
				$output .= '</select>';
				$onclickId = '<span class="bannerBarAltDiv">' . sprintf($txt['bannerBarAltText'], '<span class="bannerBarAltText">' . $output . '</span>') . '</span>';
			}
		}
		$themeArray[] = array('text', $txtKeyAlt, 'subtext' => $onclickId);
		$themeArray[] = array('text', $txtKeyCss, 'subtext' => $onclickCss);
		$themeArray[] = array('text', $txtKeyColor, 'subtext' => '<span class="bannerBarAltDiv">' . $txt['smf_bannerBarThemeBGOpt'] . '</span>');
		$themeArray[] = array('text', $txtKeyTxtColor);
		$themeArray[] = array('text', $txtKeyHeight);
		$themeArray[] = array('int', $txtKeyWidth, 8);
		$themeArray[] = array('select', $txtKeyContainer, explode('|', $txt['bannerBarContainer']));
		$context['html_headers'] .= '			
			if (document.getElementById("bannerBarContainer_' . $x . '"))
				document.getElementById("bannerBarContainer_' . $x . '").insertAdjacentHTML("afterend", \'<div style="display: flex;margin-left: auto;justify-content: flex-end;text-align: right:width: 100%;"><input type="submit" value="' . $txt['save'] . '" class="button" /></div>\');';
		$x++;
		if ($x < count($available_themes))
			$themeArray[] = '';
	}
	// document.getElementById("setting_bannerBarContainer_' . $x . '").appendChild(bannerBarLabel' . $x . ');
	$context['html_headers'] .= '
			}
			if (window.addEventListener)
				window.addEventListener("load", bannerBarSaveFunc, false);
			else if (window.attachEvent)
				window.attachEvent("onload", bannerBarSaveFunc);
		</script>';
	return array($themeArray, $html_headers);
}

function smf_bannerBar_themeFixAdminSave()
{
	global $smcFunc, $modSettings, $txt;

	list($themeArray, $available_themes, $x, $bannerBarAltVal, $bannerBarCssVal) = array(array(), array(), 0, 'content_section', '1rem 0.5rem 1rem 0.5rem');
	$request = $smcFunc['db_query']('', '
		SELECT id_theme, variable, value
		FROM {db_prefix}themes
		WHERE variable IN ({string:name}, {string:theme_url}, {string:theme_dir}, {string:images_url})
			AND id_theme IN ({array_string:known_themes})
			AND id_theme != {int:default_theme}',
		array(
			'default_theme' => 0,
			'name' => 'name',
			'theme_url' => 'theme_url',
			'theme_dir' => 'theme_dir',
			'images_url' => 'images_url',
			'known_themes' => explode(',', $modSettings['knownThemes']),
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
		$available_themes[$row['id_theme']][$row['variable']] = $row['value'];

	$smcFunc['db_free_result']($request);
	ksort($available_themes);
	foreach ($available_themes as $id_theme => $theme_data)
	{
		list($bannerBarAltVal, $bannerBarCssVal) = smf_bannerBar_themeDefaults($theme_data['name']);
		if (!empty($theme_data['theme_dir'])) {
			$theme_ids = smf_bannerBar_themeIds($theme_data['theme_dir']);
		}
		$txtKeyCss = 'bannerBarCss_' . strval(intval($id_theme));
		$txtKeyAlt = 'bannerBarAlt_' . strval(intval($id_theme));
		$txtKeyColor = 'bannerBarColor_' . strval(intval($id_theme));
		$txtKeyTxtColor = 'bannerBarTxt_' . strval(intval($id_theme));
		$txtKeyWidth = 'bannerBarWidth_' . strval(intval($id_theme));
		$txtKeyHeight = 'bannerBarHeight_' . strval(intval($id_theme));
		if (isset($_POST[$txtKeyAlt])) {
			$_POST[$txtKeyAlt] = preg_replace("/[^a-zA-Z0-9_]+/", "", $_POST[$txtKeyAlt]);
			$_POST[$txtKeyAlt] = !preg_match("/^\d+$/", $_POST[$txtKeyAlt]) ? $_POST[$txtKeyAlt] : $bannerBarAltVal;
		}
		if (isset($_POST[$txtKeyCss])) {
			$_POST[$txtKeyCss] = preg_replace("/[^a-zA-Z0-9 .]+/", "", $_POST[$txtKeyCss]);
			$_POST[$txtKeyCss] = str_replace('padding', '', $_POST[$txtKeyCss]);
			$_POST[$txtKeyCss] = !preg_match("/^\d+$/", $_POST[$txtKeyCss]) ? $_POST[$txtKeyCss] : $bannerBarCssVal;
		}
		if (isset($_POST[$txtKeyWidth])) {
			$_POST[$txtKeyWidth] = preg_replace("/[^0-9.]+/", "", $_POST[$txtKeyWidth]);
			$_POST[$txtKeyWidth] = $_POST[$txtKeyWidth] > 100 || $_POST[$txtKeyWidth] < 1 ? 100 : intval($_POST[$txtKeyWidth]);
		}
		if (isset($_POST[$txtKeyHeight])) {
			$_POST[$txtKeyHeight] = preg_replace("/[^0-9.]+/", "", $_POST[$txtKeyHeight]);
			$_POST[$txtKeyHeight] = $_POST[$txtKeyHeight] > 100 || $_POST[$txtKeyHeight] < 0 ? 3 : round($_POST[$txtKeyHeight], 2);
		}
		foreach (array($txtKeyColor, $txtKeyTxtColor) as $mySetting) {
			if (isset($_POST[$mySetting]))
				$_POST[$mySetting] = smf_bannerBar_colorBarFilter($_POST[$mySetting]);
		}
	}
}

function smf_bannerBar_themeDefaults($themeNameOrig = '')
{
	// this default list may increase with the next release
	list($themeName, $bannerBarAltVal, $bannerBarCssVal) = array(strtolower($themeNameOrig), 'content_section', '1rem 0.5rem 1rem 0.5rem');
	switch ($themeName) {
		case 'core theme':
			$bannerBarAltVal = 'bodyarea';
			$bannerBarCssVal = '1rem 0.2rem 1rem 0.2rem';
			break;
		case 'lamartine':
			$bannerBarAltVal = 'mainarea';
			$bannerBarCssVal = '2rem 0.2rem 0rem 0.2rem';
			break;
		case 'smf default theme - curve2':
			$bannerBarAltVal = 'content_section';
			$bannerBarCssVal = '1rem 0.5rem 1rem 0.5rem';
			break;
		case 'smf default theme':
			$bannerBarAltVal = 'main_content_section';
			$bannerBarCssVal = '1rem 0.5rem 1rem 0.5rem';
			break;
		default:
			$bannerBarAltVal = 'content_section';
			$bannerBarCssVal = '1rem 0.2rem 1rem 0.2rem';
	}

	return array($bannerBarAltVal, $bannerBarCssVal);
}

function smf_bannerBar_getImageList($directory = 'bannerbar')
{
	global $settings, $txt;

	// Start with an empty array
	list($files, $imageList, $imageTypes) = array(array(), array(0 => $txt['bannerBarOptImage']), array('.gif', '.jpg', '.jpeg', '.png'));
	$dirpath = $settings['default_theme_dir'] . '/' . basename($settings['default_images_url']) . '/' . $directory . '/*.*';

	// Try to open the images directory
	$files = glob($dirpath);

	// sort files by last modified date
	usort($files, function($x, $y) {
		return filemtime($x) > filemtime($y);
	});
	foreach($files as $file) {
		$fileName = basename($file);
		if (!in_array($fileName, array('.', '..', 'blank.gif', 'index.php')) && smf_bannerBar_strpos($fileName, $imageTypes, 1)) {
			$pathInfo = pathinfo($fileName);
			$pathInfoFile = preg_replace('/[^a-zA-Z0-9\-\_]/', '', (string)$pathInfo['filename']);
			$imageList[] = $fileName;
			//$txt[$pathInfoFile] = $fileName;
		}
	}

	if (!empty($imageList))
		return $imageList;
	else
		fatal_lang_error('bannerBar_cannot_open_images');

}

function smf_bannerBar_strpos($haystack, $needles=array(), $offset=0)
{
        $chars = array();
        foreach($needles as $needle)
	{
                $search = strpos($haystack, $needle, $offset);
                if ($search !== false)
			$chars[$needle] = $search;
        }
        if(empty($chars))
		return false;

        return min($chars);
}

function smf_bannerBar_helpText()
{
	global $helptxt, $txt;
	loadLanguage('smf_bannerBarHelp');
}

?>