PageRenderTime 71ms CodeModel.GetById 10ms app.highlight 47ms RepoModel.GetById 1ms app.codeStats 1ms

/Sources/Themes.php

https://github.com/smf-portal/SMF2.1
PHP | 2205 lines | 1680 code | 290 blank | 235 comment | 301 complexity | a85326323e5855469529713800af28aa MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2
   3/**
   4 * This file concerns itself almost completely with theme administration.
   5 * Its tasks include changing theme settings, installing and removing
   6 * themes, choosing the current theme, and editing themes.
   7 *
   8 * @todo Update this for the new package manager?
   9 *
  10 * Creating and distributing theme packages:
  11 * 	There isn't that much required to package and distribute your own themes...
  12 * just do the following:
  13 * - create a theme_info.xml file, with the root element theme-info.
  14 * - its name should go in a name element, just like description.
  15 * - your name should go in author. (email in the email attribute.)
  16 * - any support website for the theme should be in website.
  17 * - layers and templates (non-default) should go in those elements ;).
  18 * - if the images dir isn't images, specify in the images element.
  19 * - any extra rows for themes should go in extra, serialized. (as in array(variable => value).)
  20 * - tar and gzip the directory - and you're done!
  21 * - please include any special license in a license.txt file.
  22 *
  23 * Simple Machines Forum (SMF)
  24 *
  25 * @package SMF
  26 * @author Simple Machines http://www.simplemachines.org
  27 * @copyright 2012 Simple Machines
  28 * @license http://www.simplemachines.org/about/smf/license.php BSD
  29 *
  30 * @version 2.1 Alpha 1
  31 */
  32
  33if (!defined('SMF'))
  34	die('Hacking attempt...');
  35
  36/**
  37 * Subaction handler - manages the action and delegates control to the proper
  38 * sub-action.
  39 * It loads both the Themes and Settings language files.
  40 * Checks the session by GET or POST to verify the sent data.
  41 * Requires the user not be a guest. (@todo what?)
  42 * Accessed via ?action=admin;area=theme.
  43 */
  44function ThemesMain()
  45{
  46	global $txt, $context, $scripturl;
  47
  48	// Load the important language files...
  49	loadLanguage('Themes');
  50	loadLanguage('Settings');
  51
  52	// No funny business - guests only.
  53	is_not_guest();
  54
  55	// Default the page title to Theme Administration by default.
  56	$context['page_title'] = $txt['themeadmin_title'];
  57
  58	// Theme administration, removal, choice, or installation...
  59	$subActions = array(
  60		'admin' => 'ThemeAdmin',
  61		'list' => 'ThemeList',
  62		'reset' => 'SetThemeOptions',
  63		'options' => 'SetThemeOptions',
  64		'install' => 'ThemeInstall',
  65		'remove' => 'RemoveTheme',
  66		'pick' => 'PickTheme',
  67		'edit' => 'EditTheme',
  68		'copy' => 'CopyTemplate',
  69	);
  70
  71	// @todo Layout Settings?
  72	if (!empty($context['admin_menu_name']))
  73	{
  74		$context[$context['admin_menu_name']]['tab_data'] = array(
  75			'title' => $txt['themeadmin_title'],
  76			'help' => 'themes',
  77			'description' => $txt['themeadmin_description'],
  78			'tabs' => array(
  79				'admin' => array(
  80					'description' => $txt['themeadmin_admin_desc'],
  81				),
  82				'list' => array(
  83					'description' => $txt['themeadmin_list_desc'],
  84				),
  85				'reset' => array(
  86					'description' => $txt['themeadmin_reset_desc'],
  87				),
  88				'edit' => array(
  89					'description' => $txt['themeadmin_edit_desc'],
  90				),
  91			),
  92		);
  93	}
  94
  95	// Follow the sa or just go to administration.
  96	if (isset($_GET['sa']) && !empty($subActions[$_GET['sa']]))
  97		$subActions[$_GET['sa']]();
  98	else
  99		$subActions['admin']();
 100}
 101
 102/**
 103 * This function allows administration of themes and their settings,
 104 * as well as global theme settings.
 105 *  - sets the settings theme_allow, theme_guests, and knownThemes.
 106 *  - requires the admin_forum permission.
 107 *  - accessed with ?action=admin;area=theme;sa=admin.
 108 *
 109 *  @uses Themes template
 110 *  @uses Admin language file
 111 */
 112function ThemeAdmin()
 113{
 114	global $context, $boarddir, $modSettings, $smcFunc;
 115
 116	loadLanguage('Admin');
 117	isAllowedTo('admin_forum');
 118
 119	// If we aren't submitting - that is, if we are about to...
 120	if (!isset($_POST['save']))
 121	{
 122		loadTemplate('Themes');
 123
 124		// Make our known themes a little easier to work with.
 125		$knownThemes = !empty($modSettings['knownThemes']) ? explode(',',$modSettings['knownThemes']) : array();
 126
 127		// Load up all the themes.
 128		$request = $smcFunc['db_query']('', '
 129			SELECT id_theme, value AS name
 130			FROM {db_prefix}themes
 131			WHERE variable = {string:name}
 132				AND id_member = {int:no_member}
 133			ORDER BY id_theme',
 134			array(
 135				'no_member' => 0,
 136				'name' => 'name',
 137			)
 138		);
 139		$context['themes'] = array();
 140		while ($row = $smcFunc['db_fetch_assoc']($request))
 141			$context['themes'][] = array(
 142				'id' => $row['id_theme'],
 143				'name' => $row['name'],
 144				'known' => in_array($row['id_theme'], $knownThemes),
 145			);
 146		$smcFunc['db_free_result']($request);
 147
 148		// Can we create a new theme?
 149		$context['can_create_new'] = is_writable($boarddir . '/Themes');
 150		$context['new_theme_dir'] = substr(realpath($boarddir . '/Themes/default'), 0, -7);
 151
 152		// Look for a non existent theme directory. (ie theme87.)
 153		$theme_dir = $boarddir . '/Themes/theme';
 154		$i = 1;
 155		while (file_exists($theme_dir . $i))
 156			$i++;
 157		$context['new_theme_name'] = 'theme' . $i;
 158
 159		createToken('admin-tm');
 160	}
 161	else
 162	{
 163		checkSession();
 164		validateToken('admin-tm');
 165
 166		if (isset($_POST['options']['known_themes']))
 167			foreach ($_POST['options']['known_themes'] as $key => $id)
 168				$_POST['options']['known_themes'][$key] = (int) $id;
 169		else
 170			fatal_lang_error('themes_none_selectable', false);
 171
 172		if (!in_array($_POST['options']['theme_guests'], $_POST['options']['known_themes']))
 173				fatal_lang_error('themes_default_selectable', false);
 174
 175		// Commit the new settings.
 176		updateSettings(array(
 177			'theme_allow' => $_POST['options']['theme_allow'],
 178			'theme_guests' => $_POST['options']['theme_guests'],
 179			'knownThemes' => implode(',', $_POST['options']['known_themes']),
 180		));
 181		if ((int) $_POST['theme_reset'] == 0 || in_array($_POST['theme_reset'], $_POST['options']['known_themes']))
 182			updateMemberData(null, array('id_theme' => (int) $_POST['theme_reset']));
 183
 184		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=admin');
 185	}
 186}
 187
 188/**
 189 * This function lists the available themes and provides an interface to reset
 190 * the paths of all the installed themes.
 191 */
 192function ThemeList()
 193{
 194	global $context, $boarddir, $boardurl, $smcFunc;
 195
 196	loadLanguage('Admin');
 197	isAllowedTo('admin_forum');
 198
 199	if (isset($_REQUEST['th']))
 200		return SetThemeSettings();
 201
 202	if (isset($_POST['save']))
 203	{
 204		checkSession();
 205		validateToken('admin-tl');
 206
 207		$request = $smcFunc['db_query']('', '
 208			SELECT id_theme, variable, value
 209			FROM {db_prefix}themes
 210			WHERE variable IN ({string:theme_dir}, {string:theme_url}, {string:images_url}, {string:base_theme_dir}, {string:base_theme_url}, {string:base_images_url})
 211				AND id_member = {int:no_member}',
 212			array(
 213				'no_member' => 0,
 214				'theme_dir' => 'theme_dir',
 215				'theme_url' => 'theme_url',
 216				'images_url' => 'images_url',
 217				'base_theme_dir' => 'base_theme_dir',
 218				'base_theme_url' => 'base_theme_url',
 219				'base_images_url' => 'base_images_url',
 220			)
 221		);
 222		$themes = array();
 223		while ($row = $smcFunc['db_fetch_assoc']($request))
 224			$themes[$row['id_theme']][$row['variable']] = $row['value'];
 225		$smcFunc['db_free_result']($request);
 226
 227		$setValues = array();
 228		foreach ($themes as $id => $theme)
 229		{
 230			if (file_exists($_POST['reset_dir'] . '/' . basename($theme['theme_dir'])))
 231			{
 232				$setValues[] = array($id, 0, 'theme_dir', realpath($_POST['reset_dir'] . '/' . basename($theme['theme_dir'])));
 233				$setValues[] = array($id, 0, 'theme_url', $_POST['reset_url'] . '/' . basename($theme['theme_dir']));
 234				$setValues[] = array($id, 0, 'images_url', $_POST['reset_url'] . '/' . basename($theme['theme_dir']) . '/' . basename($theme['images_url']));
 235			}
 236
 237			if (isset($theme['base_theme_dir']) && file_exists($_POST['reset_dir'] . '/' . basename($theme['base_theme_dir'])))
 238			{
 239				$setValues[] = array($id, 0, 'base_theme_dir', realpath($_POST['reset_dir'] . '/' . basename($theme['base_theme_dir'])));
 240				$setValues[] = array($id, 0, 'base_theme_url', $_POST['reset_url'] . '/' . basename($theme['base_theme_dir']));
 241				$setValues[] = array($id, 0, 'base_images_url', $_POST['reset_url'] . '/' . basename($theme['base_theme_dir']) . '/' . basename($theme['base_images_url']));
 242			}
 243
 244			cache_put_data('theme_settings-' . $id, null, 90);
 245		}
 246
 247		if (!empty($setValues))
 248		{
 249			$smcFunc['db_insert']('replace',
 250				'{db_prefix}themes',
 251				array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
 252				$setValues,
 253				array('id_theme', 'variable', 'id_member')
 254			);
 255		}
 256
 257		redirectexit('action=admin;area=theme;sa=list;' . $context['session_var'] . '=' . $context['session_id']);
 258	}
 259
 260	loadTemplate('Themes');
 261
 262	$request = $smcFunc['db_query']('', '
 263		SELECT id_theme, variable, value
 264		FROM {db_prefix}themes
 265		WHERE variable IN ({string:name}, {string:theme_dir}, {string:theme_url}, {string:images_url})
 266			AND id_member = {int:no_member}',
 267		array(
 268			'no_member' => 0,
 269			'name' => 'name',
 270			'theme_dir' => 'theme_dir',
 271			'theme_url' => 'theme_url',
 272			'images_url' => 'images_url',
 273		)
 274	);
 275	$context['themes'] = array();
 276	while ($row = $smcFunc['db_fetch_assoc']($request))
 277	{
 278		if (!isset($context['themes'][$row['id_theme']]))
 279			$context['themes'][$row['id_theme']] = array(
 280				'id' => $row['id_theme'],
 281			);
 282		$context['themes'][$row['id_theme']][$row['variable']] = $row['value'];
 283	}
 284	$smcFunc['db_free_result']($request);
 285
 286	foreach ($context['themes'] as $i => $theme)
 287	{
 288		$context['themes'][$i]['theme_dir'] = realpath($context['themes'][$i]['theme_dir']);
 289
 290		if (file_exists($context['themes'][$i]['theme_dir'] . '/index.template.php'))
 291		{
 292			// Fetch the header... a good 256 bytes should be more than enough.
 293			$fp = fopen($context['themes'][$i]['theme_dir'] . '/index.template.php', 'rb');
 294			$header = fread($fp, 256);
 295			fclose($fp);
 296
 297			// Can we find a version comment, at all?
 298			if (preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $header, $match) == 1)
 299				$context['themes'][$i]['version'] = $match[1];
 300		}
 301
 302		$context['themes'][$i]['valid_path'] = file_exists($context['themes'][$i]['theme_dir']) && is_dir($context['themes'][$i]['theme_dir']);
 303	}
 304
 305	$context['reset_dir'] = realpath($boarddir . '/Themes');
 306	$context['reset_url'] = $boardurl . '/Themes';
 307
 308	$context['sub_template'] = 'list_themes';
 309	createToken('admin-tl');
 310	createToken('admin-tr', 'request');
 311}
 312
 313/**
 314 * Administrative global settings.
 315 */
 316function SetThemeOptions()
 317{
 318	global $txt, $context, $settings, $modSettings, $smcFunc;
 319
 320	$_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (isset($_GET['id']) ? (int) $_GET['id'] : 0);
 321
 322	isAllowedTo('admin_forum');
 323
 324	if (empty($_GET['th']) && empty($_GET['id']))
 325	{
 326		$request = $smcFunc['db_query']('', '
 327			SELECT id_theme, variable, value
 328			FROM {db_prefix}themes
 329			WHERE variable IN ({string:name}, {string:theme_dir})
 330				AND id_member = {int:no_member}',
 331			array(
 332				'no_member' => 0,
 333				'name' => 'name',
 334				'theme_dir' => 'theme_dir',
 335			)
 336		);
 337		$context['themes'] = array();
 338		while ($row = $smcFunc['db_fetch_assoc']($request))
 339		{
 340			if (!isset($context['themes'][$row['id_theme']]))
 341				$context['themes'][$row['id_theme']] = array(
 342					'id' => $row['id_theme'],
 343					'num_default_options' => 0,
 344					'num_members' => 0,
 345				);
 346			$context['themes'][$row['id_theme']][$row['variable']] = $row['value'];
 347		}
 348		$smcFunc['db_free_result']($request);
 349
 350		$request = $smcFunc['db_query']('', '
 351			SELECT id_theme, COUNT(*) AS value
 352			FROM {db_prefix}themes
 353			WHERE id_member = {int:guest_member}
 354			GROUP BY id_theme',
 355			array(
 356				'guest_member' => -1,
 357			)
 358		);
 359		while ($row = $smcFunc['db_fetch_assoc']($request))
 360			$context['themes'][$row['id_theme']]['num_default_options'] = $row['value'];
 361		$smcFunc['db_free_result']($request);
 362
 363		// Need to make sure we don't do custom fields.
 364		$request = $smcFunc['db_query']('', '
 365			SELECT col_name
 366			FROM {db_prefix}custom_fields',
 367			array(
 368			)
 369		);
 370		$customFields = array();
 371		while ($row = $smcFunc['db_fetch_assoc']($request))
 372			$customFields[] = $row['col_name'];
 373		$smcFunc['db_free_result']($request);
 374		$customFieldsQuery = empty($customFields) ? '' : ('AND variable NOT IN ({array_string:custom_fields})');
 375
 376		$request = $smcFunc['db_query']('themes_count', '
 377			SELECT COUNT(DISTINCT id_member) AS value, id_theme
 378			FROM {db_prefix}themes
 379			WHERE id_member > {int:no_member}
 380				' . $customFieldsQuery . '
 381			GROUP BY id_theme',
 382			array(
 383				'no_member' => 0,
 384				'custom_fields' => empty($customFields) ? array() : $customFields,
 385			)
 386		);
 387		while ($row = $smcFunc['db_fetch_assoc']($request))
 388			$context['themes'][$row['id_theme']]['num_members'] = $row['value'];
 389		$smcFunc['db_free_result']($request);
 390
 391		// There has to be a Settings template!
 392		foreach ($context['themes'] as $k => $v)
 393			if (empty($v['theme_dir']) || (!file_exists($v['theme_dir'] . '/Settings.template.php') && empty($v['num_members'])))
 394				unset($context['themes'][$k]);
 395
 396		loadTemplate('Themes');
 397		$context['sub_template'] = 'reset_list';
 398
 399		createToken('admin-stor', 'request');
 400		return;
 401	}
 402
 403	// Submit?
 404	if (isset($_POST['submit']) && empty($_POST['who']))
 405	{
 406		checkSession();
 407		validateToken('admin-sto');
 408
 409		if (empty($_POST['options']))
 410			$_POST['options'] = array();
 411		if (empty($_POST['default_options']))
 412			$_POST['default_options'] = array();
 413
 414		// Set up the sql query.
 415		$setValues = array();
 416
 417		foreach ($_POST['options'] as $opt => $val)
 418			$setValues[] = array(-1, $_GET['th'], $opt, is_array($val) ? implode(',', $val) : $val);
 419
 420		$old_settings = array();
 421		foreach ($_POST['default_options'] as $opt => $val)
 422		{
 423			$old_settings[] = $opt;
 424
 425			$setValues[] = array(-1, 1, $opt, is_array($val) ? implode(',', $val) : $val);
 426		}
 427
 428		// If we're actually inserting something..
 429		if (!empty($setValues))
 430		{
 431			// Are there options in non-default themes set that should be cleared?
 432			if (!empty($old_settings))
 433				$smcFunc['db_query']('', '
 434					DELETE FROM {db_prefix}themes
 435					WHERE id_theme != {int:default_theme}
 436						AND id_member = {int:guest_member}
 437						AND variable IN ({array_string:old_settings})',
 438					array(
 439						'default_theme' => 1,
 440						'guest_member' => -1,
 441						'old_settings' => $old_settings,
 442					)
 443				);
 444
 445			$smcFunc['db_insert']('replace',
 446				'{db_prefix}themes',
 447				array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
 448				$setValues,
 449				array('id_theme', 'variable', 'id_member')
 450			);
 451		}
 452
 453		cache_put_data('theme_settings-' . $_GET['th'], null, 90);
 454		cache_put_data('theme_settings-1', null, 90);
 455
 456		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
 457	}
 458	elseif (isset($_POST['submit']) && $_POST['who'] == 1)
 459	{
 460		checkSession();
 461		validateToken('admin-sto');
 462
 463		$_POST['options'] = empty($_POST['options']) ? array() : $_POST['options'];
 464		$_POST['options_master'] = empty($_POST['options_master']) ? array() : $_POST['options_master'];
 465		$_POST['default_options'] = empty($_POST['default_options']) ? array() : $_POST['default_options'];
 466		$_POST['default_options_master'] = empty($_POST['default_options_master']) ? array() : $_POST['default_options_master'];
 467
 468		$old_settings = array();
 469		foreach ($_POST['default_options'] as $opt => $val)
 470		{
 471			if ($_POST['default_options_master'][$opt] == 0)
 472				continue;
 473			elseif ($_POST['default_options_master'][$opt] == 1)
 474			{
 475				// Delete then insert for ease of database compatibility!
 476				$smcFunc['db_query']('substring', '
 477					DELETE FROM {db_prefix}themes
 478					WHERE id_theme = {int:default_theme}
 479						AND id_member != {int:no_member}
 480						AND variable = SUBSTRING({string:option}, 1, 255)',
 481					array(
 482						'default_theme' => 1,
 483						'no_member' => 0,
 484						'option' => $opt,
 485					)
 486				);
 487				$smcFunc['db_query']('substring', '
 488					INSERT INTO {db_prefix}themes
 489						(id_member, id_theme, variable, value)
 490					SELECT id_member, 1, SUBSTRING({string:option}, 1, 255), SUBSTRING({string:value}, 1, 65534)
 491					FROM {db_prefix}members',
 492					array(
 493						'option' => $opt,
 494						'value' => (is_array($val) ? implode(',', $val) : $val),
 495					)
 496				);
 497
 498				$old_settings[] = $opt;
 499			}
 500			elseif ($_POST['default_options_master'][$opt] == 2)
 501			{
 502				$smcFunc['db_query']('', '
 503					DELETE FROM {db_prefix}themes
 504					WHERE variable = {string:option_name}
 505						AND id_member > {int:no_member}',
 506					array(
 507						'no_member' => 0,
 508						'option_name' => $opt,
 509					)
 510				);
 511			}
 512		}
 513
 514		// Delete options from other themes.
 515		if (!empty($old_settings))
 516			$smcFunc['db_query']('', '
 517				DELETE FROM {db_prefix}themes
 518				WHERE id_theme != {int:default_theme}
 519					AND id_member > {int:no_member}
 520					AND variable IN ({array_string:old_settings})',
 521				array(
 522					'default_theme' => 1,
 523					'no_member' => 0,
 524					'old_settings' => $old_settings,
 525				)
 526			);
 527
 528		foreach ($_POST['options'] as $opt => $val)
 529		{
 530			if ($_POST['options_master'][$opt] == 0)
 531				continue;
 532			elseif ($_POST['options_master'][$opt] == 1)
 533			{
 534				// Delete then insert for ease of database compatibility - again!
 535				$smcFunc['db_query']('substring', '
 536					DELETE FROM {db_prefix}themes
 537					WHERE id_theme = {int:current_theme}
 538						AND id_member != {int:no_member}
 539						AND variable = SUBSTRING({string:option}, 1, 255)',
 540					array(
 541						'current_theme' => $_GET['th'],
 542						'no_member' => 0,
 543						'option' => $opt,
 544					)
 545				);
 546				$smcFunc['db_query']('substring', '
 547					INSERT INTO {db_prefix}themes
 548						(id_member, id_theme, variable, value)
 549					SELECT id_member, {int:current_theme}, SUBSTRING({string:option}, 1, 255), SUBSTRING({string:value}, 1, 65534)
 550					FROM {db_prefix}members',
 551					array(
 552						'current_theme' => $_GET['th'],
 553						'option' => $opt,
 554						'value' => (is_array($val) ? implode(',', $val) : $val),
 555					)
 556				);
 557			}
 558			elseif ($_POST['options_master'][$opt] == 2)
 559			{
 560				$smcFunc['db_query']('', '
 561					DELETE FROM {db_prefix}themes
 562					WHERE variable = {string:option}
 563						AND id_member > {int:no_member}
 564						AND id_theme = {int:current_theme}',
 565					array(
 566						'no_member' => 0,
 567						'current_theme' => $_GET['th'],
 568						'option' => $opt,
 569					)
 570				);
 571			}
 572		}
 573
 574		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
 575	}
 576	elseif (!empty($_GET['who']) && $_GET['who'] == 2)
 577	{
 578		checkSession('get');
 579		validateToken('admin-stor', 'request');
 580
 581		// Don't delete custom fields!!
 582		if ($_GET['th'] == 1)
 583		{
 584			$request = $smcFunc['db_query']('', '
 585				SELECT col_name
 586				FROM {db_prefix}custom_fields',
 587				array(
 588				)
 589			);
 590			$customFields = array();
 591			while ($row = $smcFunc['db_fetch_assoc']($request))
 592				$customFields[] = $row['col_name'];
 593			$smcFunc['db_free_result']($request);
 594		}
 595		$customFieldsQuery = empty($customFields) ? '' : ('AND variable NOT IN ({array_string:custom_fields})');
 596
 597		$smcFunc['db_query']('', '
 598			DELETE FROM {db_prefix}themes
 599			WHERE id_member > {int:no_member}
 600				AND id_theme = {int:current_theme}
 601				' . $customFieldsQuery,
 602			array(
 603				'no_member' => 0,
 604				'current_theme' => $_GET['th'],
 605				'custom_fields' => empty($customFields) ? array() : $customFields,
 606			)
 607		);
 608
 609		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
 610	}
 611
 612	$old_id = $settings['theme_id'];
 613	$old_settings = $settings;
 614
 615	loadTheme($_GET['th'], false);
 616
 617	loadLanguage('Profile');
 618	// @todo Should we just move these options so they are no longer theme dependant?
 619	loadLanguage('PersonalMessage');
 620
 621	// Let the theme take care of the settings.
 622	loadTemplate('Settings');
 623	loadSubTemplate('options');
 624
 625	$context['sub_template'] = 'set_options';
 626	$context['page_title'] = $txt['theme_settings'];
 627
 628	$context['options'] = $context['theme_options'];
 629	$context['theme_settings'] = $settings;
 630
 631	if (empty($_REQUEST['who']))
 632	{
 633		$request = $smcFunc['db_query']('', '
 634			SELECT variable, value
 635			FROM {db_prefix}themes
 636			WHERE id_theme IN (1, {int:current_theme})
 637				AND id_member = {int:guest_member}',
 638			array(
 639				'current_theme' => $_GET['th'],
 640				'guest_member' => -1,
 641			)
 642		);
 643		$context['theme_options'] = array();
 644		while ($row = $smcFunc['db_fetch_assoc']($request))
 645			$context['theme_options'][$row['variable']] = $row['value'];
 646		$smcFunc['db_free_result']($request);
 647
 648		$context['theme_options_reset'] = false;
 649	}
 650	else
 651	{
 652		$context['theme_options'] = array();
 653		$context['theme_options_reset'] = true;
 654	}
 655
 656	foreach ($context['options'] as $i => $setting)
 657	{
 658		// Is this disabled?
 659		if ($setting['id'] == 'calendar_start_day' && empty($modSettings['cal_enabled']))
 660		{
 661			unset($context['options'][$i]);
 662			continue;
 663		}
 664		elseif (($setting['id'] == 'topics_per_page' || $setting['id'] == 'messages_per_page') && !empty($modSettings['disableCustomPerPage']))
 665		{
 666			unset($context['options'][$i]);
 667			continue;
 668		}
 669
 670		if (!isset($setting['type']) || $setting['type'] == 'bool')
 671			$context['options'][$i]['type'] = 'checkbox';
 672		elseif ($setting['type'] == 'int' || $setting['type'] == 'integer')
 673			$context['options'][$i]['type'] = 'number';
 674		elseif ($setting['type'] == 'string')
 675			$context['options'][$i]['type'] = 'text';
 676
 677		if (isset($setting['options']))
 678			$context['options'][$i]['type'] = 'list';
 679
 680		$context['options'][$i]['value'] = !isset($context['theme_options'][$setting['id']]) ? '' : $context['theme_options'][$setting['id']];
 681	}
 682
 683	// Restore the existing theme.
 684	loadTheme($old_id, false);
 685	$settings = $old_settings;
 686
 687	loadTemplate('Themes');
 688	createToken('admin-sto');
 689}
 690
 691/**
 692 * Administrative global settings.
 693 * - saves and requests global theme settings. ($settings)
 694 * - loads the Admin language file.
 695 * - calls ThemeAdmin() if no theme is specified. (the theme center.)
 696 * - requires admin_forum permission.
 697 * - accessed with ?action=admin;area=theme;sa=list&th=xx.
 698 */
 699function SetThemeSettings()
 700{
 701	global $txt, $context, $settings, $modSettings, $sourcedir, $smcFunc;
 702
 703	if (empty($_GET['th']) && empty($_GET['id']))
 704		return ThemeAdmin();
 705	$_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
 706
 707	// Select the best fitting tab.
 708	$context[$context['admin_menu_name']]['current_subsection'] = 'list';
 709
 710	loadLanguage('Admin');
 711	isAllowedTo('admin_forum');
 712
 713	// Validate inputs/user.
 714	if (empty($_GET['th']))
 715		fatal_lang_error('no_theme', false);
 716
 717	// Fetch the smiley sets...
 718	$sets = explode(',', 'none,' . $modSettings['smiley_sets_known']);
 719	$set_names = explode("\n", $txt['smileys_none'] . "\n" . $modSettings['smiley_sets_names']);
 720	$context['smiley_sets'] = array(
 721		'' => $txt['smileys_no_default']
 722	);
 723	foreach ($sets as $i => $set)
 724		$context['smiley_sets'][$set] = htmlspecialchars($set_names[$i]);
 725
 726	$old_id = $settings['theme_id'];
 727	$old_settings = $settings;
 728
 729	loadTheme($_GET['th'], false);
 730
 731	// Sadly we really do need to init the template.
 732	loadSubTemplate('init', 'ignore');
 733
 734	// Also load the actual themes language file - in case of special settings.
 735	loadLanguage('Settings', '', true, true);
 736
 737	// And the custom language strings...
 738	loadLanguage('ThemeStrings', '', false, true);
 739
 740	// Let the theme take care of the settings.
 741	loadTemplate('Settings');
 742	loadSubTemplate('settings');
 743
 744	// Load the variants separately...
 745	$settings['theme_variants'] = array();
 746	if (file_exists($settings['theme_dir'] . '/index.template.php'))
 747	{
 748		$file_contents = implode('', file($settings['theme_dir'] . '/index.template.php'));
 749		if (preg_match('~\$settings\[\'theme_variants\'\]\s*=(.+?);~', $file_contents, $matches))
 750				eval('global $settings;' . $matches[0]);
 751	}
 752
 753	// Submitting!
 754	if (isset($_POST['save']))
 755	{
 756		checkSession();
 757		validateToken('admin-sts');
 758
 759		if (empty($_POST['options']))
 760			$_POST['options'] = array();
 761		if (empty($_POST['default_options']))
 762			$_POST['default_options'] = array();
 763
 764		// Make sure items are cast correctly.
 765		foreach ($context['theme_settings'] as $item)
 766		{
 767			// Disregard this item if this is just a separator.
 768			if (!is_array($item))
 769				continue;
 770
 771			foreach (array('options', 'default_options') as $option)
 772			{
 773				if (!isset($_POST[$option][$item['id']]))
 774					continue;
 775				// Checkbox.
 776				elseif (empty($item['type']))
 777					$_POST[$option][$item['id']] = $_POST[$option][$item['id']] ? 1 : 0;
 778				// Number
 779				elseif ($item['type'] == 'number')
 780					$_POST[$option][$item['id']] = (int) $_POST[$option][$item['id']];
 781			}
 782		}
 783
 784		// Set up the sql query.
 785		$inserts = array();
 786		foreach ($_POST['options'] as $opt => $val)
 787			$inserts[] = array(0, $_GET['th'], $opt, is_array($val) ? implode(',', $val) : $val);
 788		foreach ($_POST['default_options'] as $opt => $val)
 789			$inserts[] = array(0, 1, $opt, is_array($val) ? implode(',', $val) : $val);
 790		// If we're actually inserting something..
 791		if (!empty($inserts))
 792		{
 793			$smcFunc['db_insert']('replace',
 794				'{db_prefix}themes',
 795				array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
 796				$inserts,
 797				array('id_member', 'id_theme', 'variable')
 798			);
 799		}
 800
 801		cache_put_data('theme_settings-' . $_GET['th'], null, 90);
 802		cache_put_data('theme_settings-1', null, 90);
 803
 804		// Invalidate the cache.
 805		updateSettings(array('settings_updated' => time()));
 806
 807		redirectexit('action=admin;area=theme;sa=list;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id']);
 808	}
 809
 810	$context['sub_template'] = 'set_settings';
 811	$context['page_title'] = $txt['theme_settings'];
 812
 813	foreach ($settings as $setting => $dummy)
 814	{
 815		if (!in_array($setting, array('theme_url', 'theme_dir', 'images_url', 'template_dirs')))
 816			$settings[$setting] = htmlspecialchars__recursive($settings[$setting]);
 817	}
 818
 819	$context['settings'] = $context['theme_settings'];
 820	$context['theme_settings'] = $settings;
 821
 822	foreach ($context['settings'] as $i => $setting)
 823	{
 824		// Separators are dummies, so leave them alone.
 825		if (!is_array($setting))
 826			continue;
 827
 828		if (!isset($setting['type']) || $setting['type'] == 'bool')
 829			$context['settings'][$i]['type'] = 'checkbox';
 830		elseif ($setting['type'] == 'int' || $setting['type'] == 'integer')
 831			$context['settings'][$i]['type'] = 'number';
 832		elseif ($setting['type'] == 'string')
 833			$context['settings'][$i]['type'] = 'text';
 834
 835		if (isset($setting['options']))
 836			$context['settings'][$i]['type'] = 'list';
 837
 838		$context['settings'][$i]['value'] = !isset($settings[$setting['id']]) ? '' : $settings[$setting['id']];
 839	}
 840
 841	// Do we support variants?
 842	if (!empty($settings['theme_variants']))
 843	{
 844		$context['theme_variants'] = array();
 845		foreach ($settings['theme_variants'] as $variant)
 846		{
 847			// Have any text, old chap?
 848			$context['theme_variants'][$variant] = array(
 849				'label' => isset($txt['variant_' . $variant]) ? $txt['variant_' . $variant] : $variant,
 850				'thumbnail' => !file_exists($settings['theme_dir'] . '/images/thumbnail.png') || file_exists($settings['theme_dir'] . '/images/thumbnail_' . $variant . '.png') ? $settings['images_url'] . '/thumbnail_' . $variant . '.png' : ($settings['images_url'] . '/thumbnail.png'),
 851			);
 852		}
 853		$context['default_variant'] = !empty($settings['default_variant']) && isset($context['theme_variants'][$settings['default_variant']]) ? $settings['default_variant'] : $settings['theme_variants'][0];
 854	}
 855
 856	// Restore the current theme.
 857	loadTheme($old_id, false);
 858
 859	// Reinit just incase.
 860	loadSubTemplate('init', 'ignore');
 861
 862	$settings = $old_settings;
 863
 864	loadTemplate('Themes');
 865
 866	// We like Kenny better than Token.
 867	createToken('admin-sts');
 868}
 869
 870/**
 871 * Remove a theme from the database.
 872 * - removes an installed theme.
 873 * - requires an administrator.
 874 * - accessed with ?action=admin;area=theme;sa=remove.
 875 */
 876function RemoveTheme()
 877{
 878	global $modSettings, $context, $smcFunc;
 879
 880	checkSession('get');
 881
 882	isAllowedTo('admin_forum');
 883	validateToken('admin-tr', 'request');
 884
 885	// The theme's ID must be an integer.
 886	$_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
 887
 888	// You can't delete the default theme!
 889	if ($_GET['th'] == 1)
 890		fatal_lang_error('no_access', false);
 891
 892	$known = explode(',', $modSettings['knownThemes']);
 893	for ($i = 0, $n = count($known); $i < $n; $i++)
 894	{
 895		if ($known[$i] == $_GET['th'])
 896			unset($known[$i]);
 897	}
 898
 899	$smcFunc['db_query']('', '
 900		DELETE FROM {db_prefix}themes
 901		WHERE id_theme = {int:current_theme}',
 902		array(
 903			'current_theme' => $_GET['th'],
 904		)
 905	);
 906
 907	$smcFunc['db_query']('', '
 908		UPDATE {db_prefix}members
 909		SET id_theme = {int:default_theme}
 910		WHERE id_theme = {int:current_theme}',
 911		array(
 912			'default_theme' => 0,
 913			'current_theme' => $_GET['th'],
 914		)
 915	);
 916
 917	$smcFunc['db_query']('', '
 918		UPDATE {db_prefix}boards
 919		SET id_theme = {int:default_theme}
 920		WHERE id_theme = {int:current_theme}',
 921		array(
 922			'default_theme' => 0,
 923			'current_theme' => $_GET['th'],
 924		)
 925	);
 926
 927	$known = strtr(implode(',', $known), array(',,' => ','));
 928
 929	// Fix it if the theme was the overall default theme.
 930	if ($modSettings['theme_guests'] == $_GET['th'])
 931		updateSettings(array('theme_guests' => '1', 'knownThemes' => $known));
 932	else
 933		updateSettings(array('knownThemes' => $known));
 934
 935	redirectexit('action=admin;area=theme;sa=list;' . $context['session_var'] . '=' . $context['session_id']);
 936}
 937
 938/**
 939 * Choose a theme from a list.
 940 * allows an user or administrator to pick a new theme with an interface.
 941 * - can edit everyone's (u = 0), guests' (u = -1), or a specific user's.
 942 * - uses the Themes template. (pick sub template.)
 943 * - accessed with ?action=admin;area=theme;sa=pick.
 944 * @todo thought so... Might be better to split this file in ManageThemes and Themes,
 945 * with centralized admin permissions on ManageThemes.
 946 */
 947function PickTheme()
 948{
 949	global $txt, $context, $modSettings, $user_info, $language, $smcFunc, $settings, $scripturl;
 950
 951	loadLanguage('Profile');
 952	loadTemplate('Themes');
 953
 954	// Build the link tree.
 955	$context['linktree'][] = array(
 956		'url' => $scripturl . '?action=theme;sa=pick;u=' . (!empty($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0),
 957		'name' => $txt['theme_pick'],
 958	);
 959
 960	$_SESSION['id_theme'] = 0;
 961
 962	if (isset($_GET['id']))
 963		$_GET['th'] = $_GET['id'];
 964
 965	// Saving a variant cause JS doesn't work - pretend it did ;)
 966	if (isset($_POST['save']))
 967	{
 968		// Which theme?
 969		foreach ($_POST['save'] as $k => $v)
 970			$_GET['th'] = (int) $k;
 971
 972		if (isset($_POST['vrt'][$k]))
 973			$_GET['vrt'] = $_POST['vrt'][$k];
 974	}
 975
 976	// Have we made a desicion, or are we just browsing?
 977	if (isset($_GET['th']))
 978	{
 979		checkSession('get');
 980
 981		$_GET['th'] = (int) $_GET['th'];
 982
 983		// Save for this user.
 984		if (!isset($_REQUEST['u']) || !allowedTo('admin_forum'))
 985		{
 986			updateMemberData($user_info['id'], array('id_theme' => (int) $_GET['th']));
 987
 988			// A variants to save for the user?
 989			if (!empty($_GET['vrt']))
 990			{
 991				$smcFunc['db_insert']('replace',
 992					'{db_prefix}themes',
 993					array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
 994					array($_GET['th'], $user_info['id'], 'theme_variant', $_GET['vrt']),
 995					array('id_theme', 'id_member', 'variable')
 996				);
 997				cache_put_data('theme_settings-' . $_GET['th'] . ':' . $user_info['id'], null, 90);
 998
 999				$_SESSION['id_variant'] = 0;
1000			}
1001
1002			redirectexit('action=profile;area=theme');
1003		}
1004
1005		// If changing members or guests - and there's a variant - assume changing default variant.
1006		if (!empty($_GET['vrt']) && ($_REQUEST['u'] == '0' || $_REQUEST['u'] == '-1'))
1007		{
1008			$smcFunc['db_insert']('replace',
1009				'{db_prefix}themes',
1010				array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
1011				array($_GET['th'], 0, 'default_variant', $_GET['vrt']),
1012				array('id_theme', 'id_member', 'variable')
1013			);
1014
1015			// Make it obvious that it's changed
1016			cache_put_data('theme_settings-' . $_GET['th'], null, 90);
1017		}
1018
1019		// For everyone.
1020		if ($_REQUEST['u'] == '0')
1021		{
1022			updateMemberData(null, array('id_theme' => (int) $_GET['th']));
1023
1024			// Remove any custom variants.
1025			if (!empty($_GET['vrt']))
1026			{
1027				$smcFunc['db_query']('', '
1028					DELETE FROM {db_prefix}themes
1029					WHERE id_theme = {int:current_theme}
1030						AND variable = {string:theme_variant}',
1031					array(
1032						'current_theme' => (int) $_GET['th'],
1033						'theme_variant' => 'theme_variant',
1034					)
1035				);
1036			}
1037
1038			redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
1039		}
1040		// Change the default/guest theme.
1041		elseif ($_REQUEST['u'] == '-1')
1042		{
1043			updateSettings(array('theme_guests' => (int) $_GET['th']));
1044
1045			redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
1046		}
1047		// Change a specific member's theme.
1048		else
1049		{
1050			// The forum's default theme is always 0 and we
1051			if (isset($_GET['th']) && $_GET['th'] == 0)
1052					$_GET['th'] = $modSettings['theme_guests'];
1053
1054			updateMemberData((int) $_REQUEST['u'], array('id_theme' => (int) $_GET['th']));
1055
1056			if (!empty($_GET['vrt']))
1057			{
1058				$smcFunc['db_insert']('replace',
1059					'{db_prefix}themes',
1060					array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
1061					array($_GET['th'], (int) $_REQUEST['u'], 'theme_variant', $_GET['vrt']),
1062					array('id_theme', 'id_member', 'variable')
1063				);
1064				cache_put_data('theme_settings-' . $_GET['th'] . ':' . (int) $_REQUEST['u'], null, 90);
1065
1066				if ($user_info['id'] == $_REQUEST['u'])
1067					$_SESSION['id_variant'] = 0;
1068			}
1069
1070			redirectexit('action=profile;u=' . (int) $_REQUEST['u'] . ';area=theme');
1071		}
1072	}
1073
1074	// Figure out who the member of the minute is, and what theme they've chosen.
1075	if (!isset($_REQUEST['u']) || !allowedTo('admin_forum'))
1076	{
1077		$context['current_member'] = $user_info['id'];
1078		$context['current_theme'] = $user_info['theme'];
1079	}
1080	// Everyone can't chose just one.
1081	elseif ($_REQUEST['u'] == '0')
1082	{
1083		$context['current_member'] = 0;
1084		$context['current_theme'] = 0;
1085	}
1086	// Guests and such...
1087	elseif ($_REQUEST['u'] == '-1')
1088	{
1089		$context['current_member'] = -1;
1090		$context['current_theme'] = $modSettings['theme_guests'];
1091	}
1092	// Someones else :P.
1093	else
1094	{
1095		$context['current_member'] = (int) $_REQUEST['u'];
1096
1097		$request = $smcFunc['db_query']('', '
1098			SELECT id_theme
1099			FROM {db_prefix}members
1100			WHERE id_member = {int:current_member}
1101			LIMIT 1',
1102			array(
1103				'current_member' => $context['current_member'],
1104			)
1105		);
1106		list ($context['current_theme']) = $smcFunc['db_fetch_row']($request);
1107		$smcFunc['db_free_result']($request);
1108	}
1109
1110	// Get the theme name and descriptions.
1111	$context['available_themes'] = array();
1112	if (!empty($modSettings['knownThemes']))
1113	{
1114		$request = $smcFunc['db_query']('', '
1115			SELECT id_theme, variable, value
1116			FROM {db_prefix}themes
1117			WHERE variable IN ({string:name}, {string:theme_url}, {string:theme_dir}, {string:images_url}, {string:disable_user_variant})' . (!allowedTo('admin_forum') ? '
1118				AND id_theme IN ({array_string:known_themes})' : '') . '
1119				AND id_theme != {int:default_theme}
1120				AND id_member = {int:no_member}',
1121			array(
1122				'default_theme' => 0,
1123				'name' => 'name',
1124				'no_member' => 0,
1125				'theme_url' => 'theme_url',
1126				'theme_dir' => 'theme_dir',
1127				'images_url' => 'images_url',
1128				'disable_user_variant' => 'disable_user_variant',
1129				'known_themes' => explode(',', $modSettings['knownThemes']),
1130			)
1131		);
1132		while ($row = $smcFunc['db_fetch_assoc']($request))
1133		{
1134			if (!isset($context['available_themes'][$row['id_theme']]))
1135				$context['available_themes'][$row['id_theme']] = array(
1136					'id' => $row['id_theme'],
1137					'selected' => $context['current_theme'] == $row['id_theme'],
1138					'num_users' => 0
1139				);
1140			$context['available_themes'][$row['id_theme']][$row['variable']] = $row['value'];
1141		}
1142		$smcFunc['db_free_result']($request);
1143	}
1144
1145	// Okay, this is a complicated problem: the default theme is 1, but they aren't allowed to access 1!
1146	if (!isset($context['available_themes'][$modSettings['theme_guests']]))
1147	{
1148		$context['available_themes'][0] = array(
1149			'num_users' => 0
1150		);
1151		$guest_theme = 0;
1152	}
1153	else
1154		$guest_theme = $modSettings['theme_guests'];
1155
1156	$request = $smcFunc['db_query']('', '
1157		SELECT id_theme, COUNT(*) AS the_count
1158		FROM {db_prefix}members
1159		GROUP BY id_theme
1160		ORDER BY id_theme DESC',
1161		array(
1162		)
1163	);
1164	while ($row = $smcFunc['db_fetch_assoc']($request))
1165	{
1166		// Figure out which theme it is they are REALLY using.
1167		if (!empty($modSettings['knownThemes']) && !in_array($row['id_theme'], explode(',',$modSettings['knownThemes'])))
1168			$row['id_theme'] = $guest_theme;
1169		elseif (empty($modSettings['theme_allow']))
1170			$row['id_theme'] = $guest_theme;
1171
1172		if (isset($context['available_themes'][$row['id_theme']]))
1173			$context['available_themes'][$row['id_theme']]['num_users'] += $row['the_count'];
1174		else
1175			$context['available_themes'][$guest_theme]['num_users'] += $row['the_count'];
1176	}
1177	$smcFunc['db_free_result']($request);
1178
1179	// Get any member variant preferences.
1180	$variant_preferences = array();
1181	if ($context['current_member'] > 0)
1182	{
1183		$request = $smcFunc['db_query']('', '
1184			SELECT id_theme, value
1185			FROM {db_prefix}themes
1186			WHERE variable = {string:theme_variant}
1187				AND id_member IN ({array_int:id_member})
1188			ORDER BY id_member ASC',
1189			array(
1190				'theme_variant' => 'theme_variant',
1191				'id_member' => isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'pick' ? array(-1, $context['current_member']) : array(-1),
1192			)
1193		);
1194		while ($row = $smcFunc['db_fetch_assoc']($request))
1195			$variant_preferences[$row['id_theme']] = $row['value'];
1196		$smcFunc['db_free_result']($request);
1197	}
1198
1199	// Save the setting first.
1200	$current_images_url = $settings['images_url'];
1201	$current_theme_variants = !empty($settings['theme_variants']) ? $settings['theme_variants'] : array();
1202
1203	foreach ($context['available_themes'] as $id_theme => $theme_data)
1204	{
1205		// Don't try to load the forum or board default theme's data... it doesn't have any!
1206		if ($id_theme == 0)
1207			continue;
1208
1209		// The thumbnail needs the correct path.
1210		$settings['images_url'] = &$theme_data['images_url'];
1211
1212		if (file_exists($theme_data['theme_dir'] . '/languages/Settings.' . $user_info['language'] . '.php'))
1213			include($theme_data['theme_dir'] . '/languages/Settings.' . $user_info['language'] . '.php');
1214		elseif (file_exists($theme_data['theme_dir'] . '/languages/Settings.' . $language . '.php'))
1215			include($theme_data['theme_dir'] . '/languages/Settings.' . $language . '.php');
1216		else
1217		{
1218			$txt['theme_thumbnail_href'] = $theme_data['images_url'] . '/thumbnail.png';
1219			$txt['theme_description'] = '';
1220		}
1221
1222		$context['available_themes'][$id_theme]['thumbnail_href'] = $txt['theme_thumbnail_href'];
1223		$context['available_themes'][$id_theme]['description'] = $txt['theme_description'];
1224
1225		// Are there any variants?
1226		if (file_exists($theme_data['theme_dir'] . '/index.template.php') && empty($theme_data['disable_user_variant']))
1227		{
1228			$file_contents = implode('', file($theme_data['theme_dir'] . '/index.template.php'));
1229			if (preg_match('~\$settings\[\'theme_variants\'\]\s*=(.+?);~', $file_contents, $matches))
1230			{
1231				$settings['theme_variants'] = array();
1232
1233				// Fill settings up.
1234				eval('global $settings;' . $matches[0]);
1235
1236				if (!empty($settings['theme_variants']))
1237				{
1238					loadLanguage('Settings');
1239
1240					$context['available_themes'][$id_theme]['variants'] = array();
1241					foreach ($settings['theme_variants'] as $variant)
1242						$context['available_themes'][$id_theme]['variants'][$variant] = array(
1243							'label' => isset($txt['variant_' . $variant]) ? $txt['variant_' . $variant] : $variant,
1244							'thumbnail' => !file_exists($theme_data['theme_dir'] . '/images/thumbnail.png') || file_exists($theme_data['theme_dir'] . '/images/thumbnail_' . $variant . '.png') ? $theme_data['images_url'] . '/thumbnail_' . $variant . '.png' : ($theme_data['images_url'] . '/thumbnail.png'),
1245						);
1246
1247					$context['available_themes'][$id_theme]['selected_variant'] = isset($_GET['vrt']) ? $_GET['vrt'] : (!empty($variant_preferences[$id_theme]) ? $variant_preferences[$id_theme] : (!empty($settings['default_variant']) ? $settings['default_variant'] : $settings['theme_variants'][0]));
1248					if (!isset($context['available_themes'][$id_theme]['variants'][$context['available_themes'][$id_theme]['selected_variant']]['thumbnail']))
1249						$context['available_themes'][$id_theme]['selected_variant'] = $settings['theme_variants'][0];
1250
1251					$context['available_themes'][$id_theme]['thumbnail_href'] = $context['available_themes'][$id_theme]['variants'][$context['available_themes'][$id_theme]['selected_variant']]['thumbnail'];
1252					// Allow themes to override the text.
1253					$context['available_themes'][$id_theme]['pick_label'] = isset($txt['variant_pick']) ? $txt['variant_pick'] : $txt['theme_pick_variant'];
1254				}
1255			}
1256		}
1257	}
1258	// Then return it.
1259	$settings['images_url'] = $current_images_url;
1260	$settings['theme_variants'] = $current_theme_variants;
1261
1262	// As long as we're not doing the default theme...
1263	if (!isset($_REQUEST['u']) || $_REQUEST['u'] >= 0)
1264	{
1265		if ($guest_theme != 0)
1266			$context['available_themes'][0] = $context['available_themes'][$guest_theme];
1267
1268		$context['available_themes'][0]['id'] = 0;
1269		$context['available_themes'][0]['name'] = $txt['theme_forum_default'];
1270		$context['available_themes'][0]['selected'] = $context['current_theme'] == 0;
1271		$context['available_themes'][0]['description'] = $txt['theme_global_description'];
1272	}
1273
1274	ksort($context['available_themes']);
1275
1276	$context['page_title'] = $txt['theme_pick'];
1277	$context['sub_template'] = 'pick';
1278}
1279
1280/**
1281 * Installs new themes, either from a gzip or copy of the default.
1282 * - puts themes in $boardurl/Themes.
1283 * - assumes the gzip has a root directory in it. (ie default.)
1284 * Requires admin_forum.
1285 * Accessed with ?action=admin;area=theme;sa=install.
1286 */
1287function ThemeInstall()
1288{
1289	global $sourcedir, $boarddir, $boardurl, $txt, $context, $settings, $modSettings, $smcFunc;
1290
1291	checkSession('request');
1292
1293	isAllowedTo('admin_forum');
1294	checkSession('request');
1295
1296	require_once($sourcedir . '/Subs-Package.php');
1297
1298	loadTemplate('Themes');
1299
1300	if (isset($_GET['theme_id']))
1301	{
1302		$result = $smcFunc['db_query']('', '
1303			SELECT value
1304			FROM {db_prefix}themes
1305			WHERE id_theme = {int:current_theme}
1306				AND id_member = {int:no_member}
1307				AND variable = {string:name}
1308			LIMIT 1',
1309			array(
1310				'current_theme' => (int) $_GET['theme_id'],
1311				'no_member' => 0,
1312				'name' => 'name',
1313			)
1314		);
1315		list ($theme_name) = $smcFunc['db_fetch_row']($result);
1316		$smcFunc['db_free_result']($result);
1317
1318		$context['sub_template'] = 'installed';
1319		$context['page_title'] = $txt['theme_installed'];
1320		$context['installed_theme'] = array(
1321			'id' => (int) $_GET['theme_id'],
1322			'name' => $theme_name,
1323		);
1324
1325		return;
1326	}
1327
1328	if ((!empty($_FILES['theme_gz']) && (!isset($_FILES['theme_gz']['error']) || $_FILES['theme_gz']['error'] != 4)) || !empty($_REQUEST['theme_gz']))
1329		$method = 'upload';
1330	elseif (isset($_REQUEST['theme_dir']) && rtrim(realpath($_REQUEST['theme_dir']), '/\\') != realpath($boarddir . '/Themes') && file_exists($_REQUEST['theme_dir']))
1331		$method = 'path';
1332	else
1333		$method = 'copy';
1334
1335	if (!empty($_REQUEST['copy']) && $method == 'copy')
1336	{
1337		// Hopefully the themes directory is writable, or we might have a problem.
1338		if (!is_writable($boarddir . '/Themes'))
1339			fatal_lang_error('theme_install_write_error', 'critical');
1340
1341		$theme_dir = $boarddir . '/Themes/' . preg_replace('~[^A-Za-z0-9_\- ]~', '', $_REQUEST['copy']);
1342
1343		umask(0);
1344		mkdir($theme_dir, 0777);
1345
1346		@set_time_limit(600);
1347		if (function_exists('apache_reset_timeout'))
1348			@apache_reset_timeout();
1349
1350		// Create subdirectories for css and javascript files.
1351		mkdir($theme_dir . '/css', 0777);
1352		mkdir($theme_dir . '/scripts', 0777);
1353
1354		// Copy over the default non-theme files.
1355		$to_copy = array('/index.php', '/index.template.php', '/css/index.css', '/css/rtl.css', '/scripts/theme.js');
1356		foreach ($to_copy as $file)
1357		{
1358			copy($settings['default_theme_dir'] . $file, $theme_dir . $file);
1359			@chmod($theme_dir . $file, 0777);
1360		}
1361
1362		// And now the entire images directory!
1363		copytree($settings['default_theme_dir'] . '/images', $theme_dir . '/images');
1364		package_flush_cache();
1365
1366		$theme_name = $_REQUEST['copy'];
1367		$images_url = $boardurl . '/Themes/' . basename($theme_dir) . '/images';
1368		$theme_dir = realpath($theme_dir);
1369
1370		// Lets get some data for the new theme.
1371		$request = $smcFunc['db_query']('', '
1372			SELECT variable, value
1373			FROM {db_prefix}themes
1374			WHERE variable IN ({string:theme_templates}, {string:theme_layers})
1375				AND id_member = {int:no_member}
1376				AND id_theme = {int:default_theme}',
1377			array(
1378				'no_member' => 0,
1379				'default_theme' => 1,
1380				'theme_templates' => 'theme_templates',
1381				'theme_layers' => 'theme_layers',
1382			)
1383		);
1384		while ($row = $smcFunc['db_fetch_assoc']($request))
1385		{
1386			if ($row['variable'] == 'theme_templates')
1387				$theme_templates = $row['value'];
1388			elseif ($row['variable'] == 'theme_layers')
1389				$theme_layers = $row['value'];
1390			else
1391				continue;
1392		}
1393		$smcFunc['db_free_result']($request);
1394
1395		// Lets add a theme_info.xml to this theme.
1396		$xml_info = '<' . '?xml version="1.0"?' . '>
1397<theme-info xmlns="http://www.simplemachines.org/xml/theme-info" xmlns:smf="http://www.simplemachines.org/">
1398	<!-- For the id, always use something unique - put your name, a colon, and then the package name. -->
1399	<id>smf:' . $smcFunc['strtolower'](str_replace(array(' '), '_', $_REQUEST['copy'])) . '</id>
1400	<version>' . $modSettings['smfVersion'] . '</version>
1401	<!-- Theme name, used purely for aesthetics. -->
1402	<name>' . $_REQUEST['copy'] . '</name>
1403	<!-- Author: your email address or contact information. The name attribute is optional. -->
1404	<author name="Simple Machines">info@simplemachines.org</author>
1405	<!-- Website... where to get updates and more information. -->
1406	<website>http://www.simplemachines.org/</website>
1407	<!-- Template layers to use, defaults to "html,body". -->
1408	<layers>' . (empty($theme_layers) ? 'html,body' : $theme_layers) . '</layers>
1409	<!-- Templates to load on startup. Default is "index". -->
1410	<templates>' . (empty($theme_templates) ? 'index' : $theme_templates) . '</templates>
1411	<!-- Base this theme off another? Default is blank, or no. It could be "default". -->
1412	<based-on></based-on>
1413</theme-info>';
1414
1415		// Now write it.
1416		$fp = @fopen($theme_dir . '/theme_info.xml', 'w+');
1417		if ($fp)
1418		{
1419			fwrite($fp, $xml_info);
1420			fclose($fp);
1421		}
1422	}
1423	elseif (isset($_REQUEST['theme_dir']) && $method == 'path')
1424	{
1425		if (!is_dir($_REQUEST['theme_dir']) || !file_exists($_REQUEST['theme_dir'] . '/theme_info.xml'))
1426			fatal_lang_error('theme_install_error', false);
1427
1428		$theme_name = basename($_REQUEST['theme_dir']);
1429		$theme_dir = $_REQUEST['theme_dir'];
1430	}
1431	elseif ($method = 'upload')
1432	{
1433		// Hopefully the themes directory is writable, or we might have a problem.
1434		if (!is_writable($boarddir . '/Themes'))
1435			fatal_lang_error('theme_install_write_error', 'critical');
1436
1437		// This happens when the admin session is gone and the user has to login again
1438		if (empty($_FILES['theme_gz']) && empty($_REQUEST['theme_gz']))
1439			redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
1440
1441		// Set the default settings...
1442		$theme_name = strtok(basename(isset($_FILES['theme_gz']) ? $_FILES['theme_gz']['name'] : $_REQUEST['theme_gz']), '.');
1443		$theme_name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $theme_name);
1444		$theme_dir = $boarddir . '/Themes/' . $theme_name;
1445
1446		if (isset($_FILES['theme_gz']) && is_uploaded_file($_FILES['theme_gz']['tmp_name']) && (ini_get('open_basedir') != '' || file_exists($_FILES['theme_gz']['tmp_name'])))
1447			$extracted = read_tgz_file($_FILES['theme_gz']['tmp_name'], $boarddir . '/Themes/' . $theme_name, false, true);
1448		elseif (isset($_REQUEST['theme_gz']))
1449		{
1450			// Check that the theme is from simplemachines.org, for now... maybe add mirroring later.
1451			if (preg_match('~^http://[\w_\-]+\.simplemachines\.org/~', $_REQUEST['theme_gz']) == 0 || strpos($_REQUEST['theme_gz'], 'dlattach') !== false)
1452				fatal_lang_error('not_on_simplemachines');
1453
1454			$extracted = read_tgz_file($_REQUEST['theme_gz'], $boarddir . '/Themes/' . $theme_name, false, true);
1455		}
1456		else
1457			redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
1458	}
1459
1460	// Something go wrong?
1461	if ($theme_dir != '' && basename($theme_dir) != 'Themes')
1462	{
1463		// Defaults.
1464		$install_info = array(
1465			'theme_url' => $boardurl . '/Themes/' . basename($theme_dir),
1466			'images_url' => isset($images_url) ? $images_url : $boardurl . '/Themes/' . basename($theme_dir) . '/images',
1467			'theme_dir' => $theme_dir,
1468			'name' => $theme_name
1469		);
1470
1471		if (file_exists($theme_dir . '/theme_info.xml'))
1472		{
1473			$theme_info = file_get_contents($theme_dir . '/theme_info.xml');
1474			// Parse theme-info.xml into an xmlArray.
1475			require_once($sourcedir . '/Class-Package.php');
1476			$theme_info_xml = new xmlArray($theme_info);
1477			// @todo Error message of some sort?
1478			if (!$theme_info_xml->exists('theme-info[0]'))
1479				return 'package_get_error_packageinfo_corrupt';
1480
1481			$theme_info_xml = $theme_info_xml->path('theme-info[0]');
1482			$theme_info_xml = $theme_info_xml->to_array();
1483
1484			$xml_elements = array(
1485				'name' => 'name',
1486				'theme_layers' => 'layers',
1487				'theme_templates' => 'templates',
1488				'based_on' => 'based-on',
1489			);
1490			foreach ($xml_elements as $var => $name)
1491			{
1492				if (!empty($theme_info_xml[$name]))
1493					$install_info[$var] = $theme_info_xml[$name];
1494			}
1495
1496			if (!empty($theme_info_xml['images']))
1497			{
1498				$install_info['images_url'] = $install_info['theme_url'] . '/' . $theme_info_xml['images'];
1499				$explicit_images = true;
1500			}
1501
1502			if (!empty($theme_info_xml['extra']))
1503				$install_info += unserialize($theme_info_xml['extra']);
1504		}
1505
1506		if (isset($install_info['based_on']))
1507		{
1508			if ($install_info['based_on'] == 'default')
1509			{
1510				$install_info['theme_url'] = $settings['default_theme_url'];
1511				$install_info['images_url'] = $settings['default_images_url'];
1512			}
1513			elseif ($install_info['based_on'] != '')
1514			{
1515				$install_info['based_on'] = preg_replace('~[^A-Za-z0-9\-_ ]~', '', $install_info['based_on']);
1516
1517				$request = $smcFu…

Large files files are truncated, but you can click here to view the full file