Passed
Pull Request — release-2.1 (#5074)
by John
05:59
created

SetThemeOptions()   F

Complexity

Conditions 62
Paths 8024

Size

Total Lines 375
Code Lines 191

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 62
eloc 191
c 0
b 0
f 0
nop 0
dl 0
loc 375
rs 0
nc 8024

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 2018 Simple Machines and individual contributors
28
 * @license http://www.simplemachines.org/about/smf/license.php BSD
29
 *
30
 * @version 2.1 Beta 4
31
 */
32
33
if (!defined('SMF'))
34
	die('No direct access...');
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
 */
44
function ThemesMain()
45
{
46
	global $txt, $context, $sourcedir;
47
48
	// Load the important language files...
49
	loadLanguage('Themes');
50
	loadLanguage('Settings');
51
	loadLanguage('Drafts');
52
53
	// No funny business - guests only.
54
	is_not_guest();
55
56
	require_once($sourcedir . '/Subs-Themes.php');
57
58
	// Default the page title to Theme Administration by default.
59
	$context['page_title'] = $txt['themeadmin_title'];
60
61
	// Theme administration, removal, choice, or installation...
62
	$subActions = array(
63
		'admin' => 'ThemeAdmin',
64
		'list' => 'ThemeList',
65
		'reset' => 'SetThemeOptions',
66
		'options' => 'SetThemeOptions',
67
		'install' => 'ThemeInstall',
68
		'remove' => 'RemoveTheme',
69
		'pick' => 'PickTheme',
70
		'edit' => 'EditTheme',
71
		'enable' => 'EnableTheme',
72
		'copy' => 'CopyTemplate',
73
	);
74
75
	// @todo Layout Settings?  huh?
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
	// CRUD $subActions as needed.
100
	call_integration_hook('integrate_manage_themes', array(&$subActions));
101
102
	// Whatever you decide to do, clean the minify cache.
103
	cache_put_data('minimized_css', null);
104
105
	// Follow the sa or just go to administration.
106
	if (isset($_GET['sa']) && !empty($subActions[$_GET['sa']]))
107
		call_helper($subActions[$_GET['sa']]);
108
109
	else
110
		call_helper($subActions['admin']);
111
}
112
113
/**
114
 * This function allows administration of themes and their settings,
115
 * as well as global theme settings.
116
 *  - sets the settings theme_allow, theme_guests, and knownThemes.
117
 *  - requires the admin_forum permission.
118
 *  - accessed with ?action=admin;area=theme;sa=admin.
119
 *
120
 *  @uses Themes template
121
 *  @uses Admin language file
122
 */
123
function ThemeAdmin()
124
{
125
	global $context, $boarddir;
126
127
	// Are handling any settings?
128
	if (isset($_POST['save']))
129
	{
130
		checkSession();
131
		validateToken('admin-tm');
132
133
		if (isset($_POST['options']['known_themes']))
134
			foreach ($_POST['options']['known_themes'] as $key => $id)
135
				$_POST['options']['known_themes'][$key] = (int) $id;
136
137
		else
138
			fatal_lang_error('themes_none_selectable', false);
139
140
		if (!in_array($_POST['options']['theme_guests'], $_POST['options']['known_themes']))
141
			fatal_lang_error('themes_default_selectable', false);
142
143
		// Commit the new settings.
144
		updateSettings(array(
145
			'theme_allow' => $_POST['options']['theme_allow'],
146
			'theme_guests' => $_POST['options']['theme_guests'],
147
			'knownThemes' => implode(',', $_POST['options']['known_themes']),
148
		));
149
		if ((int) $_POST['theme_reset'] == 0 || in_array($_POST['theme_reset'], $_POST['options']['known_themes']))
150
			updateMemberData(null, array('id_theme' => (int) $_POST['theme_reset']));
151
152
		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=admin');
153
	}
154
155
	loadLanguage('Admin');
156
	isAllowedTo('admin_forum');
157
	loadTemplate('Themes');
158
159
	// List all installed and enabled themes.
160
	get_all_themes(true);
161
162
	// Can we create a new theme?
163
	$context['can_create_new'] = is_writable($boarddir . '/Themes');
164
	$context['new_theme_dir'] = substr(realpath($boarddir . '/Themes/default'), 0, -7);
165
166
	// Look for a non existent theme directory. (ie theme87.)
167
	$theme_dir = $boarddir . '/Themes/theme';
168
	$i = 1;
169
	while (file_exists($theme_dir . $i))
170
		$i++;
171
172
	$context['new_theme_name'] = 'theme' . $i;
173
174
	// A bunch of tokens for a bunch of forms.
175
	createToken('admin-tm');
176
	createToken('admin-t-file');
177
	createToken('admin-t-copy');
178
	createToken('admin-t-dir');
179
}
180
181
/**
182
 * This function lists the available themes and provides an interface to reset
183
 * the paths of all the installed themes.
184
 */
185
function ThemeList()
186
{
187
	global $context, $boarddir, $boardurl, $smcFunc;
188
189
	loadLanguage('Admin');
190
	isAllowedTo('admin_forum');
191
192
	if (isset($_REQUEST['th']))
193
		return SetThemeSettings();
194
195
	if (isset($_POST['save']))
196
	{
197
		checkSession();
198
		validateToken('admin-tl');
199
200
		// Calling the almighty power of global vars!
201
		get_all_themes(false);
202
203
		$setValues = array();
204
		foreach ($context['themes'] as $id => $theme)
205
		{
206
			if (file_exists($_POST['reset_dir'] . '/' . basename($theme['theme_dir'])))
207
			{
208
				$setValues[] = array($id, 0, 'theme_dir', realpath($_POST['reset_dir'] . '/' . basename($theme['theme_dir'])));
209
				$setValues[] = array($id, 0, 'theme_url', $_POST['reset_url'] . '/' . basename($theme['theme_dir']));
210
				$setValues[] = array($id, 0, 'images_url', $_POST['reset_url'] . '/' . basename($theme['theme_dir']) . '/' . basename($theme['images_url']));
211
			}
212
213
			if (isset($theme['base_theme_dir']) && file_exists($_POST['reset_dir'] . '/' . basename($theme['base_theme_dir'])))
214
			{
215
				$setValues[] = array($id, 0, 'base_theme_dir', realpath($_POST['reset_dir'] . '/' . basename($theme['base_theme_dir'])));
216
				$setValues[] = array($id, 0, 'base_theme_url', $_POST['reset_url'] . '/' . basename($theme['base_theme_dir']));
217
				$setValues[] = array($id, 0, 'base_images_url', $_POST['reset_url'] . '/' . basename($theme['base_theme_dir']) . '/' . basename($theme['base_images_url']));
218
			}
219
220
			cache_put_data('theme_settings-' . $id, null, 90);
221
		}
222
223
		if (!empty($setValues))
224
		{
225
			$smcFunc['db_insert']('replace',
226
				'{db_prefix}themes',
227
				array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
228
				$setValues,
229
				array('id_theme', 'variable', 'id_member')
230
			);
231
		}
232
233
		redirectexit('action=admin;area=theme;sa=list;' . $context['session_var'] . '=' . $context['session_id']);
234
	}
235
236
	loadTemplate('Themes');
237
238
	// Get all installed themes.
239
	get_all_themes(false);
240
241
	$context['reset_dir'] = realpath($boarddir . '/Themes');
242
	$context['reset_url'] = $boardurl . '/Themes';
243
244
	$context['sub_template'] = 'list_themes';
245
	createToken('admin-tl');
246
	createToken('admin-tr', 'request');
247
	createToken('admin-tre', 'request');
248
}
249
250
/**
251
 * Administrative global settings.
252
 */
253
function SetThemeOptions()
254
{
255
	global $txt, $context, $settings, $modSettings, $smcFunc;
256
257
	$_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (isset($_GET['id']) ? (int) $_GET['id'] : 0);
258
259
	isAllowedTo('admin_forum');
260
261
	if (empty($_GET['th']) && empty($_GET['id']))
262
	{
263
		$request = $smcFunc['db_query']('', '
264
			SELECT id_theme, variable, value
265
			FROM {db_prefix}themes
266
			WHERE variable IN ({string:name}, {string:theme_dir})
267
				AND id_member = {int:no_member}',
268
			array(
269
				'no_member' => 0,
270
				'name' => 'name',
271
				'theme_dir' => 'theme_dir',
272
			)
273
		);
274
		$context['themes'] = array();
275
		while ($row = $smcFunc['db_fetch_assoc']($request))
276
		{
277
			if (!isset($context['themes'][$row['id_theme']]))
278
				$context['themes'][$row['id_theme']] = array(
279
					'id' => $row['id_theme'],
280
					'num_default_options' => 0,
281
					'num_members' => 0,
282
				);
283
			$context['themes'][$row['id_theme']][$row['variable']] = $row['value'];
284
		}
285
		$smcFunc['db_free_result']($request);
286
287
		$request = $smcFunc['db_query']('', '
288
			SELECT id_theme, COUNT(*) AS value
289
			FROM {db_prefix}themes
290
			WHERE id_member = {int:guest_member}
291
			GROUP BY id_theme',
292
			array(
293
				'guest_member' => -1,
294
			)
295
		);
296
		while ($row = $smcFunc['db_fetch_assoc']($request))
297
			$context['themes'][$row['id_theme']]['num_default_options'] = $row['value'];
298
		$smcFunc['db_free_result']($request);
299
300
		// Need to make sure we don't do custom fields.
301
		$request = $smcFunc['db_query']('', '
302
			SELECT col_name
303
			FROM {db_prefix}custom_fields',
304
			array(
305
			)
306
		);
307
		$customFields = array();
308
		while ($row = $smcFunc['db_fetch_assoc']($request))
309
			$customFields[] = $row['col_name'];
310
		$smcFunc['db_free_result']($request);
311
		$customFieldsQuery = empty($customFields) ? '' : ('AND variable NOT IN ({array_string:custom_fields})');
312
313
		$request = $smcFunc['db_query']('themes_count', '
314
			SELECT COUNT(DISTINCT id_member) AS value, id_theme
315
			FROM {db_prefix}themes
316
			WHERE id_member > {int:no_member}
317
				' . $customFieldsQuery . '
318
			GROUP BY id_theme',
319
			array(
320
				'no_member' => 0,
321
				'custom_fields' => empty($customFields) ? array() : $customFields,
322
			)
323
		);
324
		while ($row = $smcFunc['db_fetch_assoc']($request))
325
			$context['themes'][$row['id_theme']]['num_members'] = $row['value'];
326
		$smcFunc['db_free_result']($request);
327
328
		// There has to be a Settings template!
329
		foreach ($context['themes'] as $k => $v)
330
			if (empty($v['theme_dir']) || (!file_exists($v['theme_dir'] . '/Settings.template.php') && empty($v['num_members'])))
331
				unset($context['themes'][$k]);
332
333
		loadTemplate('Themes');
334
		$context['sub_template'] = 'reset_list';
335
336
		createToken('admin-stor', 'request');
337
		return;
338
	}
339
340
	// Submit?
341
	if (isset($_POST['submit']) && empty($_POST['who']))
342
	{
343
		checkSession();
344
		validateToken('admin-sto');
345
346
		if (empty($_POST['options']))
347
			$_POST['options'] = array();
348
		if (empty($_POST['default_options']))
349
			$_POST['default_options'] = array();
350
351
		// Set up the sql query.
352
		$setValues = array();
353
354
		foreach ($_POST['options'] as $opt => $val)
355
			$setValues[] = array(-1, $_GET['th'], $opt, is_array($val) ? implode(',', $val) : $val);
356
357
		$old_settings = array();
358
		foreach ($_POST['default_options'] as $opt => $val)
359
		{
360
			$old_settings[] = $opt;
361
362
			$setValues[] = array(-1, 1, $opt, is_array($val) ? implode(',', $val) : $val);
363
		}
364
365
		// If we're actually inserting something..
366
		if (!empty($setValues))
367
		{
368
			// Are there options in non-default themes set that should be cleared?
369
			if (!empty($old_settings))
370
				$smcFunc['db_query']('', '
371
					DELETE FROM {db_prefix}themes
372
					WHERE id_theme != {int:default_theme}
373
						AND id_member = {int:guest_member}
374
						AND variable IN ({array_string:old_settings})',
375
					array(
376
						'default_theme' => 1,
377
						'guest_member' => -1,
378
						'old_settings' => $old_settings,
379
					)
380
				);
381
382
			$smcFunc['db_insert']('replace',
383
				'{db_prefix}themes',
384
				array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
385
				$setValues,
386
				array('id_theme', 'variable', 'id_member')
387
			);
388
		}
389
390
		cache_put_data('theme_settings-' . $_GET['th'], null, 90);
391
		cache_put_data('theme_settings-1', null, 90);
392
393
		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
394
	}
395
	elseif (isset($_POST['submit']) && $_POST['who'] == 1)
396
	{
397
		checkSession();
398
		validateToken('admin-sto');
399
400
		$_POST['options'] = empty($_POST['options']) ? array() : $_POST['options'];
401
		$_POST['options_master'] = empty($_POST['options_master']) ? array() : $_POST['options_master'];
402
		$_POST['default_options'] = empty($_POST['default_options']) ? array() : $_POST['default_options'];
403
		$_POST['default_options_master'] = empty($_POST['default_options_master']) ? array() : $_POST['default_options_master'];
404
405
		$old_settings = array();
406
		foreach ($_POST['default_options'] as $opt => $val)
407
		{
408
			if ($_POST['default_options_master'][$opt] == 0)
409
				continue;
410
			elseif ($_POST['default_options_master'][$opt] == 1)
411
			{
412
				// Delete then insert for ease of database compatibility!
413
				$smcFunc['db_query']('substring', '
414
					DELETE FROM {db_prefix}themes
415
					WHERE id_theme = {int:default_theme}
416
						AND id_member != {int:no_member}
417
						AND variable = SUBSTRING({string:option}, 1, 255)',
418
					array(
419
						'default_theme' => 1,
420
						'no_member' => 0,
421
						'option' => $opt,
422
					)
423
				);
424
				$smcFunc['db_query']('substring', '
425
					INSERT INTO {db_prefix}themes
426
						(id_member, id_theme, variable, value)
427
					SELECT id_member, 1, SUBSTRING({string:option}, 1, 255), SUBSTRING({string:value}, 1, 65534)
428
					FROM {db_prefix}members',
429
					array(
430
						'option' => $opt,
431
						'value' => (is_array($val) ? implode(',', $val) : $val),
432
					)
433
				);
434
435
				$old_settings[] = $opt;
436
			}
437
			elseif ($_POST['default_options_master'][$opt] == 2)
438
			{
439
				$smcFunc['db_query']('', '
440
					DELETE FROM {db_prefix}themes
441
					WHERE variable = {string:option_name}
442
						AND id_member > {int:no_member}',
443
					array(
444
						'no_member' => 0,
445
						'option_name' => $opt,
446
					)
447
				);
448
			}
449
		}
450
451
		// Delete options from other themes.
452
		if (!empty($old_settings))
453
			$smcFunc['db_query']('', '
454
				DELETE FROM {db_prefix}themes
455
				WHERE id_theme != {int:default_theme}
456
					AND id_member > {int:no_member}
457
					AND variable IN ({array_string:old_settings})',
458
				array(
459
					'default_theme' => 1,
460
					'no_member' => 0,
461
					'old_settings' => $old_settings,
462
				)
463
			);
464
465
		foreach ($_POST['options'] as $opt => $val)
466
		{
467
			if ($_POST['options_master'][$opt] == 0)
468
				continue;
469
			elseif ($_POST['options_master'][$opt] == 1)
470
			{
471
				// Delete then insert for ease of database compatibility - again!
472
				$smcFunc['db_query']('substring', '
473
					DELETE FROM {db_prefix}themes
474
					WHERE id_theme = {int:current_theme}
475
						AND id_member != {int:no_member}
476
						AND variable = SUBSTRING({string:option}, 1, 255)',
477
					array(
478
						'current_theme' => $_GET['th'],
479
						'no_member' => 0,
480
						'option' => $opt,
481
					)
482
				);
483
				$smcFunc['db_query']('substring', '
484
					INSERT INTO {db_prefix}themes
485
						(id_member, id_theme, variable, value)
486
					SELECT id_member, {int:current_theme}, SUBSTRING({string:option}, 1, 255), SUBSTRING({string:value}, 1, 65534)
487
					FROM {db_prefix}members',
488
					array(
489
						'current_theme' => $_GET['th'],
490
						'option' => $opt,
491
						'value' => (is_array($val) ? implode(',', $val) : $val),
492
					)
493
				);
494
			}
495
			elseif ($_POST['options_master'][$opt] == 2)
496
			{
497
				$smcFunc['db_query']('', '
498
					DELETE FROM {db_prefix}themes
499
					WHERE variable = {string:option}
500
						AND id_member > {int:no_member}
501
						AND id_theme = {int:current_theme}',
502
					array(
503
						'no_member' => 0,
504
						'current_theme' => $_GET['th'],
505
						'option' => $opt,
506
					)
507
				);
508
			}
509
		}
510
511
		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
512
	}
513
	elseif (!empty($_GET['who']) && $_GET['who'] == 2)
514
	{
515
		checkSession('get');
516
		validateToken('admin-stor', 'request');
517
518
		// Don't delete custom fields!!
519
		if ($_GET['th'] == 1)
520
		{
521
			$request = $smcFunc['db_query']('', '
522
				SELECT col_name
523
				FROM {db_prefix}custom_fields',
524
				array(
525
				)
526
			);
527
			$customFields = array();
528
			while ($row = $smcFunc['db_fetch_assoc']($request))
529
				$customFields[] = $row['col_name'];
530
			$smcFunc['db_free_result']($request);
531
		}
532
		$customFieldsQuery = empty($customFields) ? '' : ('AND variable NOT IN ({array_string:custom_fields})');
533
534
		$smcFunc['db_query']('', '
535
			DELETE FROM {db_prefix}themes
536
			WHERE id_member > {int:no_member}
537
				AND id_theme = {int:current_theme}
538
				' . $customFieldsQuery,
539
			array(
540
				'no_member' => 0,
541
				'current_theme' => $_GET['th'],
542
				'custom_fields' => empty($customFields) ? array() : $customFields,
543
			)
544
		);
545
546
		redirectexit('action=admin;area=theme;' . $context['session_var'] . '=' . $context['session_id'] . ';sa=reset');
547
	}
548
549
	$old_id = $settings['theme_id'];
550
	$old_settings = $settings;
551
552
	loadTheme($_GET['th'], false);
553
554
	loadLanguage('Profile');
555
	// @todo Should we just move these options so they are no longer theme dependant?
556
	loadLanguage('PersonalMessage');
557
558
	// Let the theme take care of the settings.
559
	loadTemplate('Settings');
560
	loadSubTemplate('options');
561
562
	// Let mods hook into the theme options.
563
	call_integration_hook('integrate_theme_options');
564
565
	$context['sub_template'] = 'set_options';
566
	$context['page_title'] = $txt['theme_settings'];
567
568
	$context['options'] = $context['theme_options'];
569
	$context['theme_settings'] = $settings;
570
571
	if (empty($_REQUEST['who']))
572
	{
573
		$request = $smcFunc['db_query']('', '
574
			SELECT variable, value
575
			FROM {db_prefix}themes
576
			WHERE id_theme IN (1, {int:current_theme})
577
				AND id_member = {int:guest_member}',
578
			array(
579
				'current_theme' => $_GET['th'],
580
				'guest_member' => -1,
581
			)
582
		);
583
		$context['theme_options'] = array();
584
		while ($row = $smcFunc['db_fetch_assoc']($request))
585
			$context['theme_options'][$row['variable']] = $row['value'];
586
		$smcFunc['db_free_result']($request);
587
588
		$context['theme_options_reset'] = false;
589
	}
590
	else
591
	{
592
		$context['theme_options'] = array();
593
		$context['theme_options_reset'] = true;
594
	}
595
596
	foreach ($context['options'] as $i => $setting)
597
	{
598
		// Just skip separators
599
		if (!is_array($setting))
600
			continue;
601
602
		// Is this disabled?
603
		if (isset($setting['enabled']) && $setting['enabled'] === false)
604
		{
605
			unset($context['options'][$i]);
606
			continue;
607
		}
608
609
		if (!isset($setting['type']) || $setting['type'] == 'bool')
610
			$context['options'][$i]['type'] = 'checkbox';
611
		elseif ($setting['type'] == 'int' || $setting['type'] == 'integer')
612
			$context['options'][$i]['type'] = 'number';
613
		elseif ($setting['type'] == 'string')
614
			$context['options'][$i]['type'] = 'text';
615
616
		if (isset($setting['options']))
617
			$context['options'][$i]['type'] = 'list';
618
619
		$context['options'][$i]['value'] = !isset($context['theme_options'][$setting['id']]) ? '' : $context['theme_options'][$setting['id']];
620
	}
621
622
	// Restore the existing theme.
623
	loadTheme($old_id, false);
624
	$settings = $old_settings;
625
626
	loadTemplate('Themes');
627
	createToken('admin-sto');
628
}
629
630
/**
631
 * Administrative global settings.
632
 * - saves and requests global theme settings. ($settings)
633
 * - loads the Admin language file.
634
 * - calls ThemeAdmin() if no theme is specified. (the theme center.)
635
 * - requires admin_forum permission.
636
 * - accessed with ?action=admin;area=theme;sa=list&th=xx.
637
 */
638
function SetThemeSettings()
639
{
640
	global $txt, $context, $settings, $modSettings, $smcFunc;
641
642
	if (empty($_GET['th']) && empty($_GET['id']))
643
		return ThemeAdmin();
644
645
	$_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
646
647
	// Select the best fitting tab.
648
	$context[$context['admin_menu_name']]['current_subsection'] = 'list';
649
650
	loadLanguage('Admin');
651
	isAllowedTo('admin_forum');
652
653
	// Validate inputs/user.
654
	if (empty($_GET['th']))
655
		fatal_lang_error('no_theme', false);
656
657
	// Fetch the smiley sets...
658
	$sets = explode(',', 'none,' . $modSettings['smiley_sets_known']);
659
	$set_names = explode("\n", $txt['smileys_none'] . "\n" . $modSettings['smiley_sets_names']);
660
	$context['smiley_sets'] = array(
661
		'' => $txt['smileys_no_default']
662
	);
663
	foreach ($sets as $i => $set)
664
		$context['smiley_sets'][$set] = $smcFunc['htmlspecialchars']($set_names[$i]);
665
666
	$old_id = $settings['theme_id'];
667
	$old_settings = $settings;
668
669
	loadTheme($_GET['th'], false);
670
671
	// Sadly we really do need to init the template.
672
	loadSubTemplate('init', 'ignore');
0 ignored issues
show
Bug introduced by
'ignore' of type string is incompatible with the type boolean expected by parameter $fatal of loadSubTemplate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

672
	loadSubTemplate('init', /** @scrutinizer ignore-type */ 'ignore');
Loading history...
673
674
	// Also load the actual themes language file - in case of special settings.
675
	loadLanguage('Settings', '', true, true);
676
677
	// And the custom language strings...
678
	loadLanguage('ThemeStrings', '', false, true);
679
680
	// Let the theme take care of the settings.
681
	loadTemplate('Settings');
682
	loadSubTemplate('settings');
683
684
	// Load the variants separately...
685
	$settings['theme_variants'] = array();
686
	if (file_exists($settings['theme_dir'] . '/index.template.php'))
687
	{
688
		$file_contents = implode('', file($settings['theme_dir'] . '/index.template.php'));
689
		if (preg_match('~\$settings\[\'theme_variants\'\]\s*=(.+?);~', $file_contents, $matches))
690
				eval('global $settings;' . $matches[0]);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
691
	}
692
693
	// Let mods hook into the theme settings.
694
	call_integration_hook('integrate_theme_settings');
695
696
	// Submitting!
697
	if (isset($_POST['save']))
698
	{
699
		checkSession();
700
		validateToken('admin-sts');
701
702
		if (empty($_POST['options']))
703
			$_POST['options'] = array();
704
		if (empty($_POST['default_options']))
705
			$_POST['default_options'] = array();
706
707
		// Make sure items are cast correctly.
708
		foreach ($context['theme_settings'] as $item)
709
		{
710
			// Disregard this item if this is just a separator.
711
			if (!is_array($item))
712
				continue;
713
714
			foreach (array('options', 'default_options') as $option)
715
			{
716
				if (!isset($_POST[$option][$item['id']]))
717
					continue;
718
				// Checkbox.
719
				elseif (empty($item['type']))
720
					$_POST[$option][$item['id']] = $_POST[$option][$item['id']] ? 1 : 0;
721
				// Number
722
				elseif ($item['type'] == 'number')
723
					$_POST[$option][$item['id']] = (int) $_POST[$option][$item['id']];
724
			}
725
		}
726
727
		// Set up the sql query.
728
		$inserts = array();
729
		foreach ($_POST['options'] as $opt => $val)
730
			$inserts[] = array(0, $_GET['th'], $opt, is_array($val) ? implode(',', $val) : $val);
731
		foreach ($_POST['default_options'] as $opt => $val)
732
			$inserts[] = array(0, 1, $opt, is_array($val) ? implode(',', $val) : $val);
733
		// If we're actually inserting something..
734
		if (!empty($inserts))
735
		{
736
			$smcFunc['db_insert']('replace',
737
				'{db_prefix}themes',
738
				array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
739
				$inserts,
740
				array('id_member', 'id_theme', 'variable')
741
			);
742
		}
743
744
		cache_put_data('theme_settings-' . $_GET['th'], null, 90);
745
		cache_put_data('theme_settings-1', null, 90);
746
747
		// Invalidate the cache.
748
		updateSettings(array('settings_updated' => time()));
749
750
		redirectexit('action=admin;area=theme;sa=list;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id']);
751
	}
752
753
	$context['sub_template'] = 'set_settings';
754
	$context['page_title'] = $txt['theme_settings'];
755
756
	foreach ($settings as $setting => $dummy)
757
	{
758
		if (!in_array($setting, array('theme_url', 'theme_dir', 'images_url', 'template_dirs')))
759
			$settings[$setting] = htmlspecialchars__recursive($settings[$setting]);
760
	}
761
762
	$context['settings'] = $context['theme_settings'];
763
	$context['theme_settings'] = $settings;
764
765
	foreach ($context['settings'] as $i => $setting)
766
	{
767
		// Separators are dummies, so leave them alone.
768
		if (!is_array($setting))
769
			continue;
770
771
		if (!isset($setting['type']) || $setting['type'] == 'bool')
772
			$context['settings'][$i]['type'] = 'checkbox';
773
		elseif ($setting['type'] == 'int' || $setting['type'] == 'integer')
774
			$context['settings'][$i]['type'] = 'number';
775
		elseif ($setting['type'] == 'string')
776
			$context['settings'][$i]['type'] = 'text';
777
778
		if (isset($setting['options']))
779
			$context['settings'][$i]['type'] = 'list';
780
781
		$context['settings'][$i]['value'] = !isset($settings[$setting['id']]) ? '' : $settings[$setting['id']];
782
	}
783
784
	// Do we support variants?
785
	if (!empty($settings['theme_variants']))
786
	{
787
		$context['theme_variants'] = array();
788
		foreach ($settings['theme_variants'] as $variant)
789
		{
790
			// Have any text, old chap?
791
			$context['theme_variants'][$variant] = array(
792
				'label' => isset($txt['variant_' . $variant]) ? $txt['variant_' . $variant] : $variant,
793
				'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'),
794
			);
795
		}
796
		$context['default_variant'] = !empty($settings['default_variant']) && isset($context['theme_variants'][$settings['default_variant']]) ? $settings['default_variant'] : $settings['theme_variants'][0];
797
	}
798
799
	// Restore the current theme.
800
	loadTheme($old_id, false);
801
802
	// Reinit just incase.
803
	loadSubTemplate('init', 'ignore');
804
805
	$settings = $old_settings;
806
807
	loadTemplate('Themes');
808
809
	// We like Kenny better than Token.
810
	createToken('admin-sts');
811
}
812
813
/**
814
 * Remove a theme from the database.
815
 * - removes an installed theme.
816
 * - requires an administrator.
817
 * - accessed with ?action=admin;area=theme;sa=remove.
818
 */
819
function RemoveTheme()
820
{
821
	global $context;
822
823
	checkSession('get');
824
825
	isAllowedTo('admin_forum');
826
	validateToken('admin-tr', 'request');
827
828
	// The theme's ID must be an integer.
829
	$themeID = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
830
831
	// You can't delete the default theme!
832
	if ($themeID == 1)
833
		fatal_lang_error('no_access', false);
834
835
	$theme_info = get_single_theme($themeID);
836
837
	// Remove it from the DB.
838
	remove_theme($themeID);
839
840
	// And remove all its files and folders too.
841
	if (!empty($theme_info) && !empty($theme_info['theme_dir']))
842
		remove_dir($theme_info['theme_dir']);
843
844
	// Go back to the list page.
845
	redirectexit('action=admin;area=theme;sa=list;' . $context['session_var'] . '=' . $context['session_id'] . ';done=removing');
846
}
847
848
/**
849
 * Handles enabling/disabling a theme from the admin center
850
 */
851
function EnableTheme()
852
{
853
	global $modSettings, $context;
854
855
	checkSession('get');
856
857
	isAllowedTo('admin_forum');
858
	validateToken('admin-tre', 'request');
859
860
	// The theme's ID must be an string.
861
	$themeID = isset($_GET['th']) ? (string) trim($_GET['th']) : (string) trim($_GET['id']);
862
863
	// Get the current list.
864
	$enableThemes = explode(',', $modSettings['enableThemes']);
865
866
	// Are we disabling it?
867
	if (isset($_GET['disabled']))
868
		$enableThemes = array_diff($enableThemes, array($themeID));
869
870
	// Nope? then enable it!
871
	else
872
		$enableThemes[] = (string) $themeID;
873
874
	// Update the setting.
875
	$enableThemes = strtr(implode(',', $enableThemes), array(',,' => ','));
876
	updateSettings(array('enableThemes' => $enableThemes));
877
878
	// Done!
879
	redirectexit('action=admin;area=theme;sa=list;' . $context['session_var'] . '=' . $context['session_id'] . ';done=' . (isset($_GET['disabled']) ? 'disabling' : 'enabling'));
880
}
881
882
/**
883
 * Choose a theme from a list.
884
 * allows an user or administrator to pick a new theme with an interface.
885
 * - can edit everyone's (u = 0), guests' (u = -1), or a specific user's.
886
 * - uses the Themes template. (pick sub template.)
887
 * - accessed with ?action=admin;area=theme;sa=pick.
888
 * @todo thought so... Might be better to split this file in ManageThemes and Themes,
889
 * with centralized admin permissions on ManageThemes.
890
 */
891
function PickTheme()
892
{
893
	global $txt, $context, $modSettings, $user_info, $language, $smcFunc, $settings, $scripturl;
894
895
	loadLanguage('Profile');
896
	loadTemplate('Themes');
897
898
	// Build the link tree.
899
	$context['linktree'][] = array(
900
		'url' => $scripturl . '?action=theme;sa=pick;u=' . (!empty($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0),
901
		'name' => $txt['theme_pick'],
902
	);
903
	$context['default_theme_id'] = $modSettings['theme_default'];
904
905
	$_SESSION['id_theme'] = 0;
906
907
	if (isset($_GET['id']))
908
		$_GET['th'] = $_GET['id'];
909
910
	// Saving a variant cause JS doesn't work - pretend it did ;)
911
	if (isset($_POST['save']))
912
	{
913
		// Which theme?
914
		foreach ($_POST['save'] as $k => $v)
915
			$_GET['th'] = (int) $k;
916
917
		if (isset($_POST['vrt'][$k]))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $k seems to be defined by a foreach iteration on line 914. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
918
			$_GET['vrt'] = $_POST['vrt'][$k];
919
	}
920
921
	// Have we made a decision, or are we just browsing?
922
	if (isset($_GET['th']))
923
	{
924
		checkSession('get');
925
926
		$_GET['th'] = (int) $_GET['th'];
927
928
		// Save for this user.
929
		if (!isset($_REQUEST['u']) || !allowedTo('admin_forum') || (!empty($_REQUEST['u']) && $_REQUEST['u'] == $user_info['id']))
930
		{
931
			updateMemberData($user_info['id'], array('id_theme' => (int) $_GET['th']));
932
933
			// A variants to save for the user?
934
			if (!empty($_GET['vrt']))
935
			{
936
				$smcFunc['db_insert']('replace',
937
					'{db_prefix}themes',
938
					array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
939
					array($_GET['th'], $user_info['id'], 'theme_variant', $_GET['vrt']),
940
					array('id_theme', 'id_member', 'variable')
941
				);
942
				cache_put_data('theme_settings-' . $_GET['th'] . ':' . $user_info['id'], null, 90);
943
944
				$_SESSION['id_variant'] = 0;
945
			}
946
947
			redirectexit('action=profile;area=theme');
948
		}
949
950
		// If changing members or guests - and there's a variant - assume changing default variant.
951
		if (!empty($_GET['vrt']) && ($_REQUEST['u'] == '0' || $_REQUEST['u'] == '-1'))
952
		{
953
			$smcFunc['db_insert']('replace',
954
				'{db_prefix}themes',
955
				array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
956
				array($_GET['th'], 0, 'default_variant', $_GET['vrt']),
957
				array('id_theme', 'id_member', 'variable')
958
			);
959
960
			// Make it obvious that it's changed
961
			cache_put_data('theme_settings-' . $_GET['th'], null, 90);
962
		}
963
964
		// For everyone.
965
		if ($_REQUEST['u'] == '0')
966
		{
967
			updateMemberData(null, array('id_theme' => (int) $_GET['th']));
968
969
			// Remove any custom variants.
970
			if (!empty($_GET['vrt']))
971
			{
972
				$smcFunc['db_query']('', '
973
					DELETE FROM {db_prefix}themes
974
					WHERE id_theme = {int:current_theme}
975
						AND variable = {string:theme_variant}',
976
					array(
977
						'current_theme' => (int) $_GET['th'],
978
						'theme_variant' => 'theme_variant',
979
					)
980
				);
981
			}
982
983
			redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
984
		}
985
		// Change the default/guest theme.
986
		elseif ($_REQUEST['u'] == '-1')
987
		{
988
			updateSettings(array('theme_guests' => (int) $_GET['th']));
989
990
			redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
991
		}
992
		// Change a specific member's theme.
993
		else
994
		{
995
			updateMemberData((int) $_REQUEST['u'], array('id_theme' => (int) $_GET['th']));
996
997
			if (!empty($_GET['vrt']) && $_GET['th'] != 0)
998
			{
999
				$smcFunc['db_insert']('replace',
1000
					'{db_prefix}themes',
1001
					array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
1002
					array($_GET['th'], (int) $_REQUEST['u'], 'theme_variant', $_GET['vrt']),
1003
					array('id_theme', 'id_member', 'variable')
1004
				);
1005
				cache_put_data('theme_settings-' . $_GET['th'] . ':' . (int) $_REQUEST['u'], null, 90);
1006
1007
				if ($user_info['id'] == $_REQUEST['u'])
1008
					$_SESSION['id_variant'] = 0;
1009
			}
1010
			elseif ($_GET['th'] == 0)
1011
			{
1012
				// Remove any custom variants.
1013
				$smcFunc['db_query']('', '
1014
					DELETE FROM {db_prefix}themes
1015
					WHERE 
1016
						variable = {string:theme_variant}
1017
						AND id_member = {int:id_member}',
1018
					array(
1019
						'theme_variant' => 'theme_variant',
1020
						'id_member' => (int) $_REQUEST['u'],
1021
					)
1022
				);
1023
			}
1024
1025
			redirectexit('action=profile;u=' . (int) $_REQUEST['u'] . ';area=theme');
1026
		}
1027
	}
1028
1029
	// Figure out who the member of the minute is, and what theme they've chosen.
1030
	if (!isset($_REQUEST['u']) || !allowedTo('admin_forum'))
1031
	{
1032
		$context['current_member'] = $user_info['id'];
1033
		$context['current_theme'] = $user_info['theme'];
1034
	}
1035
	// Everyone can't chose just one.
1036
	elseif ($_REQUEST['u'] == '0')
1037
	{
1038
		$context['current_member'] = 0;
1039
		$context['current_theme'] = 0;
1040
	}
1041
	// Guests and such...
1042
	elseif ($_REQUEST['u'] == '-1')
1043
	{
1044
		$context['current_member'] = -1;
1045
		$context['current_theme'] = $modSettings['theme_guests'];
1046
	}
1047
	// Someones else :P.
1048
	else
1049
	{
1050
		$context['current_member'] = (int) $_REQUEST['u'];
1051
1052
		$request = $smcFunc['db_query']('', '
1053
			SELECT id_theme
1054
			FROM {db_prefix}members
1055
			WHERE id_member = {int:current_member}
1056
			LIMIT 1',
1057
			array(
1058
				'current_member' => $context['current_member'],
1059
			)
1060
		);
1061
		list ($context['current_theme']) = $smcFunc['db_fetch_row']($request);
1062
		$smcFunc['db_free_result']($request);
1063
	}
1064
1065
	// Get the theme name and descriptions.
1066
	$context['available_themes'] = array();
1067
	if (!empty($modSettings['knownThemes']))
1068
	{
1069
		$request = $smcFunc['db_query']('', '
1070
			SELECT id_theme, variable, value
1071
			FROM {db_prefix}themes
1072
			WHERE variable IN ({string:name}, {string:theme_url}, {string:theme_dir}, {string:images_url}, {string:disable_user_variant})' . (!allowedTo('admin_forum') ? '
1073
				AND id_theme IN ({array_string:known_themes})' : '') . '
1074
				AND id_theme != {int:default_theme}
1075
				AND id_member = {int:no_member}
1076
				AND id_theme IN ({array_string:enable_themes})',
1077
			array(
1078
				'default_theme' => 0,
1079
				'name' => 'name',
1080
				'no_member' => 0,
1081
				'theme_url' => 'theme_url',
1082
				'theme_dir' => 'theme_dir',
1083
				'images_url' => 'images_url',
1084
				'disable_user_variant' => 'disable_user_variant',
1085
				'known_themes' => explode(',', $modSettings['knownThemes']),
1086
				'enable_themes' => explode(',', $modSettings['enableThemes']),
1087
			)
1088
		);
1089
		while ($row = $smcFunc['db_fetch_assoc']($request))
1090
		{
1091
			if (!isset($context['available_themes'][$row['id_theme']]))
1092
				$context['available_themes'][$row['id_theme']] = array(
1093
					'id' => $row['id_theme'],
1094
					'selected' => $context['current_theme'] == $row['id_theme'],
1095
					'num_users' => 0
1096
				);
1097
			$context['available_themes'][$row['id_theme']][$row['variable']] = $row['value'];
1098
		}
1099
		$smcFunc['db_free_result']($request);
1100
	}
1101
1102
	// Okay, this is a complicated problem: the default theme is 1, but they aren't allowed to access 1!
1103
	if (!isset($context['available_themes'][$modSettings['theme_guests']]))
1104
	{
1105
		$context['available_themes'][0] = array(
1106
			'num_users' => 0
1107
		);
1108
		$guest_theme = 0;
1109
	}
1110
	else
1111
		$guest_theme = $modSettings['theme_guests'];
1112
1113
	$request = $smcFunc['db_query']('', '
1114
		SELECT id_theme, COUNT(*) AS the_count
1115
		FROM {db_prefix}members
1116
		GROUP BY id_theme
1117
		ORDER BY id_theme DESC',
1118
		array(
1119
		)
1120
	);
1121
	while ($row = $smcFunc['db_fetch_assoc']($request))
1122
	{
1123
		// Figure out which theme it is they are REALLY using.
1124
		if (!empty($modSettings['knownThemes']) && !in_array($row['id_theme'], explode(',', $modSettings['knownThemes'])))
1125
			$row['id_theme'] = $guest_theme;
1126
		elseif (empty($modSettings['theme_allow']))
1127
			$row['id_theme'] = $guest_theme;
1128
1129
		if (isset($context['available_themes'][$row['id_theme']]))
1130
			$context['available_themes'][$row['id_theme']]['num_users'] += $row['the_count'];
1131
		else
1132
			$context['available_themes'][$guest_theme]['num_users'] += $row['the_count'];
1133
	}
1134
	$smcFunc['db_free_result']($request);
1135
1136
	// Get any member variant preferences.
1137
	$variant_preferences = array();
1138
	if ($context['current_member'] > 0)
1139
	{
1140
		$request = $smcFunc['db_query']('', '
1141
			SELECT id_theme, value
1142
			FROM {db_prefix}themes
1143
			WHERE variable = {string:theme_variant}
1144
				AND id_member IN ({array_int:id_member})
1145
			ORDER BY id_member ASC',
1146
			array(
1147
				'theme_variant' => 'theme_variant',
1148
				'id_member' => isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'pick' ? array(-1, $context['current_member']) : array(-1),
1149
			)
1150
		);
1151
		while ($row = $smcFunc['db_fetch_assoc']($request))
1152
			$variant_preferences[$row['id_theme']] = $row['value'];
1153
		$smcFunc['db_free_result']($request);
1154
	}
1155
1156
	// Save the setting first.
1157
	$current_images_url = $settings['images_url'];
1158
	$current_theme_variants = !empty($settings['theme_variants']) ? $settings['theme_variants'] : array();
1159
1160
	foreach ($context['available_themes'] as $id_theme => $theme_data)
1161
	{
1162
		// Don't try to load the forum or board default theme's data... it doesn't have any!
1163
		if ($id_theme == 0)
1164
			continue;
1165
1166
		// The thumbnail needs the correct path.
1167
		$settings['images_url'] = &$theme_data['images_url'];
1168
1169
		if (file_exists($theme_data['theme_dir'] . '/languages/Settings.' . $user_info['language'] . '.php'))
1170
			include($theme_data['theme_dir'] . '/languages/Settings.' . $user_info['language'] . '.php');
1171
		elseif (file_exists($theme_data['theme_dir'] . '/languages/Settings.' . $language . '.php'))
1172
			include($theme_data['theme_dir'] . '/languages/Settings.' . $language . '.php');
1173
		else
1174
		{
1175
			$txt['theme_thumbnail_href'] = $theme_data['images_url'] . '/thumbnail.png';
1176
			$txt['theme_description'] = '';
1177
		}
1178
1179
		$context['available_themes'][$id_theme]['thumbnail_href'] = $txt['theme_thumbnail_href'];
1180
		$context['available_themes'][$id_theme]['description'] = $txt['theme_description'];
1181
1182
		// Are there any variants?
1183
		if (file_exists($theme_data['theme_dir'] . '/index.template.php') && (empty($theme_data['disable_user_variant']) || allowedTo('admin_forum')))
1184
		{
1185
			$file_contents = implode('', file($theme_data['theme_dir'] . '/index.template.php'));
1186
			if (preg_match('~\$settings\[\'theme_variants\'\]\s*=(.+?);~', $file_contents, $matches))
1187
			{
1188
				$settings['theme_variants'] = array();
1189
1190
				// Fill settings up.
1191
				eval('global $settings;' . $matches[0]);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
1192
1193
				if (!empty($settings['theme_variants']))
1194
				{
1195
					loadLanguage('Settings');
1196
1197
					$context['available_themes'][$id_theme]['variants'] = array();
1198
					foreach ($settings['theme_variants'] as $variant)
1199
						$context['available_themes'][$id_theme]['variants'][$variant] = array(
1200
							'label' => isset($txt['variant_' . $variant]) ? $txt['variant_' . $variant] : $variant,
1201
							'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'),
1202
						);
1203
1204
					$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]));
1205
					if (!isset($context['available_themes'][$id_theme]['variants'][$context['available_themes'][$id_theme]['selected_variant']]['thumbnail']))
1206
						$context['available_themes'][$id_theme]['selected_variant'] = $settings['theme_variants'][0];
1207
1208
					$context['available_themes'][$id_theme]['thumbnail_href'] = $context['available_themes'][$id_theme]['variants'][$context['available_themes'][$id_theme]['selected_variant']]['thumbnail'];
1209
					// Allow themes to override the text.
1210
					$context['available_themes'][$id_theme]['pick_label'] = isset($txt['variant_pick']) ? $txt['variant_pick'] : $txt['theme_pick_variant'];
1211
				}
1212
			}
1213
		}
1214
	}
1215
	// Then return it.
1216
	$settings['images_url'] = $current_images_url;
1217
	$settings['theme_variants'] = $current_theme_variants;
1218
1219
	// As long as we're not doing the default theme...
1220
	if (!isset($_REQUEST['u']) || $_REQUEST['u'] >= 0)
1221
	{
1222
		if ($guest_theme != 0)
1223
			$context['available_themes'][0] = $context['available_themes'][$guest_theme];
1224
1225
		$context['available_themes'][0]['id'] = 0;
1226
		$context['available_themes'][0]['name'] = $txt['theme_forum_default'];
1227
		$context['available_themes'][0]['selected'] = $context['current_theme'] == 0;
1228
		$context['available_themes'][0]['description'] = $txt['theme_global_description'];
1229
	}
1230
1231
	ksort($context['available_themes']);
1232
1233
	$context['page_title'] = $txt['theme_pick'];
1234
	$context['sub_template'] = 'pick';
1235
}
1236
1237
/**
1238
 * Installs new themes, calls the respective function according to the install type.
1239
 * - puts themes in $boardurl/Themes.
1240
 * - assumes the gzip has a root directory in it. (ie default.)
1241
 * Requires admin_forum.
1242
 * Accessed with ?action=admin;area=theme;sa=install.
1243
 */
1244
function ThemeInstall()
1245
{
1246
	global $sourcedir, $txt, $context, $boarddir, $boardurl;
1247
	global $themedir, $themeurl, $smcFunc;
1248
1249
	checkSession('request');
1250
	isAllowedTo('admin_forum');
1251
1252
	require_once($sourcedir . '/Subs-Package.php');
1253
1254
	// Make it easier to change the path and url.
1255
	$themedir = $boarddir . '/Themes';
1256
	$themeurl = $boardurl . '/Themes';
1257
1258
	loadTemplate('Themes');
1259
1260
	$subActions = array(
1261
		'file' => 'InstallFile',
1262
		'copy' => 'InstallCopy',
1263
		'dir' => 'InstallDir',
1264
	);
1265
1266
	// Is there a function to call?
1267
	if (isset($_GET['do']) && !empty($_GET['do']) && isset($subActions[$_GET['do']]))
1268
	{
1269
		$action = $smcFunc['htmlspecialchars'](trim($_GET['do']));
1270
1271
		// Got any info from the specific form?
1272
		if (!isset($_POST['save_' . $action]))
1273
			fatal_lang_error('theme_install_no_action', false);
1274
1275
		validateToken('admin-t-' . $action);
1276
1277
		// Hopefully the themes directory is writable, or we might have a problem.
1278
		if (!is_writable($themedir))
1279
			fatal_lang_error('theme_install_write_error', 'critical');
1280
1281
		// Call the function and handle the result.
1282
		$result = $subActions[$action]();
1283
1284
		// Everything went better than expected!
1285
		if (!empty($result))
1286
		{
1287
			$context['sub_template'] = 'installed';
1288
			$context['page_title'] = $txt['theme_installed'];
1289
			$context['installed_theme'] = $result;
1290
		}
1291
	}
1292
1293
	// Nope, show a nice error.
1294
	else
1295
		fatal_lang_error('theme_install_no_action', false);
1296
}
1297
1298
/**
1299
 * Installs a theme from a theme package.
1300
 *
1301
 * Stores the theme files on a temp dir, on success it renames the dir to the new theme's name. Ends execution with fatal_lang_error() on any error.
1302
 * @return array The newly created theme's info.
1303
 */
1304
function InstallFile()
1305
{
1306
	global $themedir, $themeurl, $context;
1307
1308
	// Set a temp dir for dumping all required files on it.
1309
	$dirtemp = $themedir . '/temp';
1310
1311
	// Make sure the temp dir doesn't already exist
1312
	if (file_exists($dirtemp))
1313
		remove_dir($dirtemp);
1314
1315
	// Create the temp dir.
1316
	mkdir($dirtemp, 0777);
1317
1318
	// Hopefully the temp directory is writable, or we might have a problem.
1319
	if (!is_writable($dirtemp))
1320
	{
1321
		// Lets give it a try.
1322
		smf_chmod($dirtemp, '0755');
1323
1324
		// How about now?
1325
		if (!is_writable($dirtemp))
1326
			fatal_lang_error('theme_install_write_error', 'critical');
1327
	}
1328
1329
	// This happens when the admin session is gone and the user has to login again.
1330
	if (!isset($_FILES) || !isset($_FILES['theme_gz']) || empty($_FILES['theme_gz']))
1331
		redirectexit('action=admin;area=theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id']);
1332
1333
	// Another error check layer, something went wrong with the upload.
1334
	if (isset($_FILES['theme_gz']['error']) && $_FILES['theme_gz']['error'] != 0)
1335
		fatal_lang_error('theme_install_error_file_' . $_FILES['theme_gz']['error'], false);
1336
1337
	// Get the theme's name.
1338
	$name = pathinfo($_FILES['theme_gz']['name'], PATHINFO_FILENAME);
1339
	$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/', '/\.tar$/'), array('_', '.', '', ''), $name);
1340
1341
	// Start setting some vars.
1342
	$context['to_install'] = array(
1343
		'theme_dir' => $themedir . '/' . $name,
1344
		'theme_url' => $themeurl . '/' . $name,
1345
		'images_url' => $themeurl . '/' . $name . '/images',
1346
		'name' => $name,
1347
	);
1348
1349
	// Extract the file on the proper themes dir.
1350
	$extracted = read_tgz_file($_FILES['theme_gz']['tmp_name'], $dirtemp, false, true);
1351
1352
	if ($extracted)
1353
	{
1354
		// Read its info form the XML file.
1355
		$theme_info = get_theme_info($dirtemp);
1356
		$context['to_install'] += $theme_info;
1357
1358
		// Install the theme. theme_install() will return the new installed ID.
1359
		$context['to_install']['id'] = theme_install($context['to_install']);
1360
1361
		// Rename the temp dir to the actual theme name.
1362
		rename($dirtemp, $context['to_install']['theme_dir']);
1363
1364
		// return all the info.
1365
		return $context['to_install'];
1366
	}
1367
1368
	else
1369
		fatal_lang_error('theme_install_error_title', false);
1370
}
1371
1372
/**
1373
 * Makes a copy from the default theme, assigns a name for it and installs it.
1374
 *
1375
 * Creates a new .xml file containing all the theme's info.
1376
 * @return array The newly created theme's info.
1377
 */
1378
function InstallCopy()
1379
{
1380
	global $themedir, $themeurl, $settings, $smcFunc, $context;
1381
	global $forum_version;
1382
1383
	// There's gotta be something to work with.
1384
	if (!isset($_REQUEST['copy']) || empty($_REQUEST['copy']))
1385
		fatal_lang_error('theme_install_error_title', false);
1386
1387
	// Get a cleaner version.
1388
	$name = preg_replace('~[^A-Za-z0-9_\- ]~', '', $_REQUEST['copy']);
1389
1390
	// Is there a theme already named like this?
1391
	if (file_exists($themedir . '/' . $name))
1392
		fatal_lang_error('theme_install_already_dir', false);
1393
1394
	// This is a brand new theme so set all possible values.
1395
	$context['to_install'] = array(
1396
		'theme_dir' => $themedir . '/' . $name,
1397
		'theme_url' => $themeurl . '/' . $name,
1398
		'name' => $name,
1399
		'images_url' => $themeurl . '/' . $name . '/images',
1400
		'version' => '1.0',
1401
		'install_for' => '2.1 - 2.1.99, ' . strtr($forum_version, array('SMF ' => '')),
1402
		'based_on' => '',
1403
		'based_on_dir' => $themedir . '/default',
1404
	);
1405
1406
	// Create the specific dir.
1407
	umask(0);
1408
	mkdir($context['to_install']['theme_dir'], 0777);
1409
1410
	// Buy some time.
1411
	@set_time_limit(600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1411
	/** @scrutinizer ignore-unhandled */ @set_time_limit(600);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1412
	if (function_exists('apache_reset_timeout'))
1413
		@apache_reset_timeout();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for apache_reset_timeout(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1413
		/** @scrutinizer ignore-unhandled */ @apache_reset_timeout();

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1414
1415
	// Create subdirectories for css and javascript files.
1416
	mkdir($context['to_install']['theme_dir'] . '/css', 0777);
1417
	mkdir($context['to_install']['theme_dir'] . '/scripts', 0777);
1418
1419
	// Copy over the default non-theme files.
1420
	$to_copy = array('/index.php', '/index.template.php', '/css/index.css', '/css/responsive.css', '/css/slider.min.css', '/css/rtl.css', '/css/calendar.css', '/css/calendar.rtl.css', '/css/admin.css', '/scripts/theme.js');
1421
1422
	foreach ($to_copy as $file)
1423
	{
1424
		copy($settings['default_theme_dir'] . $file, $context['to_install']['theme_dir'] . $file);
1425
		smf_chmod($context['to_install']['theme_dir'] . $file, 0777);
1426
	}
1427
1428
	// And now the entire images directory!
1429
	copytree($settings['default_theme_dir'] . '/images', $context['to_install']['theme_dir'] . '/images');
1430
	package_flush_cache();
1431
1432
	// Lets get some data for the new theme.
1433
	$request = $smcFunc['db_query']('', '
1434
		SELECT variable, value
1435
		FROM {db_prefix}themes
1436
		WHERE variable IN ({string:theme_templates}, {string:theme_layers})
1437
			AND id_member = {int:no_member}
1438
			AND id_theme = {int:default_theme}',
1439
		array(
1440
			'no_member' => 0,
1441
			'default_theme' => 1,
1442
			'theme_templates' => 'theme_templates',
1443
			'theme_layers' => 'theme_layers',
1444
		)
1445
	);
1446
1447
	while ($row = $smcFunc['db_fetch_assoc']($request))
1448
	{
1449
		if ($row['variable'] == 'theme_templates')
1450
			$theme_templates = $row['value'];
1451
		elseif ($row['variable'] == 'theme_layers')
1452
			$theme_layers = $row['value'];
1453
		else
1454
			continue;
1455
	}
1456
1457
	$smcFunc['db_free_result']($request);
1458
1459
	$context['to_install'] += array(
1460
		'theme_layers' => empty($theme_layers) ? 'html,body' : $theme_layers,
1461
		'theme_templates' => empty($theme_templates) ? 'index' : $theme_templates,
1462
	);
1463
1464
	// Lets add a theme_info.xml to this theme.
1465
	$xml_info = '<' . '?xml version="1.0"?' . '>
1466
<theme-info xmlns="http://www.simplemachines.org/xml/theme-info" xmlns:smf="http://www.simplemachines.org/">
1467
<!-- For the id, always use something unique - put your name, a colon, and then the package name. -->
1468
<id>smf:' . $smcFunc['strtolower']($context['to_install']['name']) . '</id>
1469
<!-- The theme\'s version, please try to use semantic versioning. -->
1470
<version>1.0</version>
1471
<!-- Install for, the SMF versions this theme was designed for. Uses the same wildcards used in the packager manager. This field is mandatory. -->
1472
<install for="'. $context['to_install']['install_for'] . '" />
1473
<!-- Theme name, used purely for aesthetics. -->
1474
<name>' . $context['to_install']['name'] . '</name>
1475
<!-- Author: your email address or contact information. The name attribute is optional. -->
1476
<author name="Simple Machines">[email protected]</author>
1477
<!-- Website... where to get updates and more information. -->
1478
<website>https://www.simplemachines.org/</website>
1479
<!-- Template layers to use, defaults to "html,body". -->
1480
<layers>' . $context['to_install']['theme_layers'] . '</layers>
1481
<!-- Templates to load on startup. Default is "index". -->
1482
<templates>' . $context['to_install']['theme_templates'] . '</templates>
1483
<!-- Base this theme off another? Default is blank, or no. It could be "default". -->
1484
<based-on></based-on>
1485
</theme-info>';
1486
1487
	// Now write it.
1488
	$fp = @fopen($context['to_install']['theme_dir'] . '/theme_info.xml', 'w+');
1489
	if ($fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
1490
	{
1491
		fwrite($fp, $xml_info);
1492
		fclose($fp);
1493
	}
1494
1495
	// Install the theme. theme_install() will take care of possible errors.
1496
	$context['to_install']['id'] = theme_install($context['to_install']);
1497
1498
	// return the info.
1499
	return $context['to_install'];
1500
}
1501
1502
/**
1503
 * Install a theme from a specific dir
1504
 *
1505
 * Assumes the dir is located on the main Themes dir. Ends execution with fatal_lang_error() on any error.
1506
 * @return array The newly created theme's info.
1507
 */
1508
function InstallDir()
1509
{
1510
	global $themedir, $themeurl, $context;
1511
1512
	// Cannot use the theme dir as a theme dir.
1513
	if (!isset($_REQUEST['theme_dir']) || empty($_REQUEST['theme_dir']) || rtrim(realpath($_REQUEST['theme_dir']), '/\\') == realpath($themedir))
1514
		fatal_lang_error('theme_install_invalid_dir', false);
1515
1516
	// Check is there is "something" on the dir.
1517
	elseif (!is_dir($_REQUEST['theme_dir']) || !file_exists($_REQUEST['theme_dir'] . '/theme_info.xml'))
1518
		fatal_lang_error('theme_install_error', false);
1519
1520
	$name = basename($_REQUEST['theme_dir']);
1521
	$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
1522
1523
	// All good! set some needed vars.
1524
	$context['to_install'] = array(
1525
		'theme_dir' => $_REQUEST['theme_dir'],
1526
		'theme_url' => $themeurl . '/' . $name,
1527
		'name' => $name,
1528
		'images_url' => $themeurl . '/' . $name . '/images',
1529
	);
1530
1531
	// Read its info form the XML file.
1532
	$theme_info = get_theme_info($context['to_install']['theme_dir']);
1533
	$context['to_install'] += $theme_info;
1534
1535
	// Install the theme. theme_install() will take care of possible errors.
1536
	$context['to_install']['id'] = theme_install($context['to_install']);
1537
1538
	// return the info.
1539
	return $context['to_install'];
1540
}
1541
1542
/**
1543
 * Possibly the simplest and best example of how to use the template system.
1544
 *  - allows the theme to take care of actions.
1545
 *  - happens if $settings['catch_action'] is set and action isn't found
1546
 *   in the action array.
1547
 *  - can use a template, layers, sub_template, filename, and/or function.
1548
 */
1549
function WrapAction()
1550
{
1551
	global $context, $settings;
1552
1553
	// Load any necessary template(s)?
1554
	if (isset($settings['catch_action']['template']))
1555
	{
1556
		// Load both the template and language file. (but don't fret if the language file isn't there...)
1557
		loadTemplate($settings['catch_action']['template']);
1558
		loadLanguage($settings['catch_action']['template'], '', false);
1559
	}
1560
1561
	// Any special layers?
1562
	if (isset($settings['catch_action']['layers']))
1563
		$context['template_layers'] = $settings['catch_action']['layers'];
1564
1565
	// Any function to call?
1566
	if (isset($settings['catch_action']['function']))
1567
	{
1568
		$hook = $settings['catch_action']['function'];
1569
1570
		if (!isset($settings['catch_action']['filename']))
1571
			$settings['catch_action']['filename'] = '';
1572
1573
		add_integration_function('integrate_wrap_action', $hook, false, $settings['catch_action']['filename'], false);
1574
		call_integration_hook('integrate_wrap_action');
1575
	}
1576
	// And finally, the main sub template ;).
1577
	if (isset($settings['catch_action']['sub_template']))
1578
		$context['sub_template'] = $settings['catch_action']['sub_template'];
1579
}
1580
1581
/**
1582
 * Set an option via javascript.
1583
 * - sets a theme option without outputting anything.
1584
 * - can be used with javascript, via a dummy image... (which doesn't require
1585
 * the page to reload.)
1586
 * - requires someone who is logged in.
1587
 * - accessed via ?action=jsoption;var=variable;val=value;session_var=sess_id.
1588
 * - does not log access to the Who's Online log. (in index.php..)
1589
 */
1590
function SetJavaScript()
1591
{
1592
	global $settings, $user_info, $smcFunc, $options;
1593
1594
	// Check the session id.
1595
	checkSession('get');
1596
1597
	// This good-for-nothing pixel is being used to keep the session alive.
1598
	if (empty($_GET['var']) || !isset($_GET['val']))
1599
		redirectexit($settings['images_url'] . '/blank.png');
1600
1601
	// Sorry, guests can't go any further than this.
1602
	if ($user_info['is_guest'] || $user_info['id'] == 0)
1603
		obExit(false);
1604
1605
	$reservedVars = array(
1606
		'actual_theme_url',
1607
		'actual_images_url',
1608
		'base_theme_dir',
1609
		'base_theme_url',
1610
		'default_images_url',
1611
		'default_theme_dir',
1612
		'default_theme_url',
1613
		'default_template',
1614
		'images_url',
1615
		'number_recent_posts',
1616
		'smiley_sets_default',
1617
		'theme_dir',
1618
		'theme_id',
1619
		'theme_layers',
1620
		'theme_templates',
1621
		'theme_url',
1622
		'name',
1623
	);
1624
1625
	// Can't change reserved vars.
1626
	if (in_array(strtolower($_GET['var']), $reservedVars))
1627
		redirectexit($settings['images_url'] . '/blank.png');
1628
1629
	// Use a specific theme?
1630
	if (isset($_GET['th']) || isset($_GET['id']))
1631
	{
1632
		// Invalidate the current themes cache too.
1633
		cache_put_data('theme_settings-' . $settings['theme_id'] . ':' . $user_info['id'], null, 60);
1634
1635
		$settings['theme_id'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
1636
	}
1637
1638
	// If this is the admin preferences the passed value will just be an element of it.
1639
	if ($_GET['var'] == 'admin_preferences')
1640
	{
1641
		$options['admin_preferences'] = !empty($options['admin_preferences']) ? $smcFunc['json_decode']($options['admin_preferences'], true) : array();
1642
		// New thingy...
1643
		if (isset($_GET['admin_key']) && strlen($_GET['admin_key']) < 5)
1644
			$options['admin_preferences'][$_GET['admin_key']] = $_GET['val'];
1645
1646
		// Change the value to be something nice,
1647
		$_GET['val'] = $smcFunc['json_encode']($options['admin_preferences']);
1648
	}
1649
1650
	// Update the option.
1651
	$smcFunc['db_insert']('replace',
1652
		'{db_prefix}themes',
1653
		array('id_theme' => 'int', 'id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
1654
		array($settings['theme_id'], $user_info['id'], $_GET['var'], is_array($_GET['val']) ? implode(',', $_GET['val']) : $_GET['val']),
1655
		array('id_theme', 'id_member', 'variable')
1656
	);
1657
1658
	cache_put_data('theme_settings-' . $settings['theme_id'] . ':' . $user_info['id'], null, 60);
1659
1660
	// Don't output anything...
1661
	redirectexit($settings['images_url'] . '/blank.png');
1662
}
1663
1664
/**
1665
 * Shows an interface for editing the templates.
1666
 * - uses the Themes template and edit_template/edit_style sub template.
1667
 * - accessed via ?action=admin;area=theme;sa=edit
1668
 */
1669
function EditTheme()
1670
{
1671
	global $context, $scripturl, $boarddir, $smcFunc, $txt;
1672
1673
	// @todo Should this be removed?
1674
	if (isset($_REQUEST['preview']))
1675
		die('die() with fire');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1676
1677
	isAllowedTo('admin_forum');
1678
	loadTemplate('Themes');
1679
1680
	$_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) @$_GET['id'];
1681
1682
	if (empty($_GET['th']))
1683
	{
1684
		get_all_themes();
1685
1686
		foreach ($context['themes'] as $key => $theme)
1687
		{
1688
			// There has to be a Settings template!
1689
			if (!file_exists($theme['theme_dir'] . '/index.template.php') && !file_exists($theme['theme_dir'] . '/css/index.css'))
1690
				unset($context['themes'][$key]);
1691
1692
			else
1693
				$context['themes'][$key]['can_edit_style'] = file_exists($theme['theme_dir'] . '/css/index.css');
1694
		}
1695
1696
		$context['sub_template'] = 'edit_list';
1697
1698
		return 'no_themes';
1699
	}
1700
1701
	$context['session_error'] = false;
1702
1703
	// Get the directory of the theme we are editing.
1704
	$currentTheme = get_single_theme($_GET['th']);
1705
	$context['theme_id'] = $currentTheme['id'];
1706
	$context['browse_title'] = sprintf($txt['themeadmin_browsing_theme'], $currentTheme['name']);
1707
1708
	if (!file_exists($currentTheme['theme_dir'] . '/index.template.php') && !file_exists($currentTheme['theme_dir'] . '/css/index.css'))
1709
		fatal_lang_error('theme_edit_missing', false);
1710
1711
	if (!isset($_REQUEST['filename']))
1712
	{
1713
		if (isset($_GET['directory']))
1714
		{
1715
			if (substr($_GET['directory'], 0, 1) == '.')
1716
				$_GET['directory'] = '';
1717
			else
1718
			{
1719
				$_GET['directory'] = preg_replace(array('~^[\./\\:\0\n\r]+~', '~[\\\\]~', '~/[\./]+~'), array('', '/', '/'), $_GET['directory']);
1720
1721
				$temp = realpath($currentTheme['theme_dir'] . '/' . $_GET['directory']);
1722
				if (empty($temp) || substr($temp, 0, strlen(realpath($currentTheme['theme_dir']))) != realpath($currentTheme['theme_dir']))
1723
					$_GET['directory'] = '';
1724
			}
1725
		}
1726
1727
		if (isset($_GET['directory']) && $_GET['directory'] != '')
1728
		{
1729
			$context['theme_files'] = get_file_listing($currentTheme['theme_dir'] . '/' . $_GET['directory'], $_GET['directory'] . '/');
1730
1731
			$temp = dirname($_GET['directory']);
1732
			array_unshift($context['theme_files'], array(
1733
				'filename' => $temp == '.' || $temp == '' ? '/ (..)' : $temp . ' (..)',
1734
				'is_writable' => is_writable($currentTheme['theme_dir'] . '/' . $temp),
1735
				'is_directory' => true,
1736
				'is_template' => false,
1737
				'is_image' => false,
1738
				'is_editable' => false,
1739
				'href' => $scripturl . '?action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=edit;directory=' . $temp,
1740
				'size' => '',
1741
			));
1742
		}
1743
		else
1744
			$context['theme_files'] = get_file_listing($currentTheme['theme_dir'], '');
1745
		
1746
		// Do not list minified_ files
1747
		foreach($context['theme_files'] as $key=>$file)
1748
		{
1749
			if(strpos($file['filename'], 'minified_') !== FALSE)
1750
				unset($context['theme_files'][$key]);
1751
		}
1752
1753
		$context['sub_template'] = 'edit_browse';
1754
1755
		return;
1756
	}
1757
	else
1758
	{
1759
		if (substr($_REQUEST['filename'], 0, 1) == '.')
1760
			$_REQUEST['filename'] = '';
1761
		else
1762
		{
1763
			$_REQUEST['filename'] = preg_replace(array('~^[\./\\:\0\n\r]+~', '~[\\\\]~', '~/[\./]+~'), array('', '/', '/'), $_REQUEST['filename']);
1764
1765
			$temp = realpath($currentTheme['theme_dir'] . '/' . $_REQUEST['filename']);
1766
			if (empty($temp) || substr($temp, 0, strlen(realpath($currentTheme['theme_dir']))) != realpath($currentTheme['theme_dir']))
1767
				$_REQUEST['filename'] = '';
1768
		}
1769
1770
		if (empty($_REQUEST['filename']))
1771
			fatal_lang_error('theme_edit_missing', false);
1772
	}
1773
1774
	if (isset($_POST['save']))
1775
	{
1776
		if (checkSession('post', '', false) == '' && validateToken('admin-te-' . md5($_GET['th'] . '-' . $_REQUEST['filename']), 'post', false) == true)
1777
		{
1778
			if (is_array($_POST['entire_file']))
1779
				$_POST['entire_file'] = implode("\n", $_POST['entire_file']);
1780
1781
			$_POST['entire_file'] = rtrim(strtr($_POST['entire_file'], array("\r" => '', '   ' => "\t")));
1782
1783
			// Check for a parse error!
1784
			if (substr($_REQUEST['filename'], -13) == '.template.php' && is_writable($currentTheme['theme_dir']) && ini_get('display_errors'))
1785
			{
1786
				$fp = fopen($currentTheme['theme_dir'] . '/tmp_' . session_id() . '.php', 'w');
1787
				fwrite($fp, $_POST['entire_file']);
1788
				fclose($fp);
1789
1790
				$error = @file_get_contents($currentTheme['theme_url'] . '/tmp_' . session_id() . '.php');
1791
				if (preg_match('~ <b>(\d+)</b><br( /)?' . '>$~i', $error) != 0)
1792
					$error_file = $currentTheme['theme_dir'] . '/tmp_' . session_id() . '.php';
1793
				else
1794
					unlink($currentTheme['theme_dir'] . '/tmp_' . session_id() . '.php');
1795
			}
1796
1797
			if (!isset($error_file))
1798
			{
1799
				$fp = fopen($currentTheme['theme_dir'] . '/' . $_REQUEST['filename'], 'w');
1800
				fwrite($fp, $_POST['entire_file']);
1801
				fclose($fp);
1802
1803
				redirectexit('action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=edit;directory=' . dirname($_REQUEST['filename']));
1804
			}
1805
		}
1806
		// Session timed out.
1807
		else
1808
		{
1809
			loadLanguage('Errors');
1810
1811
			$context['session_error'] = true;
1812
			$context['sub_template'] = 'edit_file';
1813
1814
			// Recycle the submitted data.
1815
			if (is_array($_POST['entire_file']))
1816
				$context['entire_file'] = $smcFunc['htmlspecialchars'](implode("\n", $_POST['entire_file']));
1817
			else
1818
				$context['entire_file'] = $smcFunc['htmlspecialchars']($_POST['entire_file']);
1819
1820
			$context['edit_filename'] = $smcFunc['htmlspecialchars']($_POST['filename']);
1821
1822
			// You were able to submit it, so it's reasonable to assume you are allowed to save.
1823
			$context['allow_save'] = true;
1824
1825
			// Re-create the token so that it can be used
1826
			createToken('admin-te-' . md5($_GET['th'] . '-' . $_REQUEST['filename']));
1827
1828
			return;
1829
		}
1830
	}
1831
1832
	$context['allow_save'] = is_writable($currentTheme['theme_dir'] . '/' . $_REQUEST['filename']);
1833
	$context['allow_save_filename'] = strtr($currentTheme['theme_dir'] . '/' . $_REQUEST['filename'], array($boarddir => '...'));
1834
	$context['edit_filename'] = $smcFunc['htmlspecialchars']($_REQUEST['filename']);
1835
1836
	if (substr($_REQUEST['filename'], -4) == '.css')
1837
	{
1838
		$context['sub_template'] = 'edit_style';
1839
1840
		$context['entire_file'] = $smcFunc['htmlspecialchars'](strtr(file_get_contents($currentTheme['theme_dir'] . '/' . $_REQUEST['filename']), array("\t" => '   ')));
1841
	}
1842
	elseif (substr($_REQUEST['filename'], -13) == '.template.php')
1843
	{
1844
		$context['sub_template'] = 'edit_template';
1845
1846
		if (!isset($error_file))
1847
			$file_data = file($currentTheme['theme_dir'] . '/' . $_REQUEST['filename']);
1848
		else
1849
		{
1850
			if (preg_match('~(<b>.+?</b>:.+?<b>).+?(</b>.+?<b>\d+</b>)<br( /)?' . '>$~i', $error, $match) != 0)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error does not seem to be defined for all execution paths leading up to this point.
Loading history...
1851
				$context['parse_error'] = $match[1] . $_REQUEST['filename'] . $match[2];
1852
			$file_data = file($error_file);
1853
			unlink($error_file);
1854
		}
1855
1856
		$j = 0;
1857
		$context['file_parts'] = array(array('lines' => 0, 'line' => 1, 'data' => ''));
1858
		for ($i = 0, $n = count($file_data); $i < $n; $i++)
1859
		{
1860
			if (isset($file_data[$i + 1]) && substr($file_data[$i + 1], 0, 9) == 'function ')
1861
			{
1862
				// Try to format the functions a little nicer...
1863
				$context['file_parts'][$j]['data'] = trim($context['file_parts'][$j]['data']) . "\n";
1864
1865
				if (empty($context['file_parts'][$j]['lines']))
1866
					unset($context['file_parts'][$j]);
1867
				$context['file_parts'][++$j] = array('lines' => 0, 'line' => $i + 1, 'data' => '');
1868
			}
1869
1870
			$context['file_parts'][$j]['lines']++;
1871
			$context['file_parts'][$j]['data'] .= $smcFunc['htmlspecialchars'](strtr($file_data[$i], array("\t" => '   ')));
1872
		}
1873
1874
		$context['entire_file'] = $smcFunc['htmlspecialchars'](strtr(implode('', $file_data), array("\t" => '   ')));
1875
	}
1876
	else
1877
	{
1878
		$context['sub_template'] = 'edit_file';
1879
1880
		$context['entire_file'] = $smcFunc['htmlspecialchars'](strtr(file_get_contents($currentTheme['theme_dir'] . '/' . $_REQUEST['filename']), array("\t" => '   ')));
1881
	}
1882
1883
	// Create a special token to allow editing of multiple files.
1884
	createToken('admin-te-' . md5($_GET['th'] . '-' . $_REQUEST['filename']));
1885
}
1886
1887
/**
1888
 * Makes a copy of a template file in a new location
1889
 * @uses Themes template, copy_template sub-template.
1890
 */
1891
function CopyTemplate()
1892
{
1893
	global $context, $settings;
1894
1895
	isAllowedTo('admin_forum');
1896
	loadTemplate('Themes');
1897
1898
	$context[$context['admin_menu_name']]['current_subsection'] = 'edit';
1899
1900
	$_GET['th'] = isset($_GET['th']) ? (int) $_GET['th'] : (int) $_GET['id'];
1901
1902
	if (empty($_GET['th']))
1903
		fatal_lang_error('theme_install_invalid_id');
1904
1905
	// Get the theme info.
1906
	$theme = get_single_theme($_GET['th']);
1907
	$context['theme_id'] = $theme['id'];
1908
1909
	if (isset($_REQUEST['template']) && preg_match('~[\./\\\\:\0]~', $_REQUEST['template']) == 0)
1910
	{
1911
		if (file_exists($settings['default_theme_dir'] . '/' . $_REQUEST['template'] . '.template.php'))
1912
			$filename = $settings['default_theme_dir'] . '/' . $_REQUEST['template'] . '.template.php';
1913
1914
		else
1915
			fatal_lang_error('no_access', false);
1916
1917
		$fp = fopen($theme['theme_dir'] . '/' . $_REQUEST['template'] . '.template.php', 'w');
1918
		fwrite($fp, file_get_contents($filename));
1919
		fclose($fp);
1920
1921
		redirectexit('action=admin;area=theme;th=' . $context['theme_id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=copy');
1922
	}
1923
	elseif (isset($_REQUEST['lang_file']) && preg_match('~^[^\./\\\\:\0]\.[^\./\\\\:\0]$~', $_REQUEST['lang_file']) != 0)
1924
	{
1925
		if (file_exists($settings['default_theme_dir'] . '/languages/' . $_REQUEST['template'] . '.php'))
1926
			$filename = $settings['default_theme_dir'] . '/languages/' . $_REQUEST['template'] . '.php';
1927
1928
		else
1929
			fatal_lang_error('no_access', false);
1930
1931
		$fp = fopen($theme['theme_dir'] . '/languages/' . $_REQUEST['lang_file'] . '.php', 'w');
1932
		fwrite($fp, file_get_contents($filename));
1933
		fclose($fp);
1934
1935
		redirectexit('action=admin;area=theme;th=' . $context['theme_id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=copy');
1936
	}
1937
1938
	$templates = array();
1939
	$lang_files = array();
1940
1941
	$dir = dir($settings['default_theme_dir']);
1942
	while ($entry = $dir->read())
1943
	{
1944
		if (substr($entry, -13) == '.template.php')
1945
			$templates[] = substr($entry, 0, -13);
1946
	}
1947
	$dir->close();
1948
1949
	$dir = dir($settings['default_theme_dir'] . '/languages');
1950
	while ($entry = $dir->read())
1951
	{
1952
		if (preg_match('~^([^\.]+\.[^\.]+)\.php$~', $entry, $matches))
1953
			$lang_files[] = $matches[1];
1954
	}
1955
	$dir->close();
1956
1957
	natcasesort($templates);
1958
	natcasesort($lang_files);
1959
1960
	$context['available_templates'] = array();
1961
	foreach ($templates as $template)
1962
		$context['available_templates'][$template] = array(
1963
			'filename' => $template . '.template.php',
1964
			'value' => $template,
1965
			'already_exists' => false,
1966
			'can_copy' => is_writable($theme['theme_dir']),
1967
		);
1968
	$context['available_language_files'] = array();
1969
	foreach ($lang_files as $file)
1970
		$context['available_language_files'][$file] = array(
1971
			'filename' => $file . '.php',
1972
			'value' => $file,
1973
			'already_exists' => false,
1974
			'can_copy' => file_exists($theme['theme_dir'] . '/languages') ? is_writable($theme['theme_dir'] . '/languages') : is_writable($theme['theme_dir']),
1975
		);
1976
1977
	$dir = dir($theme['theme_dir']);
1978
	while ($entry = $dir->read())
1979
	{
1980
		if (substr($entry, -13) == '.template.php' && isset($context['available_templates'][substr($entry, 0, -13)]))
1981
		{
1982
			$context['available_templates'][substr($entry, 0, -13)]['already_exists'] = true;
1983
			$context['available_templates'][substr($entry, 0, -13)]['can_copy'] = is_writable($theme['theme_dir'] . '/' . $entry);
1984
		}
1985
	}
1986
	$dir->close();
1987
1988
	if (file_exists($theme['theme_dir'] . '/languages'))
1989
	{
1990
		$dir = dir($theme['theme_dir'] . '/languages');
1991
		while ($entry = $dir->read())
1992
		{
1993
			if (preg_match('~^([^\.]+\.[^\.]+)\.php$~', $entry, $matches) && isset($context['available_language_files'][$matches[1]]))
1994
			{
1995
				$context['available_language_files'][$matches[1]]['already_exists'] = true;
1996
				$context['available_language_files'][$matches[1]]['can_copy'] = is_writable($theme['theme_dir'] . '/languages/' . $entry);
1997
			}
1998
		}
1999
		$dir->close();
2000
	}
2001
2002
	$context['sub_template'] = 'copy_template';
2003
}
2004
2005
?>