Issues (1065)

Sources/Packages.php (1 issue)

1
<?php
2
3
/**
4
 * This file is the main Package Manager.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2025 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.5
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * This is the notoriously defunct package manager..... :/.
21
 */
22
function Packages()
23
{
24
	global $txt, $sourcedir, $context;
25
26
	// @todo Remove this!
27
	if (isset($_GET['get']) || isset($_GET['pgdownload']))
28
	{
29
		require_once($sourcedir . '/PackageGet.php');
30
		return PackageGet();
31
	}
32
33
	isAllowedTo('admin_forum');
34
35
	// Load all the basic stuff.
36
	require_once($sourcedir . '/Subs-Package.php');
37
	loadLanguage('Packages');
38
	loadTemplate('Packages', 'admin');
39
40
	$context['page_title'] = $txt['package'];
41
42
	// Delegation makes the world... that is, the package manager go 'round.
43
	$subActions = array(
44
		'browse' => 'PackageBrowse',
45
		'remove' => 'PackageRemove',
46
		'list' => 'PackageList',
47
		'ftptest' => 'PackageFTPTest',
48
		'install' => 'PackageInstallTest',
49
		'install2' => 'PackageInstall',
50
		'uninstall' => 'PackageInstallTest',
51
		'uninstall2' => 'PackageInstall',
52
		'options' => 'PackageOptions',
53
		'perms' => 'PackagePermissions',
54
		'flush' => 'FlushInstall',
55
		'examine' => 'ExamineFile',
56
		'showoperations' => 'ViewOperations',
57
	);
58
59
	// Work out exactly who it is we are calling.
60
	if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
61
		$context['sub_action'] = $_REQUEST['sa'];
62
	else
63
		$context['sub_action'] = 'browse';
64
65
	// Set up some tabs...
66
	$context[$context['admin_menu_name']]['tab_data'] = array(
67
		'title' => $txt['package_manager'],
68
		// @todo 'help' => 'registrations',
69
		'description' => $txt['package_manager_desc'],
70
		'tabs' => array(
71
			'browse' => array(
72
			),
73
			'packageget' => array(
74
				'description' => $txt['download_packages_desc'],
75
			),
76
			'perms' => array(
77
				'description' => $txt['package_file_perms_desc'],
78
			),
79
			'options' => array(
80
				'description' => $txt['package_install_options_desc'],
81
			),
82
		),
83
	);
84
85
	if ($context['sub_action'] == 'browse')
86
		loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
87
88
	call_integration_hook('integrate_manage_packages', array(&$subActions));
89
90
	// Call the function we're handing control to.
91
	call_helper($subActions[$context['sub_action']]);
92
}
93
94
/**
95
 * Test install a package.
96
 */
97
function PackageInstallTest()
98
{
99
	global $boarddir, $txt, $context, $scripturl, $sourcedir, $packagesdir, $modSettings, $smcFunc, $settings;
100
101
	// You have to specify a file!!
102
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
103
		redirectexit('action=admin;area=packages');
104
	$context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);
105
106
	// Do we have an existing id, for uninstalls and the like.
107
	$context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;
108
109
	require_once($sourcedir . '/Subs-Package.php');
110
111
	// Load up the package FTP information?
112
	create_chmod_control();
113
114
	// Make sure temp directory exists and is empty.
115
	if (file_exists($packagesdir . '/temp'))
116
		deltree($packagesdir . '/temp', false);
117
118
	if (!mktree($packagesdir . '/temp', 0755))
119
	{
120
		deltree($packagesdir . '/temp', false);
121
		if (!mktree($packagesdir . '/temp', 0777))
122
		{
123
			deltree($packagesdir . '/temp', false);
124
			create_chmod_control(array($packagesdir . '/temp/delme.tmp'), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package'], 'crash_on_error' => true));
125
126
			deltree($packagesdir . '/temp', false);
127
			if (!mktree($packagesdir . '/temp', 0777))
128
				fatal_lang_error('package_cant_download', false);
129
		}
130
	}
131
132
	$context['uninstalling'] = $_REQUEST['sa'] == 'uninstall';
133
134
	// Change our last link tree item for more information on this Packages area.
135
	$context['linktree'][count($context['linktree']) - 1] = array(
136
		'url' => $scripturl . '?action=admin;area=packages;sa=browse',
137
		'name' => $context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']
138
	);
139
	$context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']);
140
141
	$context['sub_template'] = 'view_package';
142
143
	if (!file_exists($packagesdir . '/' . $context['filename']))
144
	{
145
		deltree($packagesdir . '/temp');
146
		fatal_lang_error('package_no_file', false);
147
	}
148
149
	// Extract the files so we can get things like the readme, etc.
150
	if (is_file($packagesdir . '/' . $context['filename']))
151
	{
152
		$context['extracted_files'] = read_tgz_file($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
153
154
		if ($context['extracted_files'] && !file_exists($packagesdir . '/temp/package-info.xml'))
155
			foreach ($context['extracted_files'] as $file)
156
				if (basename($file['filename']) == 'package-info.xml')
157
				{
158
					$context['base_path'] = dirname($file['filename']) . '/';
159
					break;
160
				}
161
162
		if (!isset($context['base_path']))
163
			$context['base_path'] = '';
164
	}
165
	elseif (is_dir($packagesdir . '/' . $context['filename']))
166
	{
167
		copytree($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
168
		$context['extracted_files'] = listtree($packagesdir . '/temp');
169
		$context['base_path'] = '';
170
	}
171
	else
172
		fatal_lang_error('no_access', false);
173
174
	// Load up any custom themes we may want to install into...
175
	$request = $smcFunc['db_query']('', '
176
		SELECT id_theme, variable, value
177
		FROM {db_prefix}themes
178
		WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
179
			AND variable IN ({string:name}, {string:theme_dir})',
180
		array(
181
			'known_theme_list' => explode(',', $modSettings['knownThemes']),
182
			'default_theme' => 1,
183
			'name' => 'name',
184
			'theme_dir' => 'theme_dir',
185
		)
186
	);
187
	$theme_paths = array();
188
	while ($row = $smcFunc['db_fetch_assoc']($request))
189
		$theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
190
	$smcFunc['db_free_result']($request);
191
192
	// Get the package info...
193
	$packageInfo = getPackageInfo($context['filename']);
194
195
	if (!is_array($packageInfo))
196
		fatal_lang_error($packageInfo);
197
198
	$packageInfo['filename'] = $context['filename'];
199
	$context['package_name'] = isset($packageInfo['name']) ? $packageInfo['name'] : $context['filename'];
200
201
	// Set the type of extraction...
202
	$context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';
203
204
	// Get our validation info.
205
	$context['validation_tests'] = package_validate_installtest(array(
206
		'file_name' => $packagesdir . '/' . $context['filename'],
207
		'custom_id' => !empty($packageInfo['id']) ? $packageInfo['id'] : '',
208
		'custom_type' => $context['extract_type']
209
	));
210
211
	// The mod isn't installed.... unless proven otherwise.
212
	$context['is_installed'] = false;
213
214
	// See if it is installed?
215
	$request = $smcFunc['db_query']('', '
216
		SELECT version, themes_installed, db_changes
217
		FROM {db_prefix}log_packages
218
		WHERE package_id = {string:current_package}
219
			AND install_state != {int:not_installed}
220
		ORDER BY time_installed DESC
221
		LIMIT 1',
222
		array(
223
			'not_installed' => 0,
224
			'current_package' => $packageInfo['id'],
225
		)
226
	);
227
228
	while ($row = $smcFunc['db_fetch_assoc']($request))
229
	{
230
		$old_themes = explode(',', $row['themes_installed']);
231
		$old_version = $row['version'];
232
		$db_changes = empty($row['db_changes']) ? array() : $smcFunc['json_decode']($row['db_changes'], true);
233
	}
234
	$smcFunc['db_free_result']($request);
235
236
	$context['database_changes'] = array();
237
	if (isset($packageInfo['uninstall']['database']))
238
		$context['database_changes'][] = sprintf($txt['package_db_code'], $packageInfo['uninstall']['database']);
239
	if (!empty($db_changes))
240
	{
241
		foreach ($db_changes as $change)
242
		{
243
			if (isset($change[2]) && isset($txt['package_db_' . $change[0]]))
244
				$context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1], $change[2]);
245
			elseif (isset($txt['package_db_' . $change[0]]))
246
				$context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1]);
247
			else
248
				$context['database_changes'][] = $change[0] . '-' . $change[1] . (isset($change[2]) ? '-' . $change[2] : '');
249
		}
250
	}
251
252
	// Uninstalling?
253
	if ($context['uninstalling'])
254
	{
255
		// Wait, it's not installed yet!
256
		if (!isset($old_version) && $context['uninstalling'])
257
		{
258
			deltree($packagesdir . '/temp');
259
			fatal_lang_error('package_cant_uninstall', false);
260
		}
261
262
		$actions = parsePackageInfo($packageInfo['xml'], true, 'uninstall');
263
264
		// Gadzooks!  There's no uninstaller at all!?
265
		if (empty($actions))
266
		{
267
			deltree($packagesdir . '/temp');
268
			fatal_lang_error('package_uninstall_cannot', false);
269
		}
270
271
		// Can't edit the custom themes it's edited if you're uninstalling, they must be removed.
272
		$context['themes_locked'] = true;
273
274
		// Only let them uninstall themes it was installed into.
275
		foreach ($theme_paths as $id => $data)
276
			if ($id != 1 && !in_array($id, $old_themes))
277
				unset($theme_paths[$id]);
278
	}
279
	elseif (isset($old_version) && $old_version != $packageInfo['version'])
280
	{
281
		// Look for an upgrade...
282
		$actions = parsePackageInfo($packageInfo['xml'], true, 'upgrade', $old_version);
283
284
		// There was no upgrade....
285
		if (empty($actions))
286
			$context['is_installed'] = true;
287
		else
288
		{
289
			// Otherwise they can only upgrade themes from the first time around.
290
			foreach ($theme_paths as $id => $data)
291
				if ($id != 1 && !in_array($id, $old_themes))
292
					unset($theme_paths[$id]);
293
		}
294
	}
295
	elseif (isset($old_version) && $old_version == $packageInfo['version'])
296
		$context['is_installed'] = true;
297
298
	if (!isset($old_version) || $context['is_installed'])
299
		$actions = parsePackageInfo($packageInfo['xml'], true, 'install');
300
301
	$context['actions'] = array();
302
	$context['ftp_needed'] = false;
303
	$context['has_failure'] = false;
304
	$chmod_files = array();
305
306
	// no actions found, return so we can display an error
307
	if (empty($actions))
308
		return;
309
310
	// This will hold data about anything that can be installed in other themes.
311
	$themeFinds = array(
312
		'candidates' => array(),
313
		'other_themes' => array(),
314
	);
315
316
	// Now prepare things for the template.
317
	foreach ($actions as $action)
318
	{
319
		// Not failed until proven otherwise.
320
		$failed = false;
321
		$thisAction = array();
322
323
		if ($action['type'] == 'chmod')
324
		{
325
			$chmod_files[] = $action['filename'];
326
			continue;
327
		}
328
		elseif ($action['type'] == 'readme' || $action['type'] == 'license')
329
		{
330
			$type = 'package_' . $action['type'];
331
			if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
332
				$context[$type] = $smcFunc['htmlspecialchars'](trim(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), "\n\r"));
333
			elseif (file_exists($action['filename']))
334
				$context[$type] = $smcFunc['htmlspecialchars'](trim(file_get_contents($action['filename']), "\n\r"));
335
336
			if (!empty($action['parse_bbc']))
337
			{
338
				require_once($sourcedir . '/Subs-Post.php');
339
				$context[$type] = preg_replace('~\[[/]?html\]~i', '', $context[$type]);
340
				preparsecode($context[$type]);
341
				$context[$type] = parse_bbc($context[$type]);
342
			}
343
			else
344
				$context[$type] = nl2br($context[$type]);
345
346
			continue;
347
		}
348
		// Don't show redirects.
349
		elseif ($action['type'] == 'redirect')
350
			continue;
351
		elseif ($action['type'] == 'error')
352
		{
353
			$context['has_failure'] = true;
354
			if (isset($action['error_msg']) && isset($action['error_var']))
355
				$context['failure_details'] = sprintf($txt['package_will_fail_' . $action['error_msg']], $action['error_var']);
356
			elseif (isset($action['error_msg']))
357
				$context['failure_details'] = isset($txt['package_will_fail_' . $action['error_msg']]) ? $txt['package_will_fail_' . $action['error_msg']] : $action['error_msg'];
358
		}
359
		elseif ($action['type'] == 'modification')
360
		{
361
			if (!file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
362
			{
363
				$context['has_failure'] = true;
364
365
				$context['actions'][] = array(
366
					'type' => $txt['execute_modification'],
367
					'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.'))),
368
					'description' => $txt['package_action_missing'],
369
					'failed' => true,
370
				);
371
			}
372
			else
373
			{
374
				if ($action['boardmod'])
375
					$mod_actions = parseBoardMod(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
376
				else
377
					$mod_actions = parseModification(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
378
379
				if (count($mod_actions) == 1 && isset($mod_actions[0]) && $mod_actions[0]['type'] == 'error' && $mod_actions[0]['filename'] == '-')
380
					$mod_actions[0]['filename'] = $action['filename'];
381
382
				foreach ($mod_actions as $key => $mod_action)
383
				{
384
					// Lets get the last section of the file name.
385
					if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
386
						$actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
387
					elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
388
						$actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
389
					else
390
						$actual_filename = $key;
391
392
					if ($mod_action['type'] == 'opened')
393
						$failed = false;
394
					elseif ($mod_action['type'] == 'failure')
395
					{
396
						if (empty($mod_action['is_custom']))
397
							$context['has_failure'] = true;
398
						$failed = true;
399
					}
400
					elseif ($mod_action['type'] == 'chmod')
401
					{
402
						$chmod_files[] = $mod_action['filename'];
403
					}
404
					elseif ($mod_action['type'] == 'saved')
405
					{
406
						if (!empty($mod_action['is_custom']))
407
						{
408
							if (!isset($context['theme_actions'][$mod_action['is_custom']]))
409
								$context['theme_actions'][$mod_action['is_custom']] = array(
410
									'name' => $theme_paths[$mod_action['is_custom']]['name'],
411
									'actions' => array(),
412
									'has_failure' => $failed,
413
								);
414
							else
415
								$context['theme_actions'][$mod_action['is_custom']]['has_failure'] |= $failed;
416
417
							$context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename] = array(
418
								'type' => $txt['execute_modification'],
419
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
420
								'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
421
								'failed' => $failed,
422
							);
423
						}
424
						elseif (!isset($context['actions'][$actual_filename]))
425
						{
426
							$context['actions'][$actual_filename] = array(
427
								'type' => $txt['execute_modification'],
428
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
429
								'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
430
								'failed' => $failed,
431
							);
432
						}
433
						else
434
						{
435
							$context['actions'][$actual_filename]['failed'] |= $failed;
436
							$context['actions'][$actual_filename]['description'] = $context['actions'][$actual_filename]['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'];
437
						}
438
					}
439
					elseif ($mod_action['type'] == 'skipping')
440
					{
441
						$context['actions'][$actual_filename] = array(
442
							'type' => $txt['execute_modification'],
443
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
444
							'description' => $txt['package_action_skipping']
445
						);
446
					}
447
					elseif ($mod_action['type'] == 'missing' && empty($mod_action['is_custom']))
448
					{
449
						$context['has_failure'] = true;
450
						$context['actions'][$actual_filename] = array(
451
							'type' => $txt['execute_modification'],
452
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
453
							'description' => $txt['package_action_missing'],
454
							'failed' => true,
455
						);
456
					}
457
					elseif ($mod_action['type'] == 'error')
458
						$context['actions'][$actual_filename] = array(
459
							'type' => $txt['execute_modification'],
460
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
461
							'description' => $txt['package_action_error'],
462
							'failed' => true,
463
						);
464
				}
465
466
				// We need to loop again just to get the operations down correctly.
467
				foreach ($mod_actions as $operation_key => $mod_action)
468
				{
469
					// Lets get the last section of the file name.
470
					if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
471
						$actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
472
					elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
473
						$actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
474
					else
475
						$actual_filename = $key;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key does not seem to be defined for all execution paths leading up to this point.
Loading history...
476
477
					// We just need it for actual parse changes.
478
					if (!in_array($mod_action['type'], array('error', 'result', 'opened', 'saved', 'end', 'missing', 'skipping', 'chmod')))
479
					{
480
						if (empty($mod_action['is_custom']))
481
							$context['actions'][$actual_filename]['operations'][] = array(
482
								'type' => $txt['execute_modification'],
483
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
484
								'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
485
								'position' => $mod_action['position'],
486
								'operation_key' => $operation_key,
487
								'filename' => $action['filename'],
488
								'is_boardmod' => $action['boardmod'],
489
								'failed' => $mod_action['failed'],
490
								'ignore_failure' => !empty($mod_action['ignore_failure']),
491
							);
492
493
						// Themes are under the saved type.
494
						if (isset($mod_action['is_custom']) && isset($context['theme_actions'][$mod_action['is_custom']]))
495
							$context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename]['operations'][] = array(
496
								'type' => $txt['execute_modification'],
497
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
498
								'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
499
								'position' => $mod_action['position'],
500
								'operation_key' => $operation_key,
501
								'filename' => $action['filename'],
502
								'is_boardmod' => $action['boardmod'],
503
								'failed' => $mod_action['failed'],
504
								'ignore_failure' => !empty($mod_action['ignore_failure']),
505
							);
506
					}
507
				}
508
			}
509
		}
510
		elseif ($action['type'] == 'code')
511
		{
512
			$thisAction = array(
513
				'type' => $txt['execute_code'],
514
				'action' => $smcFunc['htmlspecialchars']($action['filename']),
515
			);
516
		}
517
		elseif ($action['type'] == 'database' && !$context['uninstalling'])
518
		{
519
			$thisAction = array(
520
				'type' => $txt['execute_database_changes'],
521
				'action' => $smcFunc['htmlspecialchars']($action['filename']),
522
			);
523
		}
524
		elseif (in_array($action['type'], array('create-dir', 'create-file')))
525
		{
526
			$thisAction = array(
527
				'type' => $txt['package_create'] . ' ' . ($action['type'] == 'create-dir' ? $txt['package_tree'] : $txt['package_file']),
528
				'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
529
			);
530
		}
531
		elseif ($action['type'] == 'hook')
532
		{
533
			$action['description'] = !isset($action['hook'], $action['function']) ? $txt['package_action_failure'] : $txt['package_action_success'];
534
535
			if (!isset($action['hook'], $action['function']))
536
				$context['has_failure'] = true;
537
538
			$thisAction = array(
539
				'type' => $action['reverse'] ? $txt['execute_hook_remove'] : $txt['execute_hook_add'],
540
				'action' => sprintf($txt['execute_hook_action' . ($action['reverse'] ? '_inverse' : '')], $smcFunc['htmlspecialchars']($action['hook'])),
541
			);
542
		}
543
		elseif ($action['type'] == 'credits')
544
		{
545
			$thisAction = array(
546
				'type' => $txt['execute_credits_add'],
547
				'action' => sprintf($txt['execute_credits_action'], $smcFunc['htmlspecialchars']($action['title'])),
548
			);
549
		}
550
		elseif ($action['type'] == 'requires')
551
		{
552
			$installed = false;
553
			$version = true;
554
555
			// package missing required values?
556
			if (!isset($action['id']))
557
				$context['has_failure'] = true;
558
			else
559
			{
560
				// See if this dependancy is installed
561
				$request = $smcFunc['db_query']('', '
562
					SELECT version
563
					FROM {db_prefix}log_packages
564
					WHERE package_id = {string:current_package}
565
						AND install_state != {int:not_installed}
566
					ORDER BY time_installed DESC
567
					LIMIT 1',
568
					array(
569
						'not_installed' => 0,
570
						'current_package' => $action['id'],
571
					)
572
				);
573
				$installed = ($smcFunc['db_num_rows']($request) !== 0);
574
				if ($installed)
575
					list ($version) = $smcFunc['db_fetch_row']($request);
576
				$smcFunc['db_free_result']($request);
577
578
				// do a version level check (if requested) in the most basic way
579
				$version = (isset($action['version']) ? $version == $action['version'] : true);
580
			}
581
582
			// Set success or failure information
583
			$action['description'] = ($installed && $version) ? $txt['package_action_success'] : $txt['package_action_failure'];
584
			$context['has_failure'] = !($installed && $version);
585
586
			$thisAction = array(
587
				'type' => $txt['package_requires'],
588
				'action' => $txt['package_check_for'] . ' ' . $action['id'] . (isset($action['version']) ? (' / ' . ($version ? $action['version'] : '<span class="error">' . $action['version'] . '</span>')) : ''),
589
			);
590
		}
591
		elseif (in_array($action['type'], array('require-dir', 'require-file')))
592
		{
593
			// Do this one...
594
			$thisAction = array(
595
				'type' => $txt['package_extract'] . ' ' . ($action['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
596
				'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
597
			);
598
599
			// Could this be theme related?
600
			if (!empty($action['unparsed_destination']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_destination'], $matches))
601
			{
602
				// Is the action already stated?
603
				$theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
604
				// If it's not auto do we think we have something we can act upon?
605
				if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
606
					$theme_action = '';
607
				// ... or if it's auto do we even want to do anything?
608
				elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
609
					$theme_action = '';
610
611
				// So, we still want to do something?
612
				if ($theme_action != '')
613
					$themeFinds['candidates'][] = $action;
614
				// Otherwise is this is going into another theme record it.
615
				elseif ($matches[1] == 'themes_dir')
616
					$themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_destination']), array('\\' => '/')) . '/' . basename($action['filename']));
617
			}
618
		}
619
		elseif (in_array($action['type'], array('move-dir', 'move-file')))
620
			$thisAction = array(
621
				'type' => $txt['package_move'] . ' ' . ($action['type'] == 'move-dir' ? $txt['package_tree'] : $txt['package_file']),
622
				'action' => $smcFunc['htmlspecialchars'](strtr($action['source'], array($boarddir => '.'))) . ' => ' . $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
623
			);
624
		elseif (in_array($action['type'], array('remove-dir', 'remove-file')))
625
		{
626
			$thisAction = array(
627
				'type' => $txt['package_delete'] . ' ' . ($action['type'] == 'remove-dir' ? $txt['package_tree'] : $txt['package_file']),
628
				'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.')))
629
			);
630
631
			// Could this be theme related?
632
			if (!empty($action['unparsed_filename']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_filename'], $matches))
633
			{
634
				// Is the action already stated?
635
				$theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
636
				$action['unparsed_destination'] = $action['unparsed_filename'];
637
638
				// If it's not auto do we think we have something we can act upon?
639
				if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
640
					$theme_action = '';
641
				// ... or if it's auto do we even want to do anything?
642
				elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
643
					$theme_action = '';
644
645
				// So, we still want to do something?
646
				if ($theme_action != '')
647
					$themeFinds['candidates'][] = $action;
648
				// Otherwise is this is going into another theme record it.
649
				elseif ($matches[1] == 'themes_dir')
650
					$themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_filename']), array('\\' => '/')) . '/' . basename($action['filename']));
651
			}
652
		}
653
654
		if (empty($thisAction))
655
			continue;
656
657
		if (!in_array($action['type'], array('hook', 'credits')))
658
		{
659
			if ($context['uninstalling'])
660
				$file = in_array($action['type'], array('remove-dir', 'remove-file')) ? $action['filename'] : $packagesdir . '/temp/' . $context['base_path'] . $action['filename'];
661
			else
662
				$file = $packagesdir . '/temp/' . $context['base_path'] . $action['filename'];
663
		}
664
665
		// Don't fail if a file/directory we're trying to create doesn't exist...
666
		if (isset($action['filename']) && !file_exists($file) && !in_array($action['type'], array('create-dir', 'create-file')) && $action['error'] != 'ignore')
667
		{
668
			$context['has_failure'] = true;
669
670
			$thisAction += array(
671
				'description' => $txt['package_action_missing'],
672
				'failed' => true,
673
			);
674
		}
675
676
		// @todo None given?
677
		if (empty($thisAction['description']))
678
			$thisAction['description'] = isset($action['description']) ? $action['description'] : '';
679
680
		$context['actions'][] = $thisAction;
681
	}
682
683
	// Have we got some things which we might want to do "multi-theme"?
684
	if (!empty($themeFinds['candidates']))
685
	{
686
		foreach ($themeFinds['candidates'] as $action_data)
687
		{
688
			// Get the part of the file we'll be dealing with.
689
			preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir)(\\|/)*(.+)*~i', $action_data['unparsed_destination'], $matches);
690
691
			if ($matches[1] == 'imagesdir')
692
				$path = '/' . basename($settings['default_images_url']);
693
			elseif ($matches[1] == 'languagedir' || $matches[1] == 'languages_dir')
694
				$path = '/languages';
695
			else
696
				$path = '';
697
698
			if (!empty($matches[3]))
699
				$path .= $matches[3];
700
701
			if (!$context['uninstalling'])
702
				$path .= '/' . basename($action_data['filename']);
703
704
			// Loop through each custom theme to note it's candidacy!
705
			foreach ($theme_paths as $id => $theme_data)
706
			{
707
				if (isset($theme_data['theme_dir']) && $id != 1)
708
				{
709
					$real_path = $theme_data['theme_dir'] . $path;
710
711
					// Confirm that we don't already have this dealt with by another entry.
712
					if (!in_array(strtolower(strtr($real_path, array('\\' => '/'))), $themeFinds['other_themes']))
713
					{
714
						// Check if we will need to chmod this.
715
						if (!mktree(dirname($real_path), false))
716
						{
717
							$temp = dirname($real_path);
718
							while (!file_exists($temp) && strlen($temp) > 1)
719
								$temp = dirname($temp);
720
							$chmod_files[] = $temp;
721
						}
722
723
						if ($action_data['type'] == 'require-dir' && !is_writable($real_path) && (file_exists($real_path) || !is_writable(dirname($real_path))))
724
							$chmod_files[] = $real_path;
725
726
						if (!isset($context['theme_actions'][$id]))
727
							$context['theme_actions'][$id] = array(
728
								'name' => $theme_data['name'],
729
								'actions' => array(),
730
							);
731
732
						if ($context['uninstalling'])
733
							$context['theme_actions'][$id]['actions'][] = array(
734
								'type' => $txt['package_delete'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
735
								'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
736
								'description' => '',
737
								'value' => base64_encode($smcFunc['json_encode'](array('type' => $action_data['type'], 'orig' => $action_data['filename'], 'future' => $real_path, 'id' => $id))),
738
								'not_mod' => true,
739
							);
740
						else
741
							$context['theme_actions'][$id]['actions'][] = array(
742
								'type' => $txt['package_extract'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
743
								'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
744
								'description' => '',
745
								'value' => base64_encode($smcFunc['json_encode'](array('type' => $action_data['type'], 'orig' => $action_data['destination'], 'future' => $real_path, 'id' => $id))),
746
								'not_mod' => true,
747
							);
748
					}
749
				}
750
			}
751
		}
752
	}
753
754
	// Trash the cache... which will also check permissions for us!
755
	package_flush_cache(true);
756
757
	if (file_exists($packagesdir . '/temp'))
758
		deltree($packagesdir . '/temp');
759
760
	if (!empty($chmod_files))
761
	{
762
		$ftp_status = create_chmod_control($chmod_files);
763
		$context['ftp_needed'] = !empty($ftp_status['files']['notwritable']) && !empty($context['package_ftp']);
764
	}
765
766
	$context['post_url'] = $scripturl . '?action=admin;area=packages;sa=' . ($context['uninstalling'] ? 'uninstall' : 'install') . ($context['ftp_needed'] ? '' : '2') . ';package=' . $context['filename'] . ';pid=' . $context['install_id'];
767
	checkSubmitOnce('register');
768
}
769
770
/**
771
 * Apply another type of (avatar, language, etc.) package.
772
 */
773
function PackageInstall()
774
{
775
	global $txt, $context, $boardurl, $scripturl, $sourcedir, $packagesdir, $modSettings;
776
	global $user_info, $smcFunc;
777
778
	// Make sure we don't install this mod twice.
779
	checkSubmitOnce('check');
780
	checkSession();
781
782
	// If there's no file, what are we installing?
783
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
784
		redirectexit('action=admin;area=packages');
785
	$context['filename'] = $_REQUEST['package'];
786
787
	// If this is an uninstall, we'll have an id.
788
	$context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;
789
790
	require_once($sourcedir . '/Subs-Package.php');
791
792
	// @todo Perhaps do it in steps, if necessary?
793
794
	$context['uninstalling'] = $_REQUEST['sa'] == 'uninstall2';
795
796
	// Set up the linktree for other.
797
	$context['linktree'][count($context['linktree']) - 1] = array(
798
		'url' => $scripturl . '?action=admin;area=packages;sa=browse',
799
		'name' => $context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']
800
	);
801
	$context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']);
802
803
	$context['sub_template'] = 'extract_package';
804
805
	if (!file_exists($packagesdir . '/' . $context['filename']))
806
		fatal_lang_error('package_no_file', false);
807
808
	// Load up the package FTP information?
809
	create_chmod_control(array(), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package']));
810
811
	// Make sure temp directory exists and is empty!
812
	if (file_exists($packagesdir . '/temp'))
813
		deltree($packagesdir . '/temp', false);
814
	else
815
		mktree($packagesdir . '/temp', 0777);
816
817
	// Let the unpacker do the work.
818
	if (is_file($packagesdir . '/' . $context['filename']))
819
	{
820
		$context['extracted_files'] = read_tgz_file($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
821
822
		if (!file_exists($packagesdir . '/temp/package-info.xml'))
823
			foreach ($context['extracted_files'] as $file)
824
				if (basename($file['filename']) == 'package-info.xml')
825
				{
826
					$context['base_path'] = dirname($file['filename']) . '/';
827
					break;
828
				}
829
830
		if (!isset($context['base_path']))
831
			$context['base_path'] = '';
832
	}
833
	elseif (is_dir($packagesdir . '/' . $context['filename']))
834
	{
835
		copytree($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
836
		$context['extracted_files'] = listtree($packagesdir . '/temp');
837
		$context['base_path'] = '';
838
	}
839
	else
840
		fatal_lang_error('no_access', false);
841
842
	// Are we installing this into any custom themes?
843
	$custom_themes = array(1);
844
	$known_themes = explode(',', $modSettings['knownThemes']);
845
	if (!empty($_POST['custom_theme']))
846
	{
847
		foreach ($_POST['custom_theme'] as $tid)
848
			if (in_array($tid, $known_themes))
849
				$custom_themes[] = (int) $tid;
850
	}
851
852
	// Now load up the paths of the themes that we need to know about.
853
	$request = $smcFunc['db_query']('', '
854
		SELECT id_theme, variable, value
855
		FROM {db_prefix}themes
856
		WHERE id_theme IN ({array_int:custom_themes})
857
			AND variable IN ({string:name}, {string:theme_dir})',
858
		array(
859
			'custom_themes' => $custom_themes,
860
			'name' => 'name',
861
			'theme_dir' => 'theme_dir',
862
		)
863
	);
864
	$theme_paths = array();
865
	$themes_installed = array(1);
866
867
	while ($row = $smcFunc['db_fetch_assoc']($request))
868
		$theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
869
870
	$smcFunc['db_free_result']($request);
871
872
	// Are there any theme copying that we want to take place?
873
	$context['theme_copies'] = array(
874
		'require-file' => array(),
875
		'require-dir' => array(),
876
	);
877
	if (!empty($_POST['theme_changes']))
878
	{
879
		foreach ($_POST['theme_changes'] as $change)
880
		{
881
			if (empty($change))
882
				continue;
883
			$theme_data = $smcFunc['json_decode'](base64_decode($change), true);
884
			if (empty($theme_data['type']))
885
				continue;
886
887
			$themes_installed[] = $theme_data['id'];
888
			$context['theme_copies'][$theme_data['type']][$theme_data['orig']][] = $theme_data['future'];
889
		}
890
	}
891
892
	// Get the package info...
893
	$packageInfo = getPackageInfo($context['filename']);
894
	if (!is_array($packageInfo))
895
		fatal_lang_error($packageInfo);
896
897
	if (is_dir($packagesdir . '/' . $context['filename']))
898
		$context['package_sha256_hash'] = '';
899
	else
900
		$context['package_sha256_hash'] = hash_file('sha256', $packagesdir . '/' . $context['filename']);
901
	$packageInfo['filename'] = $context['filename'];
902
903
	// Set the type of extraction...
904
	$context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';
905
906
	// Create a backup file to roll back to! (but if they do this more than once, don't run it a zillion times.)
907
	if (!empty($modSettings['package_make_full_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['filename'] . ($context['uninstalling'] ? '$$' : '$')))
908
	{
909
		$_SESSION['last_backup_for'] = $context['filename'] . ($context['uninstalling'] ? '$$' : '$');
910
		$result = package_create_backup(($context['uninstalling'] ? 'backup_' : 'before_') . strtok($context['filename'], '.'));
911
		if (!$result)
912
			fatal_lang_error('could_not_package_backup', false);
913
	}
914
915
	// The mod isn't installed.... unless proven otherwise.
916
	$context['is_installed'] = false;
917
918
	// Is it actually installed?
919
	$request = $smcFunc['db_query']('', '
920
		SELECT version, themes_installed, db_changes
921
		FROM {db_prefix}log_packages
922
		WHERE package_id = {string:current_package}
923
			AND install_state != {int:not_installed}
924
		ORDER BY time_installed DESC
925
		LIMIT 1',
926
		array(
927
			'not_installed' => 0,
928
			'current_package' => $packageInfo['id'],
929
		)
930
	);
931
	while ($row = $smcFunc['db_fetch_assoc']($request))
932
	{
933
		$old_themes = explode(',', $row['themes_installed']);
934
		$old_version = $row['version'];
935
		$db_changes = empty($row['db_changes']) ? array() : $smcFunc['json_decode']($row['db_changes'], true);
936
	}
937
	$smcFunc['db_free_result']($request);
938
939
	// Wait, it's not installed yet!
940
	// @todo Replace with a better error message!
941
	if (!isset($old_version) && $context['uninstalling'])
942
	{
943
		deltree($packagesdir . '/temp');
944
		fatal_error('Hacker?', false);
945
	}
946
	// Uninstalling?
947
	elseif ($context['uninstalling'])
948
	{
949
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'uninstall');
950
951
		// Gadzooks!  There's no uninstaller at all!?
952
		if (empty($install_log))
953
			fatal_lang_error('package_uninstall_cannot', false);
954
955
		// They can only uninstall from what it was originally installed into.
956
		foreach ($theme_paths as $id => $data)
957
			if ($id != 1 && !in_array($id, $old_themes))
958
				unset($theme_paths[$id]);
959
960
		$context['keep_url'] = $scripturl . '?action=admin;area=packages;sa=browse;' . $context['session_var'] . '=' . $context['session_id'];
961
		$context['remove_url'] = $scripturl . '?action=admin;area=packages;sa=remove;package=' . $context['filename'] . ';' . $context['session_var'] . '=' . $context['session_id'];
962
	}
963
	elseif (isset($old_version) && $old_version != $packageInfo['version'])
964
	{
965
		// Look for an upgrade...
966
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'upgrade', $old_version);
967
968
		// There was no upgrade....
969
		if (empty($install_log))
970
			$context['is_installed'] = true;
971
		else
972
		{
973
			// Upgrade previous themes only!
974
			foreach ($theme_paths as $id => $data)
975
				if ($id != 1 && !in_array($id, $old_themes))
976
					unset($theme_paths[$id]);
977
		}
978
	}
979
	elseif (isset($old_version) && $old_version == $packageInfo['version'])
980
		$context['is_installed'] = true;
981
982
	if (!isset($old_version) || $context['is_installed'])
983
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'install');
984
985
	// Disable background tasks while the code is in flux.
986
	require_once($sourcedir . '/Subs-Admin.php');
987
	updateSettingsFile(['package_installing' => true]);
988
989
	$context['install_finished'] = false;
990
991
	// @todo Make a log of any errors that occurred and output them?
992
993
	if (!empty($install_log))
994
	{
995
		$failed_steps = array();
996
		$failed_count = 0;
997
998
		foreach ($install_log as $action)
999
		{
1000
			$failed_count++;
1001
1002
			if ($action['type'] == 'modification' && !empty($action['filename']))
1003
			{
1004
				if ($action['boardmod'])
1005
					$mod_actions = parseBoardMod(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
1006
				else
1007
					$mod_actions = parseModification(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
1008
1009
				// Any errors worth noting?
1010
				foreach ($mod_actions as $key => $modAction)
1011
				{
1012
					if ($modAction['type'] == 'failure')
1013
						$failed_steps[] = array(
1014
							'file' => $modAction['filename'],
1015
							'large_step' => $failed_count,
1016
							'sub_step' => $key,
1017
							'theme' => 1,
1018
						);
1019
1020
					// Gather the themes we installed into.
1021
					if (!empty($modAction['is_custom']))
1022
						$themes_installed[] = $modAction['is_custom'];
1023
				}
1024
			}
1025
			elseif ($action['type'] == 'code' && !empty($action['filename']))
1026
			{
1027
				// This is just here as reference for what is available.
1028
				global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $smcFunc;
1029
1030
				// Now include the file and be done with it ;).
1031
				if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
1032
					require($packagesdir . '/temp/' . $context['base_path'] . $action['filename']);
1033
			}
1034
			elseif ($action['type'] == 'credits')
1035
			{
1036
				// Time to build the billboard
1037
				$credits_tag = array(
1038
					'url' => $action['url'],
1039
					'license' => $action['license'],
1040
					'licenseurl' => $action['licenseurl'],
1041
					'copyright' => $action['copyright'],
1042
					'title' => $action['title'],
1043
				);
1044
			}
1045
			elseif ($action['type'] == 'hook' && isset($action['hook'], $action['function']))
1046
			{
1047
				// Set the system to ignore hooks, but only if it wasn't changed before.
1048
				if (!isset($context['ignore_hook_errors']))
1049
					$context['ignore_hook_errors'] = true;
1050
1051
				if ($action['reverse'])
1052
					remove_integration_function($action['hook'], $action['function'], true, $action['include_file'], $action['object']);
1053
				else
1054
					add_integration_function($action['hook'], $action['function'], true, $action['include_file'], $action['object']);
1055
			}
1056
			// Only do the database changes on uninstall if requested.
1057
			elseif ($action['type'] == 'database' && !empty($action['filename']) && (!$context['uninstalling'] || !empty($_POST['do_db_changes'])))
1058
			{
1059
				// These can also be there for database changes.
1060
				global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $smcFunc;
1061
				global $db_package_log;
1062
1063
				// We'll likely want the package specific database functionality!
1064
				db_extend('packages');
1065
1066
				// Let the file work its magic ;)
1067
				if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
1068
					require($packagesdir . '/temp/' . $context['base_path'] . $action['filename']);
1069
			}
1070
			// Handle a redirect...
1071
			elseif ($action['type'] == 'redirect' && !empty($action['redirect_url']))
1072
			{
1073
				$context['redirect_url'] = $action['redirect_url'];
1074
				$context['redirect_text'] = !empty($action['filename']) && file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']) ? $smcFunc['htmlspecialchars'](file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename'])) : ($context['uninstalling'] ? $txt['package_uninstall_done'] : $txt['package_installed_done']);
1075
				$context['redirect_timeout'] = empty($action['redirect_timeout']) ? 5 : (int) ceil($action['redirect_timeout'] / 1000);
1076
				if (!empty($action['parse_bbc']))
1077
				{
1078
					require_once($sourcedir . '/Subs-Post.php');
1079
					$context['redirect_text'] = preg_replace('~\[[/]?html\]~i', '', $context['redirect_text']);
1080
					preparsecode($context['redirect_text']);
1081
					$context['redirect_text'] = parse_bbc($context['redirect_text']);
1082
				}
1083
1084
				// Parse out a couple of common urls.
1085
				$urls = array(
1086
					'$boardurl' => $boardurl,
1087
					'$scripturl' => $scripturl,
1088
					'$session_var' => $context['session_var'],
1089
					'$session_id' => $context['session_id'],
1090
				);
1091
1092
				$context['redirect_url'] = strtr($context['redirect_url'], $urls);
1093
			}
1094
		}
1095
1096
		package_flush_cache();
1097
1098
		// See if this is already installed, and change it's state as required.
1099
		$request = $smcFunc['db_query']('', '
1100
			SELECT package_id, install_state, db_changes
1101
			FROM {db_prefix}log_packages
1102
			WHERE install_state != {int:not_installed}
1103
				AND package_id = {string:current_package}
1104
				' . ($context['install_id'] ? ' AND id_install = {int:install_id} ' : '') . '
1105
			ORDER BY time_installed DESC
1106
			LIMIT 1',
1107
			array(
1108
				'not_installed' => 0,
1109
				'install_id' => $context['install_id'],
1110
				'current_package' => $packageInfo['id'],
1111
			)
1112
		);
1113
		$is_upgrade = false;
1114
		while ($row = $smcFunc['db_fetch_assoc']($request))
1115
		{
1116
			// Uninstalling?
1117
			if ($context['uninstalling'])
1118
			{
1119
				$smcFunc['db_query']('', '
1120
					UPDATE {db_prefix}log_packages
1121
					SET install_state = {int:not_installed}, member_removed = {string:member_name},
1122
						id_member_removed = {int:current_member}, time_removed = {int:current_time}, sha256_hash = {string:package_hash}
1123
					WHERE package_id = {string:package_id}
1124
						AND id_install = {int:install_id}',
1125
					array(
1126
						'current_member' => $user_info['id'],
1127
						'not_installed' => 0,
1128
						'current_time' => time(),
1129
						'package_id' => $row['package_id'],
1130
						'member_name' => $user_info['name'],
1131
						'install_id' => $context['install_id'],
1132
						'package_hash' => $context['package_sha256_hash'],
1133
					)
1134
				);
1135
			}
1136
			// Otherwise must be an upgrade.
1137
			else
1138
			{
1139
				$is_upgrade = true;
1140
				$old_db_changes = empty($row['db_changes']) ? array() : $smcFunc['json_decode']($row['db_changes'], true);
1141
1142
				// Mark the old version as uninstalled
1143
				$smcFunc['db_query']('', '
1144
					UPDATE {db_prefix}log_packages
1145
					SET install_state = {int:not_installed}, member_removed = {string:member_name},
1146
						id_member_removed = {int:current_member}, time_removed = {int:current_time}, sha256_hash = {string:package_hash}
1147
					WHERE package_id = {string:package_id}
1148
						AND version = {string:old_version}',
1149
					array(
1150
						'current_member' => $user_info['id'],
1151
						'not_installed' => 0,
1152
						'current_time' => time(),
1153
						'package_id' => $row['package_id'],
1154
						'member_name' => $user_info['name'],
1155
						'old_version' => $old_version,
1156
						'package_hash' => $context['package_sha256_hash'],
1157
					)
1158
				);
1159
			}
1160
		}
1161
1162
		// Assuming we're not uninstalling, add the entry.
1163
		if (!$context['uninstalling'])
1164
		{
1165
			// Reload the settings table for mods that have altered them upon installation
1166
			reloadSettings();
1167
1168
			// Any db changes from older version?
1169
			if (!empty($old_db_changes))
1170
				$db_package_log = empty($db_package_log) ? $old_db_changes : array_merge($old_db_changes, $db_package_log);
1171
1172
			// If there are some database changes we might want to remove then filter them out.
1173
			if (!empty($db_package_log))
1174
			{
1175
				// We're really just checking for entries which are create table AND add columns (etc).
1176
				$tables = array();
1177
1178
				usort($db_package_log, function($a, $b)
1179
				{
1180
					if ($a[0] == $b[0])
1181
						return 0;
1182
					return $a[0] == 'remove_table' ? -1 : 1;
1183
				});
1184
1185
				foreach ($db_package_log as $k => $log)
1186
				{
1187
					if ($log[0] == 'remove_table')
1188
						$tables[] = $log[1];
1189
					elseif (in_array($log[1], $tables))
1190
						unset($db_package_log[$k]);
1191
				}
1192
				$db_changes = $smcFunc['json_encode']($db_package_log);
1193
			}
1194
			else
1195
				$db_changes = '';
1196
1197
			// What themes did we actually install?
1198
			$themes_installed = array_unique($themes_installed);
1199
			$themes_installed = implode(',', $themes_installed);
1200
1201
			// What failed steps?
1202
			$failed_step_insert = $smcFunc['json_encode']($failed_steps);
1203
1204
			// Un-sanitize things before we insert them...
1205
			$keys = array('filename', 'name', 'id', 'version');
1206
			foreach ($keys as $key)
1207
			{
1208
				// Yay for variable variables...
1209
				${"package_$key"} = un_htmlspecialchars($packageInfo[$key]);
1210
			}
1211
1212
			// Credits tag?
1213
			$credits_tag = (empty($credits_tag)) ? '' : $smcFunc['json_encode']($credits_tag);
1214
			$smcFunc['db_insert']('',
1215
				'{db_prefix}log_packages',
1216
				array(
1217
					'filename' => 'string', 'name' => 'string', 'package_id' => 'string', 'version' => 'string',
1218
					'id_member_installed' => 'int', 'member_installed' => 'string', 'time_installed' => 'int',
1219
					'install_state' => 'int', 'failed_steps' => 'string', 'themes_installed' => 'string',
1220
					'member_removed' => 'int', 'db_changes' => 'string', 'credits' => 'string',
1221
					'sha256_hash' => 'string',
1222
				),
1223
				array(
1224
					$package_filename, $package_name, $package_id, $package_version,
1225
					$user_info['id'], $user_info['name'], time(),
1226
					$is_upgrade ? 2 : 1, $failed_step_insert, $themes_installed,
1227
					0, $db_changes, $credits_tag, $context['package_sha256_hash']
1228
				),
1229
				array('id_install')
1230
			);
1231
		}
1232
		$smcFunc['db_free_result']($request);
1233
1234
		$context['install_finished'] = true;
1235
	}
1236
1237
	// If there's database changes - and they want them removed - let's do it last!
1238
	if (!empty($db_changes) && !empty($_POST['do_db_changes']))
1239
	{
1240
		// We're gonna be needing the package db functions!
1241
		db_extend('packages');
1242
1243
		foreach ($db_changes as $change)
1244
		{
1245
			if ($change[0] == 'remove_table' && isset($change[1]))
1246
				$smcFunc['db_drop_table']($change[1]);
1247
			elseif ($change[0] == 'remove_column' && isset($change[2]))
1248
				$smcFunc['db_remove_column']($change[1], $change[2]);
1249
			elseif ($change[0] == 'remove_index' && isset($change[2]))
1250
				$smcFunc['db_remove_index']($change[1], $change[2]);
1251
		}
1252
	}
1253
1254
	// Clean house... get rid of the evidence ;).
1255
	if (file_exists($packagesdir . '/temp'))
1256
		deltree($packagesdir . '/temp');
1257
1258
	// Log what we just did.
1259
	logAction($context['uninstalling'] ? 'uninstall_package' : (!empty($is_upgrade) ? 'upgrade_package' : 'install_package'), array('package' => $smcFunc['htmlspecialchars']($packageInfo['name']), 'version' => $smcFunc['htmlspecialchars']($packageInfo['version'])), 'admin');
1260
1261
	// Just in case, let's clear the whole cache and any minimized CSS and JS to avoid anything going up the swanny.
1262
	clean_cache();
1263
	deleteAllMinified();
1264
1265
	foreach (array('css_files', 'javascript_files') as $file_type)
1266
	{
1267
		foreach ($context[$file_type] as $id => $file)
1268
		{
1269
			if (isset($file['filePath']) && !file_exists($file['filePath']))
1270
				unset($context[$file_type][$id]);
1271
		}
1272
	}
1273
1274
	// Restore file permissions?
1275
	create_chmod_control(array(), array(), true);
1276
1277
	// Resume background tasks.
1278
	updateSettingsFile(['package_installing' => null]);
1279
}
1280
1281
/**
1282
 * List the files in a package.
1283
 */
1284
function PackageList()
1285
{
1286
	global $txt, $scripturl, $context, $sourcedir, $packagesdir;
1287
1288
	require_once($sourcedir . '/Subs-Package.php');
1289
1290
	// No package?  Show him or her the door.
1291
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
1292
		redirectexit('action=admin;area=packages');
1293
1294
	$context['linktree'][] = array(
1295
		'url' => $scripturl . '?action=admin;area=packages;sa=list;package=' . $_REQUEST['package'],
1296
		'name' => $txt['list_file']
1297
	);
1298
	$context['page_title'] .= ' - ' . $txt['list_file'];
1299
	$context['sub_template'] = 'list';
1300
1301
	// The filename...
1302
	$context['filename'] = $_REQUEST['package'];
1303
1304
	// Let the unpacker do the work.
1305
	if (is_file($packagesdir . '/' . $context['filename']))
1306
		$context['files'] = read_tgz_file($packagesdir . '/' . $context['filename'], null);
1307
	elseif (is_dir($packagesdir . '/' . $context['filename']))
1308
		$context['files'] = listtree($packagesdir . '/' . $context['filename']);
1309
}
1310
1311
/**
1312
 * Display one of the files in a package.
1313
 */
1314
function ExamineFile()
1315
{
1316
	global $txt, $scripturl, $context, $sourcedir, $packagesdir, $smcFunc;
1317
1318
	require_once($sourcedir . '/Subs-Package.php');
1319
1320
	// No package?  Show him or her the door.
1321
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
1322
		redirectexit('action=admin;area=packages');
1323
1324
	// No file?  Show him or her the door.
1325
	if (!isset($_REQUEST['file']) || $_REQUEST['file'] == '')
1326
		redirectexit('action=admin;area=packages');
1327
1328
	$_REQUEST['package'] = preg_replace('~[\.]+~', '.', strtr($_REQUEST['package'], array('/' => '_', '\\' => '_')));
1329
	$_REQUEST['file'] = preg_replace('~[\.]+~', '.', $_REQUEST['file']);
1330
1331
	if (isset($_REQUEST['raw']))
1332
	{
1333
		if (is_file($packagesdir . '/' . $_REQUEST['package']))
1334
			echo read_tgz_file($packagesdir . '/' . $_REQUEST['package'], $_REQUEST['file'], true);
1335
		elseif (is_dir($packagesdir . '/' . $_REQUEST['package']))
1336
			echo file_get_contents($packagesdir . '/' . $_REQUEST['package'] . '/' . $_REQUEST['file']);
1337
1338
		obExit(false);
1339
	}
1340
1341
	$context['linktree'][count($context['linktree']) - 1] = array(
1342
		'url' => $scripturl . '?action=admin;area=packages;sa=list;package=' . $_REQUEST['package'],
1343
		'name' => $txt['package_examine_file']
1344
	);
1345
	$context['page_title'] .= ' - ' . $txt['package_examine_file'];
1346
	$context['sub_template'] = 'examine';
1347
1348
	// The filename...
1349
	$context['package'] = $_REQUEST['package'];
1350
	$context['filename'] = $_REQUEST['file'];
1351
1352
	// Let the unpacker do the work.... but make sure we handle images properly.
1353
	if (in_array(strtolower(strrchr($_REQUEST['file'], '.')), array('.bmp', '.gif', '.jpeg', '.jpg', '.png', '.webp')))
1354
		$context['filedata'] = '<img src="' . $scripturl . '?action=admin;area=packages;sa=examine;package=' . $_REQUEST['package'] . ';file=' . $_REQUEST['file'] . ';raw" alt="' . $_REQUEST['file'] . '">';
1355
	else
1356
	{
1357
		if (is_file($packagesdir . '/' . $_REQUEST['package']))
1358
			$context['filedata'] = $smcFunc['htmlspecialchars'](read_tgz_file($packagesdir . '/' . $_REQUEST['package'], $_REQUEST['file'], true));
1359
		elseif (is_dir($packagesdir . '/' . $_REQUEST['package']))
1360
			$context['filedata'] = $smcFunc['htmlspecialchars'](file_get_contents($packagesdir . '/' . $_REQUEST['package'] . '/' . $_REQUEST['file']));
1361
1362
		if (strtolower(strrchr($_REQUEST['file'], '.')) == '.php')
1363
			$context['filedata'] = highlight_php_code($context['filedata']);
1364
	}
1365
}
1366
1367
/**
1368
 * Delete a package.
1369
 */
1370
function PackageRemove()
1371
{
1372
	global $scripturl, $packagesdir;
1373
1374
	// Check it.
1375
	checkSession('get');
1376
1377
	// Ack, don't allow deletion of arbitrary files here, could become a security hole somehow!
1378
	if (!isset($_GET['package']) || $_GET['package'] == 'index.php' || $_GET['package'] == 'backups')
1379
		redirectexit('action=admin;area=packages;sa=browse');
1380
	$_GET['package'] = preg_replace('~[\.]+~', '.', strtr($_GET['package'], array('/' => '_', '\\' => '_')));
1381
1382
	// Can't delete what's not there.
1383
	if (file_exists($packagesdir . '/' . $_GET['package']) && (substr($_GET['package'], -4) == '.zip' || substr($_GET['package'], -4) == '.tgz' || substr($_GET['package'], -7) == '.tar.gz' || is_dir($packagesdir . '/' . $_GET['package'])) && $_GET['package'] != 'backups' && substr($_GET['package'], 0, 1) != '.')
1384
	{
1385
		create_chmod_control(array($packagesdir . '/' . $_GET['package']), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=remove;package=' . $_GET['package'], 'crash_on_error' => true));
1386
1387
		if (is_dir($packagesdir . '/' . $_GET['package']))
1388
			deltree($packagesdir . '/' . $_GET['package']);
1389
		else
1390
		{
1391
			smf_chmod($packagesdir . '/' . $_GET['package'], 0777);
1392
			unlink($packagesdir . '/' . $_GET['package']);
1393
		}
1394
	}
1395
1396
	redirectexit('action=admin;area=packages;sa=browse');
1397
}
1398
1399
/**
1400
 * Browse a list of installed packages.
1401
 */
1402
function PackageBrowse()
1403
{
1404
	global $txt, $scripturl, $context, $sourcedir, $smcFunc;
1405
1406
	$context['page_title'] .= ' - ' . $txt['browse_packages'];
1407
1408
	$context['forum_version'] = SMF_FULL_VERSION;
1409
	$context['available_packages'] = 0;
1410
	$context['modification_types'] = array('modification', 'avatar', 'language', 'unknown', 'smiley');
1411
1412
	call_integration_hook('integrate_modification_types');
1413
1414
	require_once($sourcedir . '/Subs-List.php');
1415
1416
	foreach ($context['modification_types'] as $type)
1417
	{
1418
		// Use the standard templates for showing this.
1419
		$listOptions = array(
1420
			'id' => 'packages_lists_' . $type,
1421
			'title' => $txt[$type . '_package'],
1422
			'no_items_label' => $txt['no_packages'],
1423
			'get_items' => array(
1424
				'function' => 'list_getPackages',
1425
				'params' => array($type),
1426
			),
1427
			'base_href' => $scripturl . '?action=admin;area=packages;sa=browse;type=' . $type,
1428
			'default_sort_col' => 'id' . $type,
1429
			'columns' => array(
1430
				'id' . $type => array(
1431
					'header' => array(
1432
						'value' => $txt['package_id'],
1433
						'style' => 'width: 52px;',
1434
					),
1435
					'data' => array(
1436
						'db' => 'sort_id',
1437
					),
1438
					'sort' => array(
1439
						'default' => 'sort_id',
1440
						'reverse' => 'sort_id'
1441
					),
1442
				),
1443
				'mod_name' . $type => array(
1444
					'header' => array(
1445
						'value' => $txt['mod_name'],
1446
						'style' => 'width: 25%;',
1447
					),
1448
					'data' => array(
1449
						'db' => 'name',
1450
					),
1451
					'sort' => array(
1452
						'default' => 'name',
1453
						'reverse' => 'name',
1454
					),
1455
				),
1456
				'version' . $type => array(
1457
					'header' => array(
1458
						'value' => $txt['mod_version'],
1459
					),
1460
					'data' => array(
1461
						'db' => 'version',
1462
					),
1463
					'sort' => array(
1464
						'default' => 'version',
1465
						'reverse' => 'version',
1466
					),
1467
				),
1468
				'time_installed' . $type => array(
1469
					'header' => array(
1470
						'value' => $txt['mod_installed_time'],
1471
					),
1472
					'data' => array(
1473
						'function' => function($package) use ($txt)
1474
						{
1475
							return !empty($package['time_installed'])
1476
								? timeformat($package['time_installed'])
1477
								: $txt['not_applicable'];
1478
						},
1479
						'class' => 'smalltext',
1480
					),
1481
					'sort' => array(
1482
						'default' => 'time_installed',
1483
						'reverse' => 'time_installed',
1484
					),
1485
				),
1486
				'operations' . $type => array(
1487
					'header' => array(
1488
						'value' => '',
1489
					),
1490
					'data' => array(
1491
						'function' => function($package) use ($context, $scripturl, $txt, $type)
1492
						{
1493
							$return = '';
1494
1495
							if ($package['can_uninstall'])
1496
								$return = '
1497
									<a href="' . $scripturl . '?action=admin;area=packages;sa=uninstall;package=' . $package['filename'] . ';pid=' . $package['installed_id'] . '" class="button floatnone">' . (isset($txt['uninstall_' . $type]) ? $txt['uninstall_' . $type] : $txt['uninstall']) . '</a>';
1498
							elseif ($package['can_emulate_uninstall'])
1499
								$return = '
1500
									<a href="' . $scripturl . '?action=admin;area=packages;sa=uninstall;ve=' . $package['can_emulate_uninstall'] . ';package=' . $package['filename'] . ';pid=' . $package['installed_id'] . '" class="button floatnone">' . $txt['package_emulate_uninstall'] . ' ' . $package['can_emulate_uninstall'] . '</a>';
1501
							elseif ($package['can_upgrade'])
1502
								$return = '
1503
									<a href="' . $scripturl . '?action=admin;area=packages;sa=install;package=' . $package['filename'] . '" class="button floatnone">' . $txt['package_upgrade'] . '</a>';
1504
							elseif ($package['can_install'])
1505
								$return = '
1506
									<a href="' . $scripturl . '?action=admin;area=packages;sa=install;package=' . $package['filename'] . '" class="button floatnone">' . $txt['install_' . $type] . '</a>';
1507
							elseif ($package['can_emulate_install'])
1508
								$return = '
1509
									<a href="' . $scripturl . '?action=admin;area=packages;sa=install;ve=' . $package['can_emulate_install'] . ';package=' . $package['filename'] . '" class="button floatnone">' . $txt['package_emulate_install'] . ' ' . $package['can_emulate_install'] . '</a>';
1510
1511
							return $return . '
1512
									<a href="' . $scripturl . '?action=admin;area=packages;sa=list;package=' . $package['filename'] . '" class="button floatnone">' . $txt['list_files'] . '</a>
1513
									<a href="' . $scripturl . '?action=admin;area=packages;sa=remove;package=' . $package['filename'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '"' . ($package['is_installed'] && $package['is_current'] ? ' data-confirm="' . $txt['package_delete_bad'] . '"' : '') . ' class="button' . ($package['is_installed'] && $package['is_current'] ? ' you_sure' : '') . ' floatnone">' . $txt['package_delete'] . '</a>';
1514
						},
1515
						'class' => 'righttext',
1516
					),
1517
				),
1518
			),
1519
		);
1520
1521
		createList($listOptions);
1522
	}
1523
1524
	$context['sub_template'] = 'browse';
1525
	$context['default_list'] = 'packages_lists';
1526
1527
	$get_versions = $smcFunc['db_query']('', '
1528
		SELECT data FROM {db_prefix}admin_info_files WHERE filename={string:versionsfile} AND path={string:smf}',
1529
		array(
1530
			'versionsfile' => 'latest-versions.txt',
1531
			'smf' => '/smf/',
1532
		)
1533
	);
1534
1535
	$data = $smcFunc['db_fetch_assoc']($get_versions);
1536
	$smcFunc['db_free_result']($get_versions);
1537
1538
	// Decode the data.
1539
	$items = $smcFunc['json_decode']($data['data'], true);
1540
1541
	$context['emulation_versions'] = preg_replace('~^SMF ~', '', $items);
1542
1543
	// Current SMF version, which is selected by default
1544
	$context['default_version'] = SMF_VERSION;
1545
1546
	if (!in_array($context['default_version'], $context['emulation_versions']))
1547
	{
1548
		$context['emulation_versions'][] = $context['default_version'];
1549
	}
1550
1551
	// Version we're currently emulating, if any
1552
	$context['selected_version'] = preg_replace('~^SMF ~', '', $context['forum_version']);
1553
}
1554
1555
/**
1556
 * Get a listing of all the packages
1557
 *
1558
 * Determines if the package is a mod, avatar, or language package and
1559
 * groups it accordingly. If a package is not recognised as one of the
1560
 * above, it is then put into a special group, "unknown".
1561
 *
1562
 * Determines whether the package has been installed or not by
1563
 * checking it against {@link loadInstalledPackages()}.
1564
 *
1565
 * @param int $start The item to start with (not used here)
1566
 * @param int $items_per_page The number of items to show per page (not used here)
1567
 * @param string $sort A string indicating how to sort the results
1568
 * @param string $params Type of packages
1569
 * @return array An array of information about the packages
1570
 */
1571
function list_getPackages($start, $items_per_page, $sort, $params)
1572
{
1573
	global $scripturl, $packagesdir, $context;
1574
	static $installed_mods;
1575
1576
	$packages = array();
1577
	$column = array();
1578
1579
	// We need the packages directory to be writable for this.
1580
	if (!@is_writable($packagesdir))
1581
		create_chmod_control(array($packagesdir), array('destination_url' => $scripturl . '?action=admin;area=packages', 'crash_on_error' => true));
1582
1583
	$the_version = SMF_VERSION;
1584
1585
	// Here we have a little code to help those who class themselves as something of gods, version emulation ;)
1586
	if (isset($_GET['version_emulate']) && strtr($_GET['version_emulate'], array('SMF ' => '')) == $the_version)
1587
	{
1588
		unset($_SESSION['version_emulate']);
1589
	}
1590
	elseif (isset($_GET['version_emulate']))
1591
	{
1592
		if (($_GET['version_emulate'] === 0 || $_GET['version_emulate'] === SMF_FULL_VERSION) && isset($_SESSION['version_emulate']))
1593
			unset($_SESSION['version_emulate']);
1594
		elseif ($_GET['version_emulate'] !== 0)
1595
			$_SESSION['version_emulate'] = strtr($_GET['version_emulate'], array('-' => ' ', '+' => ' ', 'SMF ' => ''));
1596
	}
1597
	if (!empty($_SESSION['version_emulate']))
1598
	{
1599
		$context['forum_version'] = 'SMF ' . $_SESSION['version_emulate'];
1600
		$the_version = $_SESSION['version_emulate'];
1601
	}
1602
	if (isset($_SESSION['single_version_emulate']))
1603
		unset($_SESSION['single_version_emulate']);
1604
1605
	if (empty($installed_mods))
1606
	{
1607
		$instmods = loadInstalledPackages();
1608
		$installed_mods = array();
1609
		// Look through the list of installed mods...
1610
		foreach ($instmods as $installed_mod)
1611
			$installed_mods[$installed_mod['package_id']] = array(
1612
				'id' => $installed_mod['id'],
1613
				'version' => $installed_mod['version'],
1614
				'time_installed' => $installed_mod['time_installed'],
1615
			);
1616
1617
		// Get a list of all the ids installed, so the latest packages won't include already installed ones.
1618
		$context['installed_mods'] = array_keys($installed_mods);
1619
	}
1620
1621
	if ($dir = @opendir($packagesdir))
1622
	{
1623
		$dirs = array();
1624
		$sort_id = array(
1625
			'modification' => 1,
1626
			'avatar' => 1,
1627
			'language' => 1,
1628
			'unknown' => 1,
1629
			'smiley' => 1,
1630
		);
1631
		call_integration_hook('integrate_packages_sort_id', array(&$sort_id, &$packages));
1632
1633
		while ($package = readdir($dir))
1634
		{
1635
			if ($package == '.' || $package == '..' || $package == 'temp' || (!(is_dir($packagesdir . '/' . $package) && file_exists($packagesdir . '/' . $package . '/package-info.xml')) && substr(strtolower($package), -7) != '.tar.gz' && substr(strtolower($package), -4) != '.tgz' && substr(strtolower($package), -4) != '.zip'))
1636
				continue;
1637
1638
			// Skip directories or files that are named the same.
1639
			if (is_dir($packagesdir . '/' . $package))
1640
			{
1641
				if (in_array($package, $dirs))
1642
					continue;
1643
				$dirs[] = $package;
1644
			}
1645
			elseif (substr(strtolower($package), -7) == '.tar.gz')
1646
			{
1647
				if (in_array(substr($package, 0, -7), $dirs))
1648
					continue;
1649
				$dirs[] = substr($package, 0, -7);
1650
			}
1651
			elseif (substr(strtolower($package), -4) == '.zip' || substr(strtolower($package), -4) == '.tgz')
1652
			{
1653
				if (in_array(substr($package, 0, -4), $dirs))
1654
					continue;
1655
				$dirs[] = substr($package, 0, -4);
1656
			}
1657
1658
			$packageInfo = getPackageInfo($package);
1659
			if (!is_array($packageInfo))
1660
				continue;
1661
1662
			if (!empty($packageInfo))
1663
			{
1664
				if (!isset($sort_id[$packageInfo['type']]))
1665
					$packageInfo['sort_id'] = $sort_id['unknown'];
1666
				else
1667
					$packageInfo['sort_id'] = $sort_id[$packageInfo['type']];
1668
1669
				$packageInfo['time_installed'] = 0;
1670
				$packageInfo['is_installed'] = isset($installed_mods[$packageInfo['id']]);
1671
				if ($packageInfo['is_installed'])
1672
				{
1673
					$packageInfo['is_current'] = $installed_mods[$packageInfo['id']]['version'] == $packageInfo['version'];
1674
					$packageInfo['is_newer'] = $installed_mods[$packageInfo['id']]['version'] > $packageInfo['version'];
1675
					$packageInfo['installed_id'] = $installed_mods[$packageInfo['id']]['id'];
1676
					if ($packageInfo['is_current'])
1677
						$packageInfo['time_installed'] = $installed_mods[$packageInfo['id']]['time_installed'];
1678
				}
1679
1680
				$packageInfo['can_install'] = false;
1681
				$packageInfo['can_uninstall'] = false;
1682
				$packageInfo['can_upgrade'] = false;
1683
				$packageInfo['can_emulate_install'] = false;
1684
				$packageInfo['can_emulate_uninstall'] = false;
1685
1686
				// This package is currently NOT installed.  Check if it can be.
1687
				if (!$packageInfo['is_installed'] && $packageInfo['xml']->exists('install'))
1688
				{
1689
					// Check if there's an install for *THIS* version of SMF.
1690
					$installs = $packageInfo['xml']->set('install');
1691
					foreach ($installs as $install)
1692
					{
1693
						if (!$install->exists('@for') || matchPackageVersion($the_version, $install->fetch('@for')))
1694
						{
1695
							// Okay, this one is good to go.
1696
							$packageInfo['can_install'] = true;
1697
							break;
1698
						}
1699
					}
1700
1701
					// no install found for this version, lets see if one exists for another
1702
					if ($packageInfo['can_install'] === false && $install->exists('@for') && empty($_SESSION['version_emulate']))
1703
					{
1704
						$reset = true;
1705
1706
						// Get the highest install version that is available from the package
1707
						foreach ($installs as $install)
1708
						{
1709
							$packageInfo['can_emulate_install'] = matchHighestPackageVersion($install->fetch('@for'), $reset, $the_version);
1710
							$reset = false;
1711
						}
1712
					}
1713
				}
1714
				// An already installed, but old, package.  Can we upgrade it?
1715
				elseif ($packageInfo['is_installed'] && !$packageInfo['is_current'] && $packageInfo['xml']->exists('upgrade'))
1716
				{
1717
					$upgrades = $packageInfo['xml']->set('upgrade');
1718
1719
					// First go through, and check against the current version of SMF.
1720
					foreach ($upgrades as $upgrade)
1721
					{
1722
						// Even if it is for this SMF, is it for the installed version of the mod?
1723
						if (!$upgrade->exists('@for') || matchPackageVersion($the_version, $upgrade->fetch('@for')))
1724
							if (!$upgrade->exists('@from') || matchPackageVersion($installed_mods[$packageInfo['id']]['version'], $upgrade->fetch('@from')))
1725
							{
1726
								$packageInfo['can_upgrade'] = true;
1727
								break;
1728
							}
1729
					}
1730
				}
1731
				// Note that it has to be the current version to be uninstallable.  Shucks.
1732
				elseif ($packageInfo['is_installed'] && $packageInfo['is_current'] && $packageInfo['xml']->exists('uninstall'))
1733
				{
1734
					$uninstalls = $packageInfo['xml']->set('uninstall');
1735
1736
					// Can we find any uninstallation methods that work for this SMF version?
1737
					foreach ($uninstalls as $uninstall)
1738
					{
1739
						if (!$uninstall->exists('@for') || matchPackageVersion($the_version, $uninstall->fetch('@for')))
1740
						{
1741
							$packageInfo['can_uninstall'] = true;
1742
							break;
1743
						}
1744
					}
1745
1746
					// no uninstall found for this version, lets see if one exists for another
1747
					if ($packageInfo['can_uninstall'] === false && $uninstall->exists('@for') && empty($_SESSION['version_emulate']))
1748
					{
1749
						$reset = true;
1750
1751
						// Get the highest install version that is available from the package
1752
						foreach ($uninstalls as $uninstall)
1753
						{
1754
							$packageInfo['can_emulate_uninstall'] = matchHighestPackageVersion($uninstall->fetch('@for'), $reset, $the_version);
1755
							$reset = false;
1756
						}
1757
					}
1758
				}
1759
1760
				// Save some memory by not passing the xmlArray object into context.
1761
				unset($packageInfo['xml']);
1762
1763
				if (isset($sort_id[$packageInfo['type']]) && $params == $packageInfo['type'])
1764
				{
1765
					$column[] = $packageInfo[$sort];
1766
					$sort_id[$packageInfo['type']]++;
1767
					$packages[] = $packageInfo;
1768
				}
1769
				elseif (!isset($sort_id[$packageInfo['type']]) && $params == 'unknown')
1770
				{
1771
					$column[] = $packageInfo[$sort];
1772
					$packageInfo['sort_id'] = $sort_id['unknown'];
1773
					$sort_id['unknown']++;
1774
					$packages[] = $packageInfo;
1775
				}
1776
			}
1777
		}
1778
		closedir($dir);
1779
	}
1780
	$context['available_packages'] += count($packages);
1781
	array_multisort(
1782
		$column,
1783
		isset($_GET['desc']) ? SORT_DESC : SORT_ASC,
1784
		$packages
1785
	);
1786
1787
	return $packages;
1788
}
1789
1790
/**
1791
 * Used when a temp FTP access is needed to package functions
1792
 */
1793
function PackageOptions()
1794
{
1795
	global $txt, $context, $modSettings, $smcFunc;
1796
1797
	if (isset($_POST['save']))
1798
	{
1799
		checkSession();
1800
1801
		updateSettings(array(
1802
			'package_server' => trim($smcFunc['htmlspecialchars']($_POST['pack_server'])),
1803
			'package_port' => trim($smcFunc['htmlspecialchars']($_POST['pack_port'])),
1804
			'package_username' => trim($smcFunc['htmlspecialchars']($_POST['pack_user'])),
1805
			'package_make_backups' => !empty($_POST['package_make_backups']),
1806
			'package_make_full_backups' => !empty($_POST['package_make_full_backups'])
1807
		));
1808
		$_SESSION['adm-save'] = true;
1809
1810
		redirectexit('action=admin;area=packages;sa=options');
1811
	}
1812
1813
	if (preg_match('~^/home\d*/([^/]+?)/public_html~', $_SERVER['DOCUMENT_ROOT'], $match))
1814
		$default_username = $match[1];
1815
	else
1816
		$default_username = '';
1817
1818
	$context['page_title'] = $txt['package_settings'];
1819
	$context['sub_template'] = 'install_options';
1820
1821
	$context['package_ftp_server'] = isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost';
1822
	$context['package_ftp_port'] = isset($modSettings['package_port']) ? $modSettings['package_port'] : '21';
1823
	$context['package_ftp_username'] = isset($modSettings['package_username']) ? $modSettings['package_username'] : $default_username;
1824
	$context['package_make_backups'] = !empty($modSettings['package_make_backups']);
1825
	$context['package_make_full_backups'] = !empty($modSettings['package_make_full_backups']);
1826
1827
	if (!empty($_SESSION['adm-save']))
1828
	{
1829
		$context['saved_successful'] = true;
1830
		unset ($_SESSION['adm-save']);
1831
	}
1832
}
1833
1834
/**
1835
 * List operations
1836
 */
1837
function ViewOperations()
1838
{
1839
	global $context, $txt, $sourcedir, $packagesdir, $smcFunc, $modSettings, $settings;
1840
1841
	// Can't be in here buddy.
1842
	isAllowedTo('admin_forum');
1843
1844
	// We need to know the operation key for the search and replace, mod file looking at, is it a board mod?
1845
	if (!isset($_REQUEST['operation_key'], $_REQUEST['filename']) && !is_numeric($_REQUEST['operation_key']))
1846
		fatal_lang_error('operation_invalid', 'general');
1847
1848
	// Load the required file.
1849
	require_once($sourcedir . '/Subs-Package.php');
1850
1851
	// Uninstalling the mod?
1852
	$reverse = isset($_REQUEST['reverse']) ? true : false;
1853
1854
	// Get the base name.
1855
	$context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);
1856
1857
	// We need to extract this again.
1858
	if (is_file($packagesdir . '/' . $context['filename']))
1859
	{
1860
		$context['extracted_files'] = read_tgz_file($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
1861
1862
		if ($context['extracted_files'] && !file_exists($packagesdir . '/temp/package-info.xml'))
1863
			foreach ($context['extracted_files'] as $file)
1864
				if (basename($file['filename']) == 'package-info.xml')
1865
				{
1866
					$context['base_path'] = dirname($file['filename']) . '/';
1867
					break;
1868
				}
1869
1870
		if (!isset($context['base_path']))
1871
			$context['base_path'] = '';
1872
	}
1873
	elseif (is_dir($packagesdir . '/' . $context['filename']))
1874
	{
1875
		copytree($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
1876
		$context['extracted_files'] = listtree($packagesdir . '/temp');
1877
		$context['base_path'] = '';
1878
	}
1879
1880
	// Load up any custom themes we may want to install into...
1881
	$request = $smcFunc['db_query']('', '
1882
		SELECT id_theme, variable, value
1883
		FROM {db_prefix}themes
1884
		WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
1885
			AND variable IN ({string:name}, {string:theme_dir})',
1886
		array(
1887
			'known_theme_list' => explode(',', $modSettings['knownThemes']),
1888
			'default_theme' => 1,
1889
			'name' => 'name',
1890
			'theme_dir' => 'theme_dir',
1891
		)
1892
	);
1893
	$theme_paths = array();
1894
	while ($row = $smcFunc['db_fetch_assoc']($request))
1895
		$theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
1896
	$smcFunc['db_free_result']($request);
1897
1898
	// If we're viewing uninstall operations, only consider themes that
1899
	// the package is actually installed into.
1900
	if (isset($_REQUEST['reverse']) && !empty($_REQUEST['install_id']))
1901
	{
1902
		$install_id = (int) $_REQUEST['install_id'];
1903
		if ($install_id > 0)
1904
		{
1905
			$old_themes = array();
1906
			$request = $smcFunc['db_query']('', '
1907
				SELECT themes_installed
1908
				FROM {db_prefix}log_packages
1909
				WHERE id_install = {int:install_id}',
1910
				array(
1911
					'install_id' => $install_id,
1912
				)
1913
			);
1914
1915
			if ($smcFunc['db_num_rows']($request) == 1)
1916
			{
1917
				list ($old_themes) = $smcFunc['db_fetch_row']($request);
1918
				$old_themes = explode(',', $old_themes);
1919
1920
				foreach ($theme_paths as $id => $data)
1921
					if ($id != 1 && !in_array($id, $old_themes))
1922
						unset($theme_paths[$id]);
1923
			}
1924
			$smcFunc['db_free_result']($request);
1925
		}
1926
	}
1927
1928
	// Boardmod?
1929
	if (isset($_REQUEST['boardmod']))
1930
		$mod_actions = parseBoardMod(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $_REQUEST['filename']), true, $reverse, $theme_paths);
1931
	else
1932
		$mod_actions = parseModification(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $_REQUEST['filename']), true, $reverse, $theme_paths);
1933
1934
	// Ok lets get the content of the file.
1935
	$context['operations'] = array(
1936
		'search' => strtr($smcFunc['htmlspecialchars']($mod_actions[$_REQUEST['operation_key']]['search_original']), array('[' => '&#91;', ']' => '&#93;')),
1937
		'replace' => strtr($smcFunc['htmlspecialchars']($mod_actions[$_REQUEST['operation_key']]['replace_original']), array('[' => '&#91;', ']' => '&#93;')),
1938
		'position' => $mod_actions[$_REQUEST['operation_key']]['position'],
1939
	);
1940
1941
	// Let's do some formatting...
1942
	$operation_text = $context['operations']['position'] == 'replace' ? 'operation_replace' : ($context['operations']['position'] == 'before' ? 'operation_after' : 'operation_before');
1943
	$context['operations']['search'] = parse_bbc('[code=' . $txt['operation_find'] . ']' . ($context['operations']['position'] == 'end' ? '?&gt;' : $context['operations']['search']) . '[/code]');
1944
	$context['operations']['replace'] = parse_bbc('[code=' . $txt[$operation_text] . ']' . $context['operations']['replace'] . '[/code]');
1945
1946
	// No layers
1947
	$context['template_layers'] = array();
1948
	$context['sub_template'] = 'view_operations';
1949
1950
	// We only want to load these three JavaScript files.
1951
	$context['javascript_files'] = array_intersect_key(
1952
		$context['javascript_files'],
1953
		[
1954
			'smf_script_js' => true,
1955
			'smf_jquery_js' => true
1956
		]
1957
	);
1958
1959
	// Since the alerts code is loaded very late in the process, it must be disabled seperately.
1960
	$settings['disable_files'] = ['smf_alerts'];
1961
}
1962
1963
/**
1964
 * Allow the admin to reset permissions on files.
1965
 */
1966
function PackagePermissions()
1967
{
1968
	global $context, $txt, $modSettings, $boarddir, $sourcedir, $cachedir, $smcFunc, $package_ftp;
1969
1970
	// Let's try and be good, yes?
1971
	checkSession('get');
1972
1973
	// If we're restoring permissions this is just a pass through really.
1974
	if (isset($_GET['restore']))
1975
	{
1976
		create_chmod_control(array(), array(), true);
1977
		fatal_lang_error('no_access', false);
1978
	}
1979
1980
	// This is a memory eat.
1981
	setMemoryLimit('128M');
1982
	@set_time_limit(600);
1983
1984
	// Load up some FTP stuff.
1985
	create_chmod_control();
1986
1987
	if (empty($package_ftp) && !isset($_POST['skip_ftp']))
1988
	{
1989
		require_once($sourcedir . '/Class-Package.php');
1990
		$ftp = new ftp_connection(null);
1991
		list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
1992
1993
		$context['package_ftp'] = array(
1994
			'server' => isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost',
1995
			'port' => isset($modSettings['package_port']) ? $modSettings['package_port'] : '21',
1996
			'username' => empty($username) ? (isset($modSettings['package_username']) ? $modSettings['package_username'] : '') : $username,
1997
			'path' => $detect_path,
1998
			'form_elements_only' => true,
1999
		);
2000
	}
2001
	else
2002
		$context['ftp_connected'] = true;
2003
2004
	// Define the template.
2005
	$context['page_title'] = $txt['package_file_perms'];
2006
	$context['sub_template'] = 'file_permissions';
2007
2008
	// Define what files we're interested in, as a tree.
2009
	$context['file_tree'] = array(
2010
		strtr($boarddir, array('\\' => '/')) => array(
2011
			'type' => 'dir',
2012
			'contents' => array(
2013
				'agreement.txt' => array(
2014
					'type' => 'file',
2015
					'writable_on' => 'standard',
2016
				),
2017
				'Settings.php' => array(
2018
					'type' => 'file',
2019
					'writable_on' => 'restrictive',
2020
				),
2021
				'Settings_bak.php' => array(
2022
					'type' => 'file',
2023
					'writable_on' => 'restrictive',
2024
				),
2025
				'attachments' => array(
2026
					'type' => 'dir',
2027
					'writable_on' => 'restrictive',
2028
				),
2029
				'avatars' => array(
2030
					'type' => 'dir',
2031
					'writable_on' => 'standard',
2032
				),
2033
				'cache' => array(
2034
					'type' => 'dir',
2035
					'writable_on' => 'restrictive',
2036
				),
2037
				'custom_avatar_dir' => array(
2038
					'type' => 'dir',
2039
					'writable_on' => 'restrictive',
2040
				),
2041
				'Smileys' => array(
2042
					'type' => 'dir_recursive',
2043
					'writable_on' => 'standard',
2044
				),
2045
				'Sources' => array(
2046
					'type' => 'dir_recursive',
2047
					'list_contents' => true,
2048
					'writable_on' => 'standard',
2049
					'contents' => array(
2050
						'tasks' => array(
2051
							'type' => 'dir',
2052
							'list_contents' => true,
2053
						),
2054
					),
2055
				),
2056
				'Themes' => array(
2057
					'type' => 'dir_recursive',
2058
					'writable_on' => 'standard',
2059
					'contents' => array(
2060
						'default' => array(
2061
							'type' => 'dir_recursive',
2062
							'list_contents' => true,
2063
							'contents' => array(
2064
								'languages' => array(
2065
									'type' => 'dir',
2066
									'list_contents' => true,
2067
								),
2068
							),
2069
						),
2070
					),
2071
				),
2072
				'Packages' => array(
2073
					'type' => 'dir',
2074
					'writable_on' => 'standard',
2075
					'contents' => array(
2076
						'temp' => array(
2077
							'type' => 'dir',
2078
						),
2079
						'backup' => array(
2080
							'type' => 'dir',
2081
						),
2082
					),
2083
				),
2084
			),
2085
		),
2086
	);
2087
2088
	// Directories that can move.
2089
	if (substr($sourcedir, 0, strlen($boarddir)) != $boarddir)
2090
	{
2091
		unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['Sources']);
2092
		$context['file_tree'][strtr($sourcedir, array('\\' => '/'))] = array(
2093
			'type' => 'dir',
2094
			'list_contents' => true,
2095
			'writable_on' => 'standard',
2096
		);
2097
	}
2098
2099
	// Moved the cache?
2100
	if (substr($cachedir, 0, strlen($boarddir)) != $boarddir)
2101
	{
2102
		unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['cache']);
2103
		$context['file_tree'][strtr($cachedir, array('\\' => '/'))] = array(
2104
			'type' => 'dir',
2105
			'list_contents' => false,
2106
			'writable_on' => 'restrictive',
2107
		);
2108
	}
2109
2110
	// Are we using multiple attachment directories?
2111
	if (!empty($modSettings['currentAttachmentUploadDir']))
2112
	{
2113
		unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['attachments']);
2114
2115
		if (!is_array($modSettings['attachmentUploadDir']))
2116
			$modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
2117
2118
		// @todo Should we suggest non-current directories be read only?
2119
		foreach ($modSettings['attachmentUploadDir'] as $dir)
2120
			$context['file_tree'][strtr($dir, array('\\' => '/'))] = array(
2121
				'type' => 'dir',
2122
				'writable_on' => 'restrictive',
2123
			);
2124
	}
2125
	elseif (substr($modSettings['attachmentUploadDir'], 0, strlen($boarddir)) != $boarddir)
2126
	{
2127
		unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['attachments']);
2128
		$context['file_tree'][strtr($modSettings['attachmentUploadDir'], array('\\' => '/'))] = array(
2129
			'type' => 'dir',
2130
			'writable_on' => 'restrictive',
2131
		);
2132
	}
2133
2134
	if (substr($modSettings['smileys_dir'], 0, strlen($boarddir)) != $boarddir)
2135
	{
2136
		unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['Smileys']);
2137
		$context['file_tree'][strtr($modSettings['smileys_dir'], array('\\' => '/'))] = array(
2138
			'type' => 'dir_recursive',
2139
			'writable_on' => 'standard',
2140
		);
2141
	}
2142
	if (substr($modSettings['avatar_directory'], 0, strlen($boarddir)) != $boarddir)
2143
	{
2144
		unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['avatars']);
2145
		$context['file_tree'][strtr($modSettings['avatar_directory'], array('\\' => '/'))] = array(
2146
			'type' => 'dir',
2147
			'writable_on' => 'standard',
2148
		);
2149
	}
2150
	if (isset($modSettings['custom_avatar_dir']) && substr($modSettings['custom_avatar_dir'], 0, strlen($boarddir)) != $boarddir)
2151
	{
2152
		unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['custom_avatar_dir']);
2153
		$context['file_tree'][strtr($modSettings['custom_avatar_dir'], array('\\' => '/'))] = array(
2154
			'type' => 'dir',
2155
			'writable_on' => 'restrictive',
2156
		);
2157
	}
2158
2159
	// Load up any custom themes.
2160
	$request = $smcFunc['db_query']('', '
2161
		SELECT value
2162
		FROM {db_prefix}themes
2163
		WHERE id_theme > {int:default_theme_id}
2164
			AND id_member = {int:guest_id}
2165
			AND variable = {string:theme_dir}
2166
		ORDER BY value ASC',
2167
		array(
2168
			'default_theme_id' => 1,
2169
			'guest_id' => 0,
2170
			'theme_dir' => 'theme_dir',
2171
		)
2172
	);
2173
	while ($row = $smcFunc['db_fetch_assoc']($request))
2174
	{
2175
		if (substr(strtolower(strtr($row['value'], array('\\' => '/'))), 0, strlen($boarddir) + 7) == strtolower(strtr($boarddir, array('\\' => '/')) . '/Themes'))
2176
			$context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['Themes']['contents'][substr($row['value'], strlen($boarddir) + 8)] = array(
2177
				'type' => 'dir_recursive',
2178
				'list_contents' => true,
2179
				'contents' => array(
2180
					'languages' => array(
2181
						'type' => 'dir',
2182
						'list_contents' => true,
2183
					),
2184
				),
2185
			);
2186
		else
2187
		{
2188
			$context['file_tree'][strtr($row['value'], array('\\' => '/'))] = array(
2189
				'type' => 'dir_recursive',
2190
				'list_contents' => true,
2191
				'contents' => array(
2192
					'languages' => array(
2193
						'type' => 'dir',
2194
						'list_contents' => true,
2195
					),
2196
				),
2197
			);
2198
		}
2199
	}
2200
	$smcFunc['db_free_result']($request);
2201
2202
	// If we're submitting then let's move on to another function to keep things cleaner..
2203
	if (isset($_POST['action_changes']))
2204
		return PackagePermissionsAction();
2205
2206
	$context['look_for'] = array();
2207
	// Are we looking for a particular tree - normally an expansion?
2208
	if (!empty($_REQUEST['find']))
2209
		$context['look_for'][] = base64_decode($_REQUEST['find']);
2210
	// Only that tree?
2211
	$context['only_find'] = isset($_GET['xml']) && !empty($_REQUEST['onlyfind']) ? $_REQUEST['onlyfind'] : '';
2212
	if ($context['only_find'])
2213
		$context['look_for'][] = $context['only_find'];
2214
2215
	// Have we got a load of back-catalogue trees to expand from a submit etc?
2216
	if (!empty($_GET['back_look']))
2217
	{
2218
		$potententialTrees = $smcFunc['json_decode'](base64_decode($_GET['back_look']), true);
2219
		foreach ($potententialTrees as $tree)
2220
			$context['look_for'][] = $tree;
2221
	}
2222
	// ... maybe posted?
2223
	if (!empty($_POST['back_look']))
2224
		$context['only_find'] = array_merge($context['only_find'], $_POST['back_look']);
2225
2226
	$context['back_look_data'] = base64_encode($smcFunc['json_encode'](array_slice($context['look_for'], 0, 15)));
2227
2228
	// Are we finding more files than first thought?
2229
	$context['file_offset'] = !empty($_REQUEST['fileoffset']) ? (int) $_REQUEST['fileoffset'] : 0;
2230
	// Don't list more than this many files in a directory.
2231
	$context['file_limit'] = 150;
2232
2233
	// How many levels shall we show?
2234
	$context['default_level'] = empty($context['only_find']) ? 2 : 25;
2235
2236
	// This will be used if we end up catching XML data.
2237
	$context['xml_data'] = array(
2238
		'roots' => array(
2239
			'identifier' => 'root',
2240
			'children' => array(
2241
				array(
2242
					'value' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
2243
				),
2244
			),
2245
		),
2246
		'folders' => array(
2247
			'identifier' => 'folder',
2248
			'children' => array(),
2249
		),
2250
	);
2251
2252
	foreach ($context['file_tree'] as $path => $data)
2253
	{
2254
		// Run this directory.
2255
		if (file_exists($path) && (empty($context['only_find']) || substr($context['only_find'], 0, strlen($path)) == $path))
2256
		{
2257
			// Get the first level down only.
2258
			fetchPerms__recursive($path, $context['file_tree'][$path], 1);
2259
			$context['file_tree'][$path]['perms'] = array(
2260
				'chmod' => @is_writable($path),
2261
				'perms' => @fileperms($path),
2262
			);
2263
		}
2264
		else
2265
			unset($context['file_tree'][$path]);
2266
	}
2267
2268
	// Is this actually xml?
2269
	if (isset($_GET['xml']))
2270
	{
2271
		loadTemplate('Xml');
2272
		$context['sub_template'] = 'generic_xml';
2273
		$context['template_layers'] = array();
2274
	}
2275
}
2276
2277
/**
2278
 * Checkes the permissions of all the areas that will be affected by the package
2279
 *
2280
 * @param string $path The path to the directiory to check permissions for
2281
 * @param array $data An array of data about the directory
2282
 * @param int $level How far deep to go
2283
 */
2284
function fetchPerms__recursive($path, &$data, $level)
2285
{
2286
	global $context;
2287
2288
	$isLikelyPath = false;
2289
	foreach ($context['look_for'] as $possiblePath)
2290
		if (substr($possiblePath, 0, strlen($path)) == $path)
2291
			$isLikelyPath = true;
2292
2293
	// Is this where we stop?
2294
	if (isset($_GET['xml']) && !empty($context['look_for']) && !$isLikelyPath)
2295
		return;
2296
	elseif ($level > $context['default_level'] && !$isLikelyPath)
2297
		return;
2298
2299
	// Are we actually interested in saving this data?
2300
	$save_data = empty($context['only_find']) || $context['only_find'] == $path;
2301
2302
	// @todo Shouldn't happen - but better error message?
2303
	if (!is_dir($path))
2304
		fatal_lang_error('no_access', false);
2305
2306
	// This is where we put stuff we've found for sorting.
2307
	$foundData = array(
2308
		'files' => array(),
2309
		'folders' => array(),
2310
	);
2311
2312
	$dh = opendir($path);
2313
	while ($entry = readdir($dh))
2314
	{
2315
		// Bypass directory abbreviations altogether...
2316
		if ($entry == '.' || $entry == '..')
2317
			continue;
2318
2319
		// Some kind of file?
2320
		if (is_file($path . '/' . $entry))
2321
		{
2322
			// Are we listing PHP files in this directory?
2323
			if ($save_data && !empty($data['list_contents']) && substr($entry, -4) == '.php')
2324
				$foundData['files'][$entry] = true;
2325
			// A file we were looking for.
2326
			elseif ($save_data && isset($data['contents'][$entry]))
2327
				$foundData['files'][$entry] = true;
2328
		}
2329
		// It's a directory - we're interested one way or another, probably...
2330
		else
2331
		{
2332
			// Going further?
2333
			if ((!empty($data['type']) && $data['type'] == 'dir_recursive') || (isset($data['contents'][$entry]) && (!empty($data['contents'][$entry]['list_contents']) || (!empty($data['contents'][$entry]['type']) && $data['contents'][$entry]['type'] == 'dir_recursive'))))
2334
			{
2335
				if (!isset($data['contents'][$entry]))
2336
					$foundData['folders'][$entry] = 'dir_recursive';
2337
				else
2338
					$foundData['folders'][$entry] = true;
2339
2340
				// If this wasn't expected inherit the recusiveness...
2341
				if (!isset($data['contents'][$entry]))
2342
					// We need to do this as we will be going all recursive.
2343
					$data['contents'][$entry] = array(
2344
						'type' => 'dir_recursive',
2345
					);
2346
2347
				// Actually do the recursive stuff...
2348
				fetchPerms__recursive($path . '/' . $entry, $data['contents'][$entry], $level + 1);
2349
			}
2350
			// Maybe it is a folder we are not descending into.
2351
			elseif (isset($data['contents'][$entry]))
2352
				$foundData['folders'][$entry] = true;
2353
			// Otherwise we stop here.
2354
		}
2355
	}
2356
	closedir($dh);
2357
2358
	// Nothing to see here?
2359
	if (!$save_data)
2360
		return;
2361
2362
	// Now actually add the data, starting with the folders.
2363
	ksort($foundData['folders']);
2364
	foreach ($foundData['folders'] as $folder => $type)
2365
	{
2366
		$additional_data = array(
2367
			'perms' => array(
2368
				'chmod' => @is_writable($path . '/' . $folder),
2369
				'perms' => @fileperms($path . '/' . $folder),
2370
			),
2371
		);
2372
		if ($type !== true)
2373
			$additional_data['type'] = $type;
2374
2375
		// If there's an offset ignore any folders in XML mode.
2376
		if (isset($_GET['xml']) && $context['file_offset'] == 0)
2377
		{
2378
			$context['xml_data']['folders']['children'][] = array(
2379
				'attributes' => array(
2380
					'writable' => $additional_data['perms']['chmod'] ? 1 : 0,
2381
					'permissions' => substr(sprintf('%o', $additional_data['perms']['perms']), -4),
2382
					'folder' => 1,
2383
					'path' => $context['only_find'],
2384
					'level' => $level,
2385
					'more' => 0,
2386
					'offset' => $context['file_offset'],
2387
					'my_ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find'] . '/' . $folder),
2388
					'ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
2389
				),
2390
				'value' => $folder,
2391
			);
2392
		}
2393
		elseif (!isset($_GET['xml']))
2394
		{
2395
			if (isset($data['contents'][$folder]))
2396
				$data['contents'][$folder] = array_merge($data['contents'][$folder], $additional_data);
2397
			else
2398
				$data['contents'][$folder] = $additional_data;
2399
		}
2400
	}
2401
2402
	// Now we want to do a similar thing with files.
2403
	ksort($foundData['files']);
2404
	$counter = -1;
2405
	foreach ($foundData['files'] as $file => $dummy)
2406
	{
2407
		$counter++;
2408
2409
		// Have we reached our offset?
2410
		if ($context['file_offset'] > $counter)
2411
			continue;
2412
		// Gone too far?
2413
		if ($counter > ($context['file_offset'] + $context['file_limit']))
2414
			continue;
2415
2416
		$additional_data = array(
2417
			'perms' => array(
2418
				'chmod' => @is_writable($path . '/' . $file),
2419
				'perms' => @fileperms($path . '/' . $file),
2420
			),
2421
		);
2422
2423
		// XML?
2424
		if (isset($_GET['xml']))
2425
		{
2426
			$context['xml_data']['folders']['children'][] = array(
2427
				'attributes' => array(
2428
					'writable' => $additional_data['perms']['chmod'] ? 1 : 0,
2429
					'permissions' => substr(sprintf('%o', $additional_data['perms']['perms']), -4),
2430
					'folder' => 0,
2431
					'path' => $context['only_find'],
2432
					'level' => $level,
2433
					'more' => $counter == ($context['file_offset'] + $context['file_limit']) ? 1 : 0,
2434
					'offset' => $context['file_offset'],
2435
					'my_ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find'] . '/' . $file),
2436
					'ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
2437
				),
2438
				'value' => $file,
2439
			);
2440
		}
2441
		elseif ($counter != ($context['file_offset'] + $context['file_limit']))
2442
		{
2443
			if (isset($data['contents'][$file]))
2444
				$data['contents'][$file] = array_merge($data['contents'][$file], $additional_data);
2445
			else
2446
				$data['contents'][$file] = $additional_data;
2447
		}
2448
	}
2449
}
2450
2451
/**
2452
 * Actually action the permission changes they want.
2453
 */
2454
function PackagePermissionsAction()
2455
{
2456
	global $smcFunc, $context, $txt, $package_ftp;
2457
2458
	umask(0);
2459
2460
	$timeout_limit = 5;
2461
2462
	$context['method'] = $_POST['method'] == 'individual' ? 'individual' : 'predefined';
2463
	$context['sub_template'] = 'action_permissions';
2464
	$context['page_title'] = $txt['package_file_perms_applying'];
2465
	$context['back_look_data'] = isset($_POST['back_look']) ? $_POST['back_look'] : array();
2466
2467
	// Skipping use of FTP?
2468
	if (empty($package_ftp))
2469
		$context['skip_ftp'] = true;
2470
2471
	// We'll start off in a good place, security. Make sure that if we're dealing with individual files that they seem in the right place.
2472
	if ($context['method'] == 'individual')
2473
	{
2474
		// Only these path roots are legal.
2475
		$legal_roots = array_keys($context['file_tree']);
2476
		$context['custom_value'] = (int) $_POST['custom_value'];
2477
2478
		// Continuing?
2479
		if (isset($_POST['toProcess']))
2480
			$_POST['permStatus'] = $smcFunc['json_decode'](base64_decode($_POST['toProcess']), true);
2481
2482
		if (isset($_POST['permStatus']))
2483
		{
2484
			$context['to_process'] = array();
2485
			$validate_custom = false;
2486
			foreach ($_POST['permStatus'] as $path => $status)
2487
			{
2488
				// Nothing to see here?
2489
				if ($status == 'no_change')
2490
					continue;
2491
				$legal = false;
2492
				foreach ($legal_roots as $root)
2493
					if (substr($path, 0, strlen($root)) == $root)
2494
						$legal = true;
2495
2496
				if (!$legal)
2497
					continue;
2498
2499
				// Check it exists.
2500
				if (!file_exists($path))
2501
					continue;
2502
2503
				if ($status == 'custom')
2504
					$validate_custom = true;
2505
2506
				// Now add it.
2507
				$context['to_process'][$path] = $status;
2508
			}
2509
			$context['total_items'] = isset($_POST['totalItems']) ? (int) $_POST['totalItems'] : count($context['to_process']);
2510
2511
			// Make sure the chmod status is valid?
2512
			if ($validate_custom)
2513
			{
2514
				if (preg_match('~^[4567][4567][4567]$~', $context['custom_value']) == false)
2515
					fatal_error($txt['chmod_value_invalid']);
2516
			}
2517
2518
			// Nothing to do?
2519
			if (empty($context['to_process']))
2520
				redirectexit('action=admin;area=packages;sa=perms' . (!empty($context['back_look_data']) ? ';back_look=' . base64_encode($smcFunc['json_encode']($context['back_look_data'])) : '') . ';' . $context['session_var'] . '=' . $context['session_id']);
2521
		}
2522
		// Should never get here,
2523
		else
2524
			fatal_lang_error('no_access', false);
2525
2526
		// Setup the custom value.
2527
		$custom_value = octdec('0' . $context['custom_value']);
2528
2529
		// Start processing items.
2530
		foreach ($context['to_process'] as $path => $status)
2531
		{
2532
			if (in_array($status, array('execute', 'writable', 'read')))
2533
				package_chmod($path, $status);
2534
			elseif ($status == 'custom' && !empty($custom_value))
2535
			{
2536
				// Use FTP if we have it.
2537
				if (!empty($package_ftp) && !empty($_SESSION['pack_ftp']))
2538
				{
2539
					$ftp_file = strtr($path, array($_SESSION['pack_ftp']['root'] => ''));
2540
					$package_ftp->chmod($ftp_file, $custom_value);
2541
				}
2542
				else
2543
					smf_chmod($path, $custom_value);
2544
			}
2545
2546
			// This fish is fried...
2547
			unset($context['to_process'][$path]);
2548
2549
			// See if we're out of time?
2550
			if ((time() - TIME_START) > $timeout_limit)
2551
			{
2552
				// Prepare template usage for to_process.
2553
				$context['to_process_encode'] = base64_encode($smcFunc['json_encode']($context['to_process']));
2554
2555
				return false;
2556
			}
2557
		}
2558
2559
		// Prepare template usage for to_process.
2560
		$context['to_process_encode'] = base64_encode($smcFunc['json_encode']($context['to_process']));
2561
	}
2562
	// If predefined this is a little different.
2563
	else
2564
	{
2565
		$context['predefined_type'] = isset($_POST['predefined']) ? $_POST['predefined'] : 'restricted';
2566
2567
		$context['total_items'] = isset($_POST['totalItems']) ? (int) $_POST['totalItems'] : 0;
2568
		$context['directory_list'] = isset($_POST['dirList']) ? $smcFunc['json_decode'](base64_decode($_POST['dirList']), true) : array();
2569
2570
		$context['file_offset'] = isset($_POST['fileOffset']) ? (int) $_POST['fileOffset'] : 0;
2571
2572
		// Haven't counted the items yet?
2573
		if (empty($context['total_items']))
2574
		{
2575
			/**
2576
			 * Counts all the directories under a given path
2577
			 *
2578
			 * @param string $dir
2579
			 * @return integer
2580
			 */
2581
			function count_directories__recursive($dir)
2582
			{
2583
				global $context;
2584
2585
				$count = 0;
2586
				$dh = @opendir($dir);
2587
				while ($entry = readdir($dh))
2588
				{
2589
					if ($entry != '.' && $entry != '..' && is_dir($dir . '/' . $entry))
2590
					{
2591
						$context['directory_list'][$dir . '/' . $entry] = 1;
2592
						$count++;
2593
						$count += count_directories__recursive($dir . '/' . $entry);
2594
					}
2595
				}
2596
				closedir($dh);
2597
2598
				return $count;
2599
			}
2600
2601
			foreach ($context['file_tree'] as $path => $data)
2602
			{
2603
				if (is_dir($path))
2604
				{
2605
					$context['directory_list'][$path] = 1;
2606
					$context['total_items'] += count_directories__recursive($path);
2607
					$context['total_items']++;
2608
				}
2609
			}
2610
		}
2611
2612
		// Have we built up our list of special files?
2613
		if (!isset($_POST['specialFiles']) && $context['predefined_type'] != 'free')
2614
		{
2615
			$context['special_files'] = array();
2616
2617
			/**
2618
			 * Builds a list of special files recursively for a given path
2619
			 *
2620
			 * @param string $path
2621
			 * @param array $data
2622
			 */
2623
			function build_special_files__recursive($path, &$data)
2624
			{
2625
				global $context;
2626
2627
				if (!empty($data['writable_on']))
2628
					if ($context['predefined_type'] == 'standard' || $data['writable_on'] == 'restrictive')
2629
						$context['special_files'][$path] = 1;
2630
2631
				if (!empty($data['contents']))
2632
					foreach ($data['contents'] as $name => $contents)
2633
						build_special_files__recursive($path . '/' . $name, $contents);
2634
			}
2635
2636
			foreach ($context['file_tree'] as $path => $data)
2637
				build_special_files__recursive($path, $data);
2638
		}
2639
		// Free doesn't need special files.
2640
		elseif ($context['predefined_type'] == 'free')
2641
			$context['special_files'] = array();
2642
		else
2643
			$context['special_files'] = $smcFunc['json_decode'](base64_decode($_POST['specialFiles']), true);
2644
2645
		// Now we definitely know where we are, we need to go through again doing the chmod!
2646
		foreach ($context['directory_list'] as $path => $dummy)
2647
		{
2648
			// Do the contents of the directory first.
2649
			$dh = @opendir($path);
2650
			$file_count = 0;
2651
			$dont_chmod = false;
2652
			while ($entry = readdir($dh))
2653
			{
2654
				// Bypass directory abbreviations altogether...
2655
				if ($entry == '.' || $entry == '..')
2656
					continue;
2657
2658
				$file_count++;
2659
				// Actually process this file?
2660
				if (!$dont_chmod && !is_dir($path . '/' . $entry) && (empty($context['file_offset']) || $context['file_offset'] < $file_count))
2661
				{
2662
					$status = $context['predefined_type'] == 'free' || isset($context['special_files'][$path . '/' . $entry]) ? 'writable' : 'execute';
2663
					package_chmod($path . '/' . $entry, $status);
2664
				}
2665
2666
				// See if we're out of time?
2667
				if (!$dont_chmod && (time() - TIME_START) > $timeout_limit)
2668
				{
2669
					$dont_chmod = true;
2670
					// Don't do this again.
2671
					$context['file_offset'] = $file_count;
2672
				}
2673
			}
2674
			closedir($dh);
2675
2676
			// If this is set it means we timed out half way through.
2677
			if ($dont_chmod)
2678
			{
2679
				$context['total_files'] = $file_count;
2680
				$context['directory_list_encode'] = base64_encode($smcFunc['json_encode']($context['directory_list']));
2681
				$context['special_files_encode'] = base64_encode($smcFunc['json_encode']($context['special_files']));
2682
				return false;
2683
			}
2684
2685
			// Do the actual directory.
2686
			$status = $context['predefined_type'] == 'free' || isset($context['special_files'][$path]) ? 'writable' : 'execute';
2687
			package_chmod($path, $status);
2688
2689
			// We've finished the directory so no file offset, and no record.
2690
			$context['file_offset'] = 0;
2691
			unset($context['directory_list'][$path]);
2692
2693
			// See if we're out of time?
2694
			if ((time() - TIME_START) > $timeout_limit)
2695
			{
2696
				// Prepare this for usage on templates.
2697
				$context['directory_list_encode'] = base64_encode($smcFunc['json_encode']($context['directory_list']));
2698
				$context['special_files_encode'] = base64_encode($smcFunc['json_encode']($context['special_files']));
2699
2700
				return false;
2701
			}
2702
		}
2703
2704
		// Prepare this for usage on templates.
2705
		$context['directory_list_encode'] = base64_encode($smcFunc['json_encode']($context['directory_list']));
2706
		$context['special_files_encode'] = base64_encode($smcFunc['json_encode']($context['special_files']));
2707
	}
2708
2709
	// If we're here we are done!
2710
	redirectexit('action=admin;area=packages;sa=perms' . (!empty($context['back_look_data']) ? ';back_look=' . base64_encode($smcFunc['json_encode']($context['back_look_data'])) : '') . ';' . $context['session_var'] . '=' . $context['session_id']);
2711
}
2712
2713
/**
2714
 * Test an FTP connection.
2715
 */
2716
function PackageFTPTest()
2717
{
2718
	global $context, $txt, $package_ftp;
2719
2720
	checkSession('get');
2721
2722
	// Try to make the FTP connection.
2723
	create_chmod_control(array(), array('force_find_error' => true));
2724
2725
	// Deal with the template stuff.
2726
	loadTemplate('Xml');
2727
	$context['sub_template'] = 'generic_xml';
2728
	$context['template_layers'] = array();
2729
2730
	// Define the return data, this is simple.
2731
	$context['xml_data'] = array(
2732
		'results' => array(
2733
			'identifier' => 'result',
2734
			'children' => array(
2735
				array(
2736
					'attributes' => array(
2737
						'success' => !empty($package_ftp) ? 1 : 0,
2738
					),
2739
					'value' => !empty($package_ftp) ? $txt['package_ftp_test_success'] : (isset($context['package_ftp'], $context['package_ftp']['error']) ? $context['package_ftp']['error'] : $txt['package_ftp_test_failed']),
2740
				),
2741
			),
2742
		),
2743
	);
2744
}
2745
2746
?>