PageRenderTime 5ms CodeModel.GetById 12ms app.highlight 51ms RepoModel.GetById 1ms app.codeStats 0ms

/sources/admin/Themes.php

https://github.com/Arantor/Elkarte
PHP | 2214 lines | 1682 code | 291 blank | 241 comment | 303 complexity | d32e679edfe046490fdab9eb8eb64c63 MD5 | raw file

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

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

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