<commit_before><?php

/**
 * This file is the main Package Manager.
 *
 * Simple Machines Forum (SMF)
 *
 * @package SMF
 * @author Simple Machines http://www.simplemachines.org
 * @copyright 2015 Simple Machines and individual contributors
 * @license http://www.simplemachines.org/about/smf/license.php BSD
 *
 * @version 2.1 Beta 2
 */

if (!defined('SMF'))
	die('No direct access...');

/**
 * This is the notoriously defunct package manager..... :/.
 */
function Packages()
{
	global $txt, $sourcedir, $context;

	// @todo Remove this!
	if (isset($_GET['get']) || isset($_GET['pgdownload']))
	{
		require_once($sourcedir . '/PackageGet.php');
		return PackageGet();
	}

	isAllowedTo('admin_forum');

	// Load all the basic stuff.
	require_once($sourcedir . '/Subs-Package.php');
	loadLanguage('Packages');
	loadTemplate('Packages', 'admin');

	$context['page_title'] = $txt['package'];

	// Delegation makes the world... that is, the package manager go 'round.
	$subActions = array(
		'browse' => 'PackageBrowse',
		'remove' => 'PackageRemove',
		'list' => 'PackageList',
		'ftptest' => 'PackageFTPTest',
		'install' => 'PackageInstallTest',
		'install2' => 'PackageInstall',
		'uninstall' => 'PackageInstallTest',
		'uninstall2' => 'PackageInstall',
		'options' => 'PackageOptions',
		'perms' => 'PackagePermissions',
		'flush' => 'FlushInstall',
		'examine' => 'ExamineFile',
		'showoperations' => 'ViewOperations',
	);

	// Work out exactly who it is we are calling.
	if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
		$context['sub_action'] = $_REQUEST['sa'];
	else
		$context['sub_action'] = 'browse';

	// Set up some tabs...
	$context[$context['admin_menu_name']]['tab_data'] = array(
		'title' => $txt['package_manager'],
		// @todo 'help' => 'registrations',
		'description' => $txt['package_manager_desc'],
		'tabs' => array(
			'browse' => array(
			),
			'packageget' => array(
				'description' => $txt['download_packages_desc'],
			),
			'perms' => array(
				'description' => $txt['package_file_perms_desc'],
			),
			'options' => array(
				'description' => $txt['package_install_options_desc'],
			),
		),
	);

	if ($context['sub_action'] == 'browse')
		loadJavascriptFile('suggest.js', array('default_theme' => true, 'defer' => false), 'smf_suggest');

	call_integration_hook('integrate_manage_packages', array(&$subActions));

	// Call the function we're handing control to.
	call_helper($subActions[$context['sub_action']]);
}

/**
 * Test install a package.
 */
function PackageInstallTest()
{
	global $boarddir, $txt, $context, $scripturl, $sourcedir, $packagesdir, $modSettings, $smcFunc, $settings;

	// You have to specify a file!!
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
		redirectexit('action=admin;area=packages');
	$context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);

	// Do we have an existing id, for uninstalls and the like.
	$context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;

	require_once($sourcedir . '/Subs-Package.php');

	// Load up the package FTP information?
	create_chmod_control();

	// Make sure temp directory exists and is empty.
	if (file_exists($packagesdir . '/temp'))
		deltree($packagesdir . '/temp', false);

	if (!mktree($packagesdir . '/temp', 0755))
	{
		deltree($packagesdir . '/temp', false);
		if (!mktree($packagesdir . '/temp', 0777))
		{
			deltree($packagesdir . '/temp', false);
			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));

			deltree($packagesdir . '/temp', false);
			if (!mktree($packagesdir . '/temp', 0777))
				fatal_lang_error('package_cant_download', false);
		}
	}

	$context['uninstalling'] = $_REQUEST['sa'] == 'uninstall';

	// Change our last link tree item for more information on this Packages area.
	$context['linktree'][count($context['linktree']) - 1] = array(
		'url' => $scripturl . '?action=admin;area=packages;sa=browse',
		'name' => $context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']
	);
	$context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']);

	$context['sub_template'] = 'view_package';

	if (!file_exists($packagesdir . '/' . $context['filename']))
	{
		deltree($packagesdir . '/temp');
		fatal_lang_error('package_no_file', false);
	}

	// Extract the files so we can get things like the readme, etc.
	if (is_file($packagesdir . '/' . $context['filename']))
	{
		$context['extracted_files'] = read_tgz_file($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');

		if ($context['extracted_files'] && !file_exists($packagesdir . '/temp/package-info.xml'))
			foreach ($context['extracted_files'] as $file)
				if (basename($file['filename']) == 'package-info.xml')
				{
					$context['base_path'] = dirname($file['filename']) . '/';
					break;
				}

		if (!isset($context['base_path']))
			$context['base_path'] = '';
	}
	elseif (is_dir($packagesdir . '/' . $context['filename']))
	{
		copytree($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
		$context['extracted_files'] = listtree($packagesdir . '/temp');
		$context['base_path'] = '';
	}
	else
		fatal_lang_error('no_access', false);

	// Load up any custom themes we may want to install into...
	$request = $smcFunc['db_query']('', '
		SELECT id_theme, variable, value
		FROM {db_prefix}themes
		WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
			AND variable IN ({string:name}, {string:theme_dir})',
		array(
			'known_theme_list' => explode(',', $modSettings['knownThemes']),
			'default_theme' => 1,
			'name' => 'name',
			'theme_dir' => 'theme_dir',
		)
	);
	$theme_paths = array();
	while ($row = $smcFunc['db_fetch_assoc']($request))
		$theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
	$smcFunc['db_free_result']($request);

	// Get the package info...
	$packageInfo = getPackageInfo($context['filename']);

	if (!is_array($packageInfo))
		fatal_lang_error($packageInfo);

	$packageInfo['filename'] = $context['filename'];
	$context['package_name'] = isset($packageInfo['name']) ? $packageInfo['name'] : $context['filename'];

	// Set the type of extraction...
	$context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';

	// The mod isn't installed.... unless proven otherwise.
	$context['is_installed'] = false;

	// See if it is installed?
	$request = $smcFunc['db_query']('', '
		SELECT version, themes_installed, db_changes
		FROM {db_prefix}log_packages
		WHERE package_id = {string:current_package}
			AND install_state != {int:not_installed}
		ORDER BY time_installed DESC
		LIMIT 1',
		array(
			'not_installed'	=> 0,
			'current_package' => $packageInfo['id'],
		)
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$old_themes = explode(',', $row['themes_installed']);
		$old_version = $row['version'];
		$db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
	}
	$smcFunc['db_free_result']($request);

	$context['database_changes'] = array();
	if (isset($packageInfo['uninstall']['database']))
		$context['database_changes'][] = $txt['execute_database_changes'] . ' - ' . $packageInfo['uninstall']['database'];
	elseif (!empty($db_changes))
	{
		foreach ($db_changes as $change)
		{
			if (isset($change[2]) && isset($txt['package_db_' . $change[0]]))
				$context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1], $change[2]);
			elseif (isset($txt['package_db_' . $change[0]]))
				$context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1]);
			else
				$context['database_changes'][] = $change[0] . '-' . $change[1] . (isset($change[2]) ? '-' . $change[2] : '');
		}
	}

	// Uninstalling?
	if ($context['uninstalling'])
	{
		// Wait, it's not installed yet!
		if (!isset($old_version) && $context['uninstalling'])
		{
			deltree($packagesdir . '/temp');
			fatal_lang_error('package_cant_uninstall', false);
		}

		$actions = parsePackageInfo($packageInfo['xml'], true, 'uninstall');

		// Gadzooks!  There's no uninstaller at all!?
		if (empty($actions))
		{
			deltree($packagesdir . '/temp');
			fatal_lang_error('package_uninstall_cannot', false);
		}

		// Can't edit the custom themes it's edited if you're uninstalling, they must be removed.
		$context['themes_locked'] = true;

		// Only let them uninstall themes it was installed into.
		foreach ($theme_paths as $id => $data)
			if ($id != 1 && !in_array($id, $old_themes))
				unset($theme_paths[$id]);
	}
	elseif (isset($old_version) && $old_version != $packageInfo['version'])
	{
		// Look for an upgrade...
		$actions = parsePackageInfo($packageInfo['xml'], true, 'upgrade', $old_version);

		// There was no upgrade....
		if (empty($actions))
			$context['is_installed'] = true;
		else
		{
			// Otherwise they can only upgrade themes from the first time around.
			foreach ($theme_paths as $id => $data)
				if ($id != 1 && !in_array($id, $old_themes))
					unset($theme_paths[$id]);
		}
	}
	elseif (isset($old_version) && $old_version == $packageInfo['version'])
		$context['is_installed'] = true;

	if (!isset($old_version) || $context['is_installed'])
		$actions = parsePackageInfo($packageInfo['xml'], true, 'install');

	$context['actions'] = array();
	$context['ftp_needed'] = false;
	$context['has_failure'] = false;
	$chmod_files = array();

	// no actions found, return so we can display an error
	if (empty($actions))
		return;

	// This will hold data about anything that can be installed in other themes.
	$themeFinds = array(
		'candidates' => array(),
		'other_themes' => array(),
	);

	// Now prepare things for the template.
	foreach ($actions as $action)
	{
		// Not failed until proven otherwise.
		$failed = false;
		$thisAction = array();

		if ($action['type'] == 'chmod')
		{
			$chmod_files[] = $action['filename'];
			continue;
		}
		elseif ($action['type'] == 'readme' || $action['type'] == 'license')
		{
			$type = 'package_' . $action['type'];
			if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
				$context[$type] = $smcFunc['htmlspecialchars'](trim(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), "\n\r"));
			elseif (file_exists($action['filename']))
				$context[$type] = $smcFunc['htmlspecialchars'](trim(file_get_contents($action['filename']), "\n\r"));

			if (!empty($action['parse_bbc']))
			{
				require_once($sourcedir . '/Subs-Post.php');
				$context[$type] = preg_replace('~\[[/]?html\]~i', '', $context[$type]);
				preparsecode($context[$type]);
				$context[$type] = parse_bbc($context[$type]);
			}
			else
				$context[$type] = nl2br($context[$type]);

			continue;
		}
		// Don't show redirects.
		elseif ($action['type'] == 'redirect')
			continue;
		elseif ($action['type'] == 'error')
		{
			$context['has_failure'] = true;
			if (isset($action['error_msg']) && isset($action['error_var']))
				$context['failure_details'] = sprintf($txt['package_will_fail_' . $action['error_msg']], $action['error_var']);
			elseif (isset($action['error_msg']))
				$context['failure_details'] = isset($txt['package_will_fail_' . $action['error_msg']]) ? $txt['package_will_fail_' . $action['error_msg']] : $action['error_msg'];
		}
		elseif ($action['type'] == 'modification')
		{
			if (!file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
			{
				$context['has_failure'] = true;

				$context['actions'][] = array(
					'type' => $txt['execute_modification'],
					'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.'))),
					'description' => $txt['package_action_missing'],
					'failed' => true,
				);
			}
			else
			{

				if ($action['boardmod'])
					$mod_actions = parseBoardMod(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
				else
					$mod_actions = parseModification(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);

				if (count($mod_actions) == 1 && isset($mod_actions[0]) && $mod_actions[0]['type'] == 'error' && $mod_actions[0]['filename'] == '-')
					$mod_actions[0]['filename'] = $action['filename'];

				foreach ($mod_actions as $key => $mod_action)
				{
					// Lets get the last section of the file name.
					if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
						$actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
					elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
						$actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
					else
						$actual_filename = $key;

					if ($mod_action['type'] == 'opened')
						$failed = false;
					elseif ($mod_action['type'] == 'failure')
					{
						if (empty($mod_action['is_custom']))
							$context['has_failure'] = true;
						$failed = true;
					}
					elseif ($mod_action['type'] == 'chmod')
					{
						$chmod_files[] = $mod_action['filename'];
					}
					elseif ($mod_action['type'] == 'saved')
					{
						if (!empty($mod_action['is_custom']))
						{
							if (!isset($context['theme_actions'][$mod_action['is_custom']]))
								$context['theme_actions'][$mod_action['is_custom']] = array(
									'name' => $theme_paths[$mod_action['is_custom']]['name'],
									'actions' => array(),
									'has_failure' => $failed,
								);
							else
								$context['theme_actions'][$mod_action['is_custom']]['has_failure'] |= $failed;

							$context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
								'failed' => $failed,
							);
						}
						elseif (!isset($context['actions'][$actual_filename]))
						{
							$context['actions'][$actual_filename] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
								'failed' => $failed,
							);
						}
						else
						{
								$context['actions'][$actual_filename]['failed'] |= $failed;
								$context['actions'][$actual_filename]['description'] = $context['actions'][$actual_filename]['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'];
						}
					}
					elseif ($mod_action['type'] == 'skipping')
					{
						$context['actions'][$actual_filename] = array(
							'type' => $txt['execute_modification'],
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
							'description' => $txt['package_action_skipping']
						);
					}
					elseif ($mod_action['type'] == 'missing' && empty($mod_action['is_custom']))
					{
						$context['has_failure'] = true;
						$context['actions'][$actual_filename] = array(
							'type' => $txt['execute_modification'],
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
							'description' => $txt['package_action_missing'],
							'failed' => true,
						);
					}
					elseif ($mod_action['type'] == 'error')
						$context['actions'][$actual_filename] = array(
							'type' => $txt['execute_modification'],
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
							'description' => $txt['package_action_error'],
							'failed' => true,
						);
				}

				// We need to loop again just to get the operations down correctly.
				foreach ($mod_actions as $operation_key => $mod_action)
				{
					// Lets get the last section of the file name.
					if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
						$actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
					elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
						$actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
					else
						$actual_filename = $key;

					// We just need it for actual parse changes.
					if (!in_array($mod_action['type'], array('error', 'result', 'opened', 'saved', 'end', 'missing', 'skipping', 'chmod')))
					{
						if (empty($mod_action['is_custom']))
							$context['actions'][$actual_filename]['operations'][] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
								'position' => $mod_action['position'],
								'operation_key' => $operation_key,
								'filename' => $action['filename'],
								'is_boardmod' => $action['boardmod'],
								'failed' => $mod_action['failed'],
								'ignore_failure' => !empty($mod_action['ignore_failure']),
							);

						// Themes are under the saved type.
						if (isset($mod_action['is_custom']) && isset($context['theme_actions'][$mod_action['is_custom']]))
							$context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename]['operations'][] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
								'position' => $mod_action['position'],
								'operation_key' => $operation_key,
								'filename' => $action['filename'],
								'is_boardmod' => $action['boardmod'],
								'failed' => $mod_action['failed'],
								'ignore_failure' => !empty($mod_action['ignore_failure']),
							);
					}
				}
			}
		}
		elseif ($action['type'] == 'code')
		{
			$thisAction = array(
				'type' => $txt['execute_code'],
				'action' => $smcFunc['htmlspecialchars']($action['filename']),
			);
		}
		elseif ($action['type'] == 'database')
		{
			$thisAction = array(
				'type' => $txt['execute_database_changes'],
				'action' => $smcFunc['htmlspecialchars']($action['filename']),
			);
		}
		elseif (in_array($action['type'], array('create-dir', 'create-file')))
		{
			$thisAction = array(
				'type' => $txt['package_create'] . ' ' . ($action['type'] == 'create-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
			);
		}
		elseif ($action['type'] == 'hook')
		{
			$action['description'] = !isset($action['hook'], $action['function']) ? $txt['package_action_failure'] : $txt['package_action_success'];

			if (!isset($action['hook'], $action['function']))
				$context['has_failure'] = true;

			$thisAction = array(
				'type' => $action['reverse'] ? $txt['execute_hook_remove'] : $txt['execute_hook_add'],
				'action' => sprintf($txt['execute_hook_action'],  $smcFunc['htmlspecialchars']($action['hook'])),
			);
		}
		elseif ($action['type'] == 'credits')
		{
			$thisAction = array(
				'type' => $txt['execute_credits_add'],
				'action' => sprintf($txt['execute_credits_action'],  $smcFunc['htmlspecialchars']($action['title'])),
			);
		}
		elseif ($action['type'] == 'requires')
		{
			$installed = false;
			$version = true;

			// package missing required values?
			if (!isset($action['id']))
				$context['has_failure'] = true;
			else
			{
				// See if this dependancy is installed
				$request = $smcFunc['db_query']('', '
					SELECT version
					FROM {db_prefix}log_packages
					WHERE package_id = {string:current_package}
						AND install_state != {int:not_installed}
					ORDER BY time_installed DESC
					LIMIT 1',
					array(
						'not_installed'	=> 0,
						'current_package' => $action['id'],
					)
				);
				$installed = ($smcFunc['db_num_rows']($request) !== 0);
				if ($installed)
					list ($version) = $smcFunc['db_fetch_row']($request);
				$smcFunc['db_free_result']($request);

				// do a version level check (if requested) in the most basic way
				$version = (isset($action['version']) ? $version == $action['version'] : true);
			}

			// Set success or failure information
			$action['description'] = ($installed && $version) ? $txt['package_action_success'] : $txt['package_action_failure'];
			$context['has_failure'] = !($installed && $version);

			$thisAction = array(
				'type' => $txt['package_requires'],
				'action' => $txt['package_check_for'] . ' ' . $action['id'] . (isset($action['version']) ? (' / ' . ($version ? $action['version'] : '<span class="error">' . $action['version'] . '</span>')) : ''),
			);
		}
		elseif (in_array($action['type'], array('require-dir', 'require-file')))
		{
			// Do this one...
			$thisAction = array(
				'type' => $txt['package_extract'] . ' ' . ($action['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
			);

			// Could this be theme related?
			if (!empty($action['unparsed_destination']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_destination'], $matches))
			{
				// Is the action already stated?
				$theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
				// If it's not auto do we think we have something we can act upon?
				if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
					$theme_action = '';
				// ... or if it's auto do we even want to do anything?
				elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
					$theme_action = '';

				// So, we still want to do something?
				if ($theme_action != '')
					$themeFinds['candidates'][] = $action;
				// Otherwise is this is going into another theme record it.
				elseif ($matches[1] == 'themes_dir')
					$themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_destination']), array('\\' => '/')) . '/' . basename($action['filename']));
			}
		}
		elseif (in_array($action['type'], array('move-dir', 'move-file')))
			$thisAction = array(
				'type' => $txt['package_move'] . ' ' . ($action['type'] == 'move-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['source'], array($boarddir => '.'))) . ' => ' . $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
			);
		elseif (in_array($action['type'], array('remove-dir', 'remove-file')))
		{
			$thisAction = array(
				'type' => $txt['package_delete'] . ' ' . ($action['type'] == 'remove-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.')))
			);

			// Could this be theme related?
			if (!empty($action['unparsed_filename']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_filename'], $matches))
			{

				// Is the action already stated?
				$theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
				$action['unparsed_destination'] = $action['unparsed_filename'];

				// If it's not auto do we think we have something we can act upon?
				if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
					$theme_action = '';
				// ... or if it's auto do we even want to do anything?
				elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
					$theme_action = '';

				// So, we still want to do something?
				if ($theme_action != '')
					$themeFinds['candidates'][] = $action;
				// Otherwise is this is going into another theme record it.
				elseif ($matches[1] == 'themes_dir')
					$themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_filename']), array('\\' => '/')) . '/' . basename($action['filename']));
			}
		}

		if (empty($thisAction))
			continue;

		if (!in_array($action['type'], array('hook', 'credits')))
		{
			if ($context['uninstalling'])
				$file = in_array($action['type'], array('remove-dir', 'remove-file')) ? $action['filename'] : $packagesdir . '/temp/' . $context['base_path'] . $action['filename'];
			else
				$file =  $packagesdir . '/temp/' . $context['base_path'] . $action['filename'];
		}

		if (isset($action['filename']) && !file_exists($file))
		{
			$context['has_failure'] = true;

			$thisAction += array(
				'description' => $txt['package_action_error'],
				'failed' => true,
			);
		}

		// @todo None given?
		if (empty($thisAction['description']))
			$thisAction['description'] = isset($action['description']) ? $action['description'] : '';

		$context['actions'][] = $thisAction;
	}

	// Have we got some things which we might want to do "multi-theme"?
	if (!empty($themeFinds['candidates']))
	{
		foreach ($themeFinds['candidates'] as $action_data)
		{
			// Get the part of the file we'll be dealing with.
			preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir)(\\|/)*(.+)*~i', $action_data['unparsed_destination'], $matches);

			if ($matches[1] == 'imagesdir')
				$path = '/' . basename($settings['default_images_url']);
			elseif ($matches[1] == 'languagedir' || $matches[1] == 'languages_dir')
				$path = '/languages';
			else
				$path = '';

			if (!empty($matches[3]))
				$path .= $matches[3];

			if (!$context['uninstalling'])
				$path .= '/' . basename($action_data['filename']);

			// Loop through each custom theme to note it's candidacy!
			foreach ($theme_paths as $id => $theme_data)
			{
				if (isset($theme_data['theme_dir']) && $id != 1)
				{
					$real_path = $theme_data['theme_dir'] . $path;

					// Confirm that we don't already have this dealt with by another entry.
					if (!in_array(strtolower(strtr($real_path, array('\\' => '/'))), $themeFinds['other_themes']))
					{
						// Check if we will need to chmod this.
						if (!mktree(dirname($real_path), false))
						{
							$temp = dirname($real_path);
							while (!file_exists($temp) && strlen($temp) > 1)
								$temp = dirname($temp);
							$chmod_files[] = $temp;
						}

						if ($action_data['type'] == 'require-dir' && !is_writable($real_path) && (file_exists($real_path) || !is_writable(dirname($real_path))))
							$chmod_files[] = $real_path;

						if (!isset($context['theme_actions'][$id]))
							$context['theme_actions'][$id] = array(
								'name' => $theme_data['name'],
								'actions' => array(),
							);

						if ($context['uninstalling'])
							$context['theme_actions'][$id]['actions'][] = array(
								'type' => $txt['package_delete'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
								'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
								'description' => '',
								'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['filename'], 'future' => $real_path, 'id' => $id))),
								'not_mod' => true,
							);
						else
							$context['theme_actions'][$id]['actions'][] = array(
								'type' => $txt['package_extract'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
								'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
								'description' => '',
								'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['destination'], 'future' => $real_path, 'id' => $id))),
								'not_mod' => true,
							);
					}
				}
			}
		}
	}

	// Trash the cache... which will also check permissions for us!
	package_flush_cache(true);

	if (file_exists($packagesdir . '/temp'))
		deltree($packagesdir . '/temp');

	if (!empty($chmod_files))
	{
		$ftp_status = create_chmod_control($chmod_files);
		$context['ftp_needed'] = !empty($ftp_status['files']['notwritable']) && !empty($context['package_ftp']);
	}

	$context['post_url'] = $scripturl .'?action=admin;area=packages;sa=' . ($context['uninstalling'] ? 'uninstall' : 'install') . ($context['ftp_needed'] ? '' : '2') . ';package=' . $context['filename'] . ';pid=' . $context['install_id'];
	checkSubmitOnce('register');
}

/**
 * Apply another type of (avatar, language, etc.) package.
 */
function PackageInstall()
{
	global $boarddir, $txt, $context, $boardurl, $scripturl, $sourcedir, $packagesdir, $modSettings;
	global $user_info, $smcFunc;

	// Make sure we don't install this mod twice.
	checkSubmitOnce('check');
	checkSession();

	// If there's no file, what are we installing?
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
		redirectexit('action=admin;area=packages');
	$context['filename'] = $_REQUEST['package'];

	// If this is an uninstall, we'll have an id.
	$context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;

	require_once($sourcedir . '/Subs-Package.php');

	// @todo Perhaps do it in steps, if necessary?

	$context['uninstalling'] = $_REQUEST['sa'] == 'uninstall2';

	// Set up the linktree for other.
	$context['linktree'][count($context['linktree']) - 1] = array(
		'url' => $scripturl . '?action=admin;area=packages;sa=browse',
		'name' => $context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']
	);
	$context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']);

	$context['sub_template'] = 'extract_package';

	if (!file_exists($packagesdir . '/' . $context['filename']))
		fatal_lang_error('package_no_file', false);

	// Load up the package FTP information?
	create_chmod_control(array(), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package']));

	// Make sure temp directory exists and is empty!
	if (file_exists($packagesdir . '/temp'))
		deltree($packagesdir . '/temp', false);
	else
		mktree($packagesdir . '/temp', 0777);

	// Let the unpacker do the work.
	if (is_file($packagesdir . '/' . $context['filename']))
	{
		$context['extracted_files'] = read_tgz_file($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');

		if (!file_exists($packagesdir . '/temp/package-info.xml'))
			foreach ($context['extracted_files'] as $file)
				if (basename($file['filename']) == 'package-info.xml')
				{
					$context['base_path'] = dirname($file['filename']) . '/';
					break;
				}

		if (!isset($context['base_path']))
			$context['base_path'] = '';
	}
	elseif (is_dir($packagesdir . '/' . $context['filename']))
	{
		copytree($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
		$context['extracted_files'] = listtree($packagesdir . '/temp');
		$context['base_path'] = '';
	}
	else
		fatal_lang_error('no_access', false);

	// Are we installing this into any custom themes?
	$custom_themes = array(1);
	$known_themes = explode(',', $modSettings['knownThemes']);
	if (!empty($_POST['custom_theme']))
	{
		foreach ($_POST['custom_theme'] as $tid)
			if (in_array($tid, $known_themes))
				$custom_themes[] = (int) $tid;
	}

	// Now load up the paths of the themes that we need to know about.
	$request = $smcFunc['db_query']('', '
		SELECT id_theme, variable, value
		FROM {db_prefix}themes
		WHERE id_theme IN ({array_int:custom_themes})
			AND variable IN ({string:name}, {string:theme_dir})',
		array(
			'custom_themes' => $custom_themes,
			'name' => 'name',
			'theme_dir' => 'theme_dir',
		)
	);
	$theme_paths = array();
	$themes_installed = array(1);
	while ($row = $smcFunc['db_fetch_assoc']($request))
		$theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
	$smcFunc['db_free_result']($request);

	// Are there any theme copying that we want to take place?
	$context['theme_copies'] = array(
		'require-file' => array(),
		'require-dir' => array(),
	);
	if (!empty($_POST['theme_changes']))
	{
		foreach ($_POST['theme_changes'] as $change)
		{
			if (empty($change))
				continue;
			$theme_data = unserialize(base64_decode($change));
			if (empty($theme_data['type']))
				continue;

			$themes_installed[] = $theme_data['id'];
			$context['theme_copies'][$theme_data['type']][$theme_data['orig']][] = $theme_data['future'];
		}
	}

	// Get the package info...
	$packageInfo = getPackageInfo($context['filename']);
	if (!is_array($packageInfo))
		fatal_lang_error($packageInfo);

	$packageInfo['filename'] = $context['filename'];

	// Set the type of extraction...
	$context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';

	// Create a backup file to roll back to! (but if they do this more than once, don't run it a zillion times.)
	if (!empty($modSettings['package_make_full_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['filename'] . ($context['uninstalling'] ? '$$' : '$')))
	{
		$_SESSION['last_backup_for'] = $context['filename'] . ($context['uninstalling'] ? '$$' : '$');
		$result = package_create_backup(($context['uninstalling'] ? 'backup_' : 'before_') . strtok($context['filename'], '.'));
		if (!$result)
			fatal_lang_error('could_not_package_backup', false);
	}

	// The mod isn't installed.... unless proven otherwise.
	$context['is_installed'] = false;

	// Is it actually installed?
	$request = $smcFunc['db_query']('', '
		SELECT version, themes_installed, db_changes
		FROM {db_prefix}log_packages
		WHERE package_id = {string:current_package}
			AND install_state != {int:not_installed}
		ORDER BY time_installed DESC
		LIMIT 1',
		array(
			'not_installed'	=> 0,
			'current_package' => $packageInfo['id'],
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$old_themes = explode(',', $row['themes_installed']);
		$old_version = $row['version'];
		$db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
	}
	$smcFunc['db_free_result']($request);

	// Wait, it's not installed yet!
	// @todo Replace with a better error message!
	if (!isset($old_version) && $context['uninstalling'])
	{
		deltree($packagesdir . '/temp');
		fatal_error('Hacker?', false);
	}
	// Uninstalling?
	elseif ($context['uninstalling'])
	{
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'uninstall');

		// Gadzooks!  There's no uninstaller at all!?
		if (empty($install_log))
			fatal_lang_error('package_uninstall_cannot', false);

		// They can only uninstall from what it was originally installed into.
		foreach ($theme_paths as $id => $data)
			if ($id != 1 && !in_array($id, $old_themes))
				unset($theme_paths[$id]);
	}
	elseif (isset($old_version) && $old_version != $packageInfo['version'])
	{
		// Look for an upgrade...
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'upgrade', $old_version);

		// There was no upgrade....
		if (empty($install_log))
			$context['is_installed'] = true;
		else
		{
			// Upgrade previous themes only!
			foreach ($theme_paths as $id => $data)
				if ($id != 1 && !in_array($id, $old_themes))
					unset($theme_paths[$id]);
		}
	}
	elseif (isset($old_version) && $old_version == $packageInfo['version'])
		$context['is_installed'] = true;

	if (!isset($old_version) || $context['is_installed'])
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'install');

	$context['install_finished'] = false;

	// @todo Make a log of any errors that occurred and output them?

	if (!empty($install_log))
	{
		$failed_steps = array();
		$failed_count = 0;

		foreach ($install_log as $action)
		{
			$failed_count++;

			if ($action['type'] == 'modification' && !empty($action['filename']))
			{
				if ($action['boardmod'])
					$mod_actions = parseBoardMod(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
				else
					$mod_actions = parseModification(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);

				// Any errors worth noting?
				foreach ($mod_actions as $key => $action)
				{
					if ($action['type'] == 'failure')
						$failed_steps[] = array(
							'file' => $action['filename'],
							'large_step' => $failed_count,
							'sub_step' => $key,
							'theme' => 1,
						);

					// Gather the themes we installed into.
					if (!empty($action['is_custom']))
						$themes_installed[] = $action['is_custom'];
				}
			}
			elseif ($action['type'] == 'code' && !empty($action['filename']))
			{
				// This is just here as reference for what is available.
				global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $forum_version, $smcFunc;

				// Now include the file and be done with it ;).
				if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
					require($packagesdir . '/temp/' . $context['base_path'] . $action['filename']);
			}
			elseif ($action['type'] == 'credits')
			{
				// Time to build the billboard
				$credits_tag = array(
					'url' => $action['url'],
					'license' => $action['license'],
					'licenseurl' => $action['licenseurl'],
					'copyright' => $action['copyright'],
					'title' => $action['title'],
				);
			}
			elseif ($action['type'] == 'hook' && isset($action['hook'], $action['function']))
			{
				if ($action['reverse'])
					remove_integration_function($action['hook'], $action['function'], true, $action['include_file'], $action['object']);
				else
					add_integration_function($action['hook'], $action['function'], true, $action['include_file'], $action['object']);
			}
			// Only do the database changes on uninstall if requested.
			elseif ($action['type'] == 'database' && !empty($action['filename']) && (!$context['uninstalling'] || !empty($_POST['do_db_changes'])))
			{
				// These can also be there for database changes.
				global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $forum_version, $smcFunc;
				global $db_package_log;

				// We'll likely want the package specific database functionality!
				db_extend('packages');

				// Let the file work its magic ;)
				if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
					require($packagesdir . '/temp/' . $context['base_path'] . $action['filename']);
			}
			// Handle a redirect...
			elseif ($action['type'] == 'redirect' && !empty($action['redirect_url']))
			{
				$context['redirect_url'] = $action['redirect_url'];
				$context['redirect_text'] = !empty($action['filename']) && file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']) ? file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']) : ($context['uninstalling'] ? $txt['package_uninstall_done'] : $txt['package_installed_done']);
				$context['redirect_timeout'] = $action['redirect_timeout'];

				// Parse out a couple of common urls.
				$urls = array(
					'$boardurl' => $boardurl,
					'$scripturl' => $scripturl,
					'$session_var' => $context['session_var'],
					'$session_id' => $context['session_id'],
				);

				$context['redirect_url'] = strtr($context['redirect_url'], $urls);
			}
		}

		package_flush_cache();

		// See if this is already installed, and change it's state as required.
		$request = $smcFunc['db_query']('', '
			SELECT package_id, install_state, db_changes
			FROM {db_prefix}log_packages
			WHERE install_state != {int:not_installed}
				AND package_id = {string:current_package}
				' . ($context['install_id'] ? ' AND id_install = {int:install_id} ' : '') . '
			ORDER BY time_installed DESC
			LIMIT 1',<commit_msg>sanitize redirect<commit_after><?php

/**
 * This file is the main Package Manager.
 *
 * Simple Machines Forum (SMF)
 *
 * @package SMF
 * @author Simple Machines http://www.simplemachines.org
 * @copyright 2015 Simple Machines and individual contributors
 * @license http://www.simplemachines.org/about/smf/license.php BSD
 *
 * @version 2.1 Beta 2
 */

if (!defined('SMF'))
	die('No direct access...');

/**
 * This is the notoriously defunct package manager..... :/.
 */
function Packages()
{
	global $txt, $sourcedir, $context;

	// @todo Remove this!
	if (isset($_GET['get']) || isset($_GET['pgdownload']))
	{
		require_once($sourcedir . '/PackageGet.php');
		return PackageGet();
	}

	isAllowedTo('admin_forum');

	// Load all the basic stuff.
	require_once($sourcedir . '/Subs-Package.php');
	loadLanguage('Packages');
	loadTemplate('Packages', 'admin');

	$context['page_title'] = $txt['package'];

	// Delegation makes the world... that is, the package manager go 'round.
	$subActions = array(
		'browse' => 'PackageBrowse',
		'remove' => 'PackageRemove',
		'list' => 'PackageList',
		'ftptest' => 'PackageFTPTest',
		'install' => 'PackageInstallTest',
		'install2' => 'PackageInstall',
		'uninstall' => 'PackageInstallTest',
		'uninstall2' => 'PackageInstall',
		'options' => 'PackageOptions',
		'perms' => 'PackagePermissions',
		'flush' => 'FlushInstall',
		'examine' => 'ExamineFile',
		'showoperations' => 'ViewOperations',
	);

	// Work out exactly who it is we are calling.
	if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
		$context['sub_action'] = $_REQUEST['sa'];
	else
		$context['sub_action'] = 'browse';

	// Set up some tabs...
	$context[$context['admin_menu_name']]['tab_data'] = array(
		'title' => $txt['package_manager'],
		// @todo 'help' => 'registrations',
		'description' => $txt['package_manager_desc'],
		'tabs' => array(
			'browse' => array(
			),
			'packageget' => array(
				'description' => $txt['download_packages_desc'],
			),
			'perms' => array(
				'description' => $txt['package_file_perms_desc'],
			),
			'options' => array(
				'description' => $txt['package_install_options_desc'],
			),
		),
	);

	if ($context['sub_action'] == 'browse')
		loadJavascriptFile('suggest.js', array('default_theme' => true, 'defer' => false), 'smf_suggest');

	call_integration_hook('integrate_manage_packages', array(&$subActions));

	// Call the function we're handing control to.
	call_helper($subActions[$context['sub_action']]);
}

/**
 * Test install a package.
 */
function PackageInstallTest()
{
	global $boarddir, $txt, $context, $scripturl, $sourcedir, $packagesdir, $modSettings, $smcFunc, $settings;

	// You have to specify a file!!
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
		redirectexit('action=admin;area=packages');
	$context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);

	// Do we have an existing id, for uninstalls and the like.
	$context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;

	require_once($sourcedir . '/Subs-Package.php');

	// Load up the package FTP information?
	create_chmod_control();

	// Make sure temp directory exists and is empty.
	if (file_exists($packagesdir . '/temp'))
		deltree($packagesdir . '/temp', false);

	if (!mktree($packagesdir . '/temp', 0755))
	{
		deltree($packagesdir . '/temp', false);
		if (!mktree($packagesdir . '/temp', 0777))
		{
			deltree($packagesdir . '/temp', false);
			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));

			deltree($packagesdir . '/temp', false);
			if (!mktree($packagesdir . '/temp', 0777))
				fatal_lang_error('package_cant_download', false);
		}
	}

	$context['uninstalling'] = $_REQUEST['sa'] == 'uninstall';

	// Change our last link tree item for more information on this Packages area.
	$context['linktree'][count($context['linktree']) - 1] = array(
		'url' => $scripturl . '?action=admin;area=packages;sa=browse',
		'name' => $context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']
	);
	$context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']);

	$context['sub_template'] = 'view_package';

	if (!file_exists($packagesdir . '/' . $context['filename']))
	{
		deltree($packagesdir . '/temp');
		fatal_lang_error('package_no_file', false);
	}

	// Extract the files so we can get things like the readme, etc.
	if (is_file($packagesdir . '/' . $context['filename']))
	{
		$context['extracted_files'] = read_tgz_file($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');

		if ($context['extracted_files'] && !file_exists($packagesdir . '/temp/package-info.xml'))
			foreach ($context['extracted_files'] as $file)
				if (basename($file['filename']) == 'package-info.xml')
				{
					$context['base_path'] = dirname($file['filename']) . '/';
					break;
				}

		if (!isset($context['base_path']))
			$context['base_path'] = '';
	}
	elseif (is_dir($packagesdir . '/' . $context['filename']))
	{
		copytree($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
		$context['extracted_files'] = listtree($packagesdir . '/temp');
		$context['base_path'] = '';
	}
	else
		fatal_lang_error('no_access', false);

	// Load up any custom themes we may want to install into...
	$request = $smcFunc['db_query']('', '
		SELECT id_theme, variable, value
		FROM {db_prefix}themes
		WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
			AND variable IN ({string:name}, {string:theme_dir})',
		array(
			'known_theme_list' => explode(',', $modSettings['knownThemes']),
			'default_theme' => 1,
			'name' => 'name',
			'theme_dir' => 'theme_dir',
		)
	);
	$theme_paths = array();
	while ($row = $smcFunc['db_fetch_assoc']($request))
		$theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
	$smcFunc['db_free_result']($request);

	// Get the package info...
	$packageInfo = getPackageInfo($context['filename']);

	if (!is_array($packageInfo))
		fatal_lang_error($packageInfo);

	$packageInfo['filename'] = $context['filename'];
	$context['package_name'] = isset($packageInfo['name']) ? $packageInfo['name'] : $context['filename'];

	// Set the type of extraction...
	$context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';

	// The mod isn't installed.... unless proven otherwise.
	$context['is_installed'] = false;

	// See if it is installed?
	$request = $smcFunc['db_query']('', '
		SELECT version, themes_installed, db_changes
		FROM {db_prefix}log_packages
		WHERE package_id = {string:current_package}
			AND install_state != {int:not_installed}
		ORDER BY time_installed DESC
		LIMIT 1',
		array(
			'not_installed'	=> 0,
			'current_package' => $packageInfo['id'],
		)
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$old_themes = explode(',', $row['themes_installed']);
		$old_version = $row['version'];
		$db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
	}
	$smcFunc['db_free_result']($request);

	$context['database_changes'] = array();
	if (isset($packageInfo['uninstall']['database']))
		$context['database_changes'][] = $txt['execute_database_changes'] . ' - ' . $packageInfo['uninstall']['database'];
	elseif (!empty($db_changes))
	{
		foreach ($db_changes as $change)
		{
			if (isset($change[2]) && isset($txt['package_db_' . $change[0]]))
				$context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1], $change[2]);
			elseif (isset($txt['package_db_' . $change[0]]))
				$context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1]);
			else
				$context['database_changes'][] = $change[0] . '-' . $change[1] . (isset($change[2]) ? '-' . $change[2] : '');
		}
	}

	// Uninstalling?
	if ($context['uninstalling'])
	{
		// Wait, it's not installed yet!
		if (!isset($old_version) && $context['uninstalling'])
		{
			deltree($packagesdir . '/temp');
			fatal_lang_error('package_cant_uninstall', false);
		}

		$actions = parsePackageInfo($packageInfo['xml'], true, 'uninstall');

		// Gadzooks!  There's no uninstaller at all!?
		if (empty($actions))
		{
			deltree($packagesdir . '/temp');
			fatal_lang_error('package_uninstall_cannot', false);
		}

		// Can't edit the custom themes it's edited if you're uninstalling, they must be removed.
		$context['themes_locked'] = true;

		// Only let them uninstall themes it was installed into.
		foreach ($theme_paths as $id => $data)
			if ($id != 1 && !in_array($id, $old_themes))
				unset($theme_paths[$id]);
	}
	elseif (isset($old_version) && $old_version != $packageInfo['version'])
	{
		// Look for an upgrade...
		$actions = parsePackageInfo($packageInfo['xml'], true, 'upgrade', $old_version);

		// There was no upgrade....
		if (empty($actions))
			$context['is_installed'] = true;
		else
		{
			// Otherwise they can only upgrade themes from the first time around.
			foreach ($theme_paths as $id => $data)
				if ($id != 1 && !in_array($id, $old_themes))
					unset($theme_paths[$id]);
		}
	}
	elseif (isset($old_version) && $old_version == $packageInfo['version'])
		$context['is_installed'] = true;

	if (!isset($old_version) || $context['is_installed'])
		$actions = parsePackageInfo($packageInfo['xml'], true, 'install');

	$context['actions'] = array();
	$context['ftp_needed'] = false;
	$context['has_failure'] = false;
	$chmod_files = array();

	// no actions found, return so we can display an error
	if (empty($actions))
		return;

	// This will hold data about anything that can be installed in other themes.
	$themeFinds = array(
		'candidates' => array(),
		'other_themes' => array(),
	);

	// Now prepare things for the template.
	foreach ($actions as $action)
	{
		// Not failed until proven otherwise.
		$failed = false;
		$thisAction = array();

		if ($action['type'] == 'chmod')
		{
			$chmod_files[] = $action['filename'];
			continue;
		}
		elseif ($action['type'] == 'readme' || $action['type'] == 'license')
		{
			$type = 'package_' . $action['type'];
			if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
				$context[$type] = $smcFunc['htmlspecialchars'](trim(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), "\n\r"));
			elseif (file_exists($action['filename']))
				$context[$type] = $smcFunc['htmlspecialchars'](trim(file_get_contents($action['filename']), "\n\r"));

			if (!empty($action['parse_bbc']))
			{
				require_once($sourcedir . '/Subs-Post.php');
				$context[$type] = preg_replace('~\[[/]?html\]~i', '', $context[$type]);
				preparsecode($context[$type]);
				$context[$type] = parse_bbc($context[$type]);
			}
			else
				$context[$type] = nl2br($context[$type]);

			continue;
		}
		// Don't show redirects.
		elseif ($action['type'] == 'redirect')
			continue;
		elseif ($action['type'] == 'error')
		{
			$context['has_failure'] = true;
			if (isset($action['error_msg']) && isset($action['error_var']))
				$context['failure_details'] = sprintf($txt['package_will_fail_' . $action['error_msg']], $action['error_var']);
			elseif (isset($action['error_msg']))
				$context['failure_details'] = isset($txt['package_will_fail_' . $action['error_msg']]) ? $txt['package_will_fail_' . $action['error_msg']] : $action['error_msg'];
		}
		elseif ($action['type'] == 'modification')
		{
			if (!file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
			{
				$context['has_failure'] = true;

				$context['actions'][] = array(
					'type' => $txt['execute_modification'],
					'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.'))),
					'description' => $txt['package_action_missing'],
					'failed' => true,
				);
			}
			else
			{

				if ($action['boardmod'])
					$mod_actions = parseBoardMod(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
				else
					$mod_actions = parseModification(@file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);

				if (count($mod_actions) == 1 && isset($mod_actions[0]) && $mod_actions[0]['type'] == 'error' && $mod_actions[0]['filename'] == '-')
					$mod_actions[0]['filename'] = $action['filename'];

				foreach ($mod_actions as $key => $mod_action)
				{
					// Lets get the last section of the file name.
					if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
						$actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
					elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
						$actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
					else
						$actual_filename = $key;

					if ($mod_action['type'] == 'opened')
						$failed = false;
					elseif ($mod_action['type'] == 'failure')
					{
						if (empty($mod_action['is_custom']))
							$context['has_failure'] = true;
						$failed = true;
					}
					elseif ($mod_action['type'] == 'chmod')
					{
						$chmod_files[] = $mod_action['filename'];
					}
					elseif ($mod_action['type'] == 'saved')
					{
						if (!empty($mod_action['is_custom']))
						{
							if (!isset($context['theme_actions'][$mod_action['is_custom']]))
								$context['theme_actions'][$mod_action['is_custom']] = array(
									'name' => $theme_paths[$mod_action['is_custom']]['name'],
									'actions' => array(),
									'has_failure' => $failed,
								);
							else
								$context['theme_actions'][$mod_action['is_custom']]['has_failure'] |= $failed;

							$context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
								'failed' => $failed,
							);
						}
						elseif (!isset($context['actions'][$actual_filename]))
						{
							$context['actions'][$actual_filename] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
								'failed' => $failed,
							);
						}
						else
						{
								$context['actions'][$actual_filename]['failed'] |= $failed;
								$context['actions'][$actual_filename]['description'] = $context['actions'][$actual_filename]['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'];
						}
					}
					elseif ($mod_action['type'] == 'skipping')
					{
						$context['actions'][$actual_filename] = array(
							'type' => $txt['execute_modification'],
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
							'description' => $txt['package_action_skipping']
						);
					}
					elseif ($mod_action['type'] == 'missing' && empty($mod_action['is_custom']))
					{
						$context['has_failure'] = true;
						$context['actions'][$actual_filename] = array(
							'type' => $txt['execute_modification'],
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
							'description' => $txt['package_action_missing'],
							'failed' => true,
						);
					}
					elseif ($mod_action['type'] == 'error')
						$context['actions'][$actual_filename] = array(
							'type' => $txt['execute_modification'],
							'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
							'description' => $txt['package_action_error'],
							'failed' => true,
						);
				}

				// We need to loop again just to get the operations down correctly.
				foreach ($mod_actions as $operation_key => $mod_action)
				{
					// Lets get the last section of the file name.
					if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
						$actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
					elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
						$actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
					else
						$actual_filename = $key;

					// We just need it for actual parse changes.
					if (!in_array($mod_action['type'], array('error', 'result', 'opened', 'saved', 'end', 'missing', 'skipping', 'chmod')))
					{
						if (empty($mod_action['is_custom']))
							$context['actions'][$actual_filename]['operations'][] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
								'position' => $mod_action['position'],
								'operation_key' => $operation_key,
								'filename' => $action['filename'],
								'is_boardmod' => $action['boardmod'],
								'failed' => $mod_action['failed'],
								'ignore_failure' => !empty($mod_action['ignore_failure']),
							);

						// Themes are under the saved type.
						if (isset($mod_action['is_custom']) && isset($context['theme_actions'][$mod_action['is_custom']]))
							$context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename]['operations'][] = array(
								'type' => $txt['execute_modification'],
								'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
								'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
								'position' => $mod_action['position'],
								'operation_key' => $operation_key,
								'filename' => $action['filename'],
								'is_boardmod' => $action['boardmod'],
								'failed' => $mod_action['failed'],
								'ignore_failure' => !empty($mod_action['ignore_failure']),
							);
					}
				}
			}
		}
		elseif ($action['type'] == 'code')
		{
			$thisAction = array(
				'type' => $txt['execute_code'],
				'action' => $smcFunc['htmlspecialchars']($action['filename']),
			);
		}
		elseif ($action['type'] == 'database')
		{
			$thisAction = array(
				'type' => $txt['execute_database_changes'],
				'action' => $smcFunc['htmlspecialchars']($action['filename']),
			);
		}
		elseif (in_array($action['type'], array('create-dir', 'create-file')))
		{
			$thisAction = array(
				'type' => $txt['package_create'] . ' ' . ($action['type'] == 'create-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
			);
		}
		elseif ($action['type'] == 'hook')
		{
			$action['description'] = !isset($action['hook'], $action['function']) ? $txt['package_action_failure'] : $txt['package_action_success'];

			if (!isset($action['hook'], $action['function']))
				$context['has_failure'] = true;

			$thisAction = array(
				'type' => $action['reverse'] ? $txt['execute_hook_remove'] : $txt['execute_hook_add'],
				'action' => sprintf($txt['execute_hook_action'],  $smcFunc['htmlspecialchars']($action['hook'])),
			);
		}
		elseif ($action['type'] == 'credits')
		{
			$thisAction = array(
				'type' => $txt['execute_credits_add'],
				'action' => sprintf($txt['execute_credits_action'],  $smcFunc['htmlspecialchars']($action['title'])),
			);
		}
		elseif ($action['type'] == 'requires')
		{
			$installed = false;
			$version = true;

			// package missing required values?
			if (!isset($action['id']))
				$context['has_failure'] = true;
			else
			{
				// See if this dependancy is installed
				$request = $smcFunc['db_query']('', '
					SELECT version
					FROM {db_prefix}log_packages
					WHERE package_id = {string:current_package}
						AND install_state != {int:not_installed}
					ORDER BY time_installed DESC
					LIMIT 1',
					array(
						'not_installed'	=> 0,
						'current_package' => $action['id'],
					)
				);
				$installed = ($smcFunc['db_num_rows']($request) !== 0);
				if ($installed)
					list ($version) = $smcFunc['db_fetch_row']($request);
				$smcFunc['db_free_result']($request);

				// do a version level check (if requested) in the most basic way
				$version = (isset($action['version']) ? $version == $action['version'] : true);
			}

			// Set success or failure information
			$action['description'] = ($installed && $version) ? $txt['package_action_success'] : $txt['package_action_failure'];
			$context['has_failure'] = !($installed && $version);

			$thisAction = array(
				'type' => $txt['package_requires'],
				'action' => $txt['package_check_for'] . ' ' . $action['id'] . (isset($action['version']) ? (' / ' . ($version ? $action['version'] : '<span class="error">' . $action['version'] . '</span>')) : ''),
			);
		}
		elseif (in_array($action['type'], array('require-dir', 'require-file')))
		{
			// Do this one...
			$thisAction = array(
				'type' => $txt['package_extract'] . ' ' . ($action['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
			);

			// Could this be theme related?
			if (!empty($action['unparsed_destination']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_destination'], $matches))
			{
				// Is the action already stated?
				$theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
				// If it's not auto do we think we have something we can act upon?
				if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
					$theme_action = '';
				// ... or if it's auto do we even want to do anything?
				elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
					$theme_action = '';

				// So, we still want to do something?
				if ($theme_action != '')
					$themeFinds['candidates'][] = $action;
				// Otherwise is this is going into another theme record it.
				elseif ($matches[1] == 'themes_dir')
					$themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_destination']), array('\\' => '/')) . '/' . basename($action['filename']));
			}
		}
		elseif (in_array($action['type'], array('move-dir', 'move-file')))
			$thisAction = array(
				'type' => $txt['package_move'] . ' ' . ($action['type'] == 'move-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['source'], array($boarddir => '.'))) . ' => ' . $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
			);
		elseif (in_array($action['type'], array('remove-dir', 'remove-file')))
		{
			$thisAction = array(
				'type' => $txt['package_delete'] . ' ' . ($action['type'] == 'remove-dir' ? $txt['package_tree'] : $txt['package_file']),
				'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.')))
			);

			// Could this be theme related?
			if (!empty($action['unparsed_filename']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_filename'], $matches))
			{

				// Is the action already stated?
				$theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
				$action['unparsed_destination'] = $action['unparsed_filename'];

				// If it's not auto do we think we have something we can act upon?
				if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
					$theme_action = '';
				// ... or if it's auto do we even want to do anything?
				elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
					$theme_action = '';

				// So, we still want to do something?
				if ($theme_action != '')
					$themeFinds['candidates'][] = $action;
				// Otherwise is this is going into another theme record it.
				elseif ($matches[1] == 'themes_dir')
					$themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_filename']), array('\\' => '/')) . '/' . basename($action['filename']));
			}
		}

		if (empty($thisAction))
			continue;

		if (!in_array($action['type'], array('hook', 'credits')))
		{
			if ($context['uninstalling'])
				$file = in_array($action['type'], array('remove-dir', 'remove-file')) ? $action['filename'] : $packagesdir . '/temp/' . $context['base_path'] . $action['filename'];
			else
				$file =  $packagesdir . '/temp/' . $context['base_path'] . $action['filename'];
		}

		if (isset($action['filename']) && !file_exists($file))
		{
			$context['has_failure'] = true;

			$thisAction += array(
				'description' => $txt['package_action_error'],
				'failed' => true,
			);
		}

		// @todo None given?
		if (empty($thisAction['description']))
			$thisAction['description'] = isset($action['description']) ? $action['description'] : '';

		$context['actions'][] = $thisAction;
	}

	// Have we got some things which we might want to do "multi-theme"?
	if (!empty($themeFinds['candidates']))
	{
		foreach ($themeFinds['candidates'] as $action_data)
		{
			// Get the part of the file we'll be dealing with.
			preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir)(\\|/)*(.+)*~i', $action_data['unparsed_destination'], $matches);

			if ($matches[1] == 'imagesdir')
				$path = '/' . basename($settings['default_images_url']);
			elseif ($matches[1] == 'languagedir' || $matches[1] == 'languages_dir')
				$path = '/languages';
			else
				$path = '';

			if (!empty($matches[3]))
				$path .= $matches[3];

			if (!$context['uninstalling'])
				$path .= '/' . basename($action_data['filename']);

			// Loop through each custom theme to note it's candidacy!
			foreach ($theme_paths as $id => $theme_data)
			{
				if (isset($theme_data['theme_dir']) && $id != 1)
				{
					$real_path = $theme_data['theme_dir'] . $path;

					// Confirm that we don't already have this dealt with by another entry.
					if (!in_array(strtolower(strtr($real_path, array('\\' => '/'))), $themeFinds['other_themes']))
					{
						// Check if we will need to chmod this.
						if (!mktree(dirname($real_path), false))
						{
							$temp = dirname($real_path);
							while (!file_exists($temp) && strlen($temp) > 1)
								$temp = dirname($temp);
							$chmod_files[] = $temp;
						}

						if ($action_data['type'] == 'require-dir' && !is_writable($real_path) && (file_exists($real_path) || !is_writable(dirname($real_path))))
							$chmod_files[] = $real_path;

						if (!isset($context['theme_actions'][$id]))
							$context['theme_actions'][$id] = array(
								'name' => $theme_data['name'],
								'actions' => array(),
							);

						if ($context['uninstalling'])
							$context['theme_actions'][$id]['actions'][] = array(
								'type' => $txt['package_delete'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
								'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
								'description' => '',
								'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['filename'], 'future' => $real_path, 'id' => $id))),
								'not_mod' => true,
							);
						else
							$context['theme_actions'][$id]['actions'][] = array(
								'type' => $txt['package_extract'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
								'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
								'description' => '',
								'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['destination'], 'future' => $real_path, 'id' => $id))),
								'not_mod' => true,
							);
					}
				}
			}
		}
	}

	// Trash the cache... which will also check permissions for us!
	package_flush_cache(true);

	if (file_exists($packagesdir . '/temp'))
		deltree($packagesdir . '/temp');

	if (!empty($chmod_files))
	{
		$ftp_status = create_chmod_control($chmod_files);
		$context['ftp_needed'] = !empty($ftp_status['files']['notwritable']) && !empty($context['package_ftp']);
	}

	$context['post_url'] = $scripturl .'?action=admin;area=packages;sa=' . ($context['uninstalling'] ? 'uninstall' : 'install') . ($context['ftp_needed'] ? '' : '2') . ';package=' . $context['filename'] . ';pid=' . $context['install_id'];
	checkSubmitOnce('register');
}

/**
 * Apply another type of (avatar, language, etc.) package.
 */
function PackageInstall()
{
	global $boarddir, $txt, $context, $boardurl, $scripturl, $sourcedir, $packagesdir, $modSettings;
	global $user_info, $smcFunc;

	// Make sure we don't install this mod twice.
	checkSubmitOnce('check');
	checkSession();

	// If there's no file, what are we installing?
	if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
		redirectexit('action=admin;area=packages');
	$context['filename'] = $_REQUEST['package'];

	// If this is an uninstall, we'll have an id.
	$context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;

	require_once($sourcedir . '/Subs-Package.php');

	// @todo Perhaps do it in steps, if necessary?

	$context['uninstalling'] = $_REQUEST['sa'] == 'uninstall2';

	// Set up the linktree for other.
	$context['linktree'][count($context['linktree']) - 1] = array(
		'url' => $scripturl . '?action=admin;area=packages;sa=browse',
		'name' => $context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']
	);
	$context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']);

	$context['sub_template'] = 'extract_package';

	if (!file_exists($packagesdir . '/' . $context['filename']))
		fatal_lang_error('package_no_file', false);

	// Load up the package FTP information?
	create_chmod_control(array(), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package']));

	// Make sure temp directory exists and is empty!
	if (file_exists($packagesdir . '/temp'))
		deltree($packagesdir . '/temp', false);
	else
		mktree($packagesdir . '/temp', 0777);

	// Let the unpacker do the work.
	if (is_file($packagesdir . '/' . $context['filename']))
	{
		$context['extracted_files'] = read_tgz_file($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');

		if (!file_exists($packagesdir . '/temp/package-info.xml'))
			foreach ($context['extracted_files'] as $file)
				if (basename($file['filename']) == 'package-info.xml')
				{
					$context['base_path'] = dirname($file['filename']) . '/';
					break;
				}

		if (!isset($context['base_path']))
			$context['base_path'] = '';
	}
	elseif (is_dir($packagesdir . '/' . $context['filename']))
	{
		copytree($packagesdir . '/' . $context['filename'], $packagesdir . '/temp');
		$context['extracted_files'] = listtree($packagesdir . '/temp');
		$context['base_path'] = '';
	}
	else
		fatal_lang_error('no_access', false);

	// Are we installing this into any custom themes?
	$custom_themes = array(1);
	$known_themes = explode(',', $modSettings['knownThemes']);
	if (!empty($_POST['custom_theme']))
	{
		foreach ($_POST['custom_theme'] as $tid)
			if (in_array($tid, $known_themes))
				$custom_themes[] = (int) $tid;
	}

	// Now load up the paths of the themes that we need to know about.
	$request = $smcFunc['db_query']('', '
		SELECT id_theme, variable, value
		FROM {db_prefix}themes
		WHERE id_theme IN ({array_int:custom_themes})
			AND variable IN ({string:name}, {string:theme_dir})',
		array(
			'custom_themes' => $custom_themes,
			'name' => 'name',
			'theme_dir' => 'theme_dir',
		)
	);
	$theme_paths = array();
	$themes_installed = array(1);
	while ($row = $smcFunc['db_fetch_assoc']($request))
		$theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
	$smcFunc['db_free_result']($request);

	// Are there any theme copying that we want to take place?
	$context['theme_copies'] = array(
		'require-file' => array(),
		'require-dir' => array(),
	);
	if (!empty($_POST['theme_changes']))
	{
		foreach ($_POST['theme_changes'] as $change)
		{
			if (empty($change))
				continue;
			$theme_data = unserialize(base64_decode($change));
			if (empty($theme_data['type']))
				continue;

			$themes_installed[] = $theme_data['id'];
			$context['theme_copies'][$theme_data['type']][$theme_data['orig']][] = $theme_data['future'];
		}
	}

	// Get the package info...
	$packageInfo = getPackageInfo($context['filename']);
	if (!is_array($packageInfo))
		fatal_lang_error($packageInfo);

	$packageInfo['filename'] = $context['filename'];

	// Set the type of extraction...
	$context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';

	// Create a backup file to roll back to! (but if they do this more than once, don't run it a zillion times.)
	if (!empty($modSettings['package_make_full_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['filename'] . ($context['uninstalling'] ? '$$' : '$')))
	{
		$_SESSION['last_backup_for'] = $context['filename'] . ($context['uninstalling'] ? '$$' : '$');
		$result = package_create_backup(($context['uninstalling'] ? 'backup_' : 'before_') . strtok($context['filename'], '.'));
		if (!$result)
			fatal_lang_error('could_not_package_backup', false);
	}

	// The mod isn't installed.... unless proven otherwise.
	$context['is_installed'] = false;

	// Is it actually installed?
	$request = $smcFunc['db_query']('', '
		SELECT version, themes_installed, db_changes
		FROM {db_prefix}log_packages
		WHERE package_id = {string:current_package}
			AND install_state != {int:not_installed}
		ORDER BY time_installed DESC
		LIMIT 1',
		array(
			'not_installed'	=> 0,
			'current_package' => $packageInfo['id'],
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$old_themes = explode(',', $row['themes_installed']);
		$old_version = $row['version'];
		$db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
	}
	$smcFunc['db_free_result']($request);

	// Wait, it's not installed yet!
	// @todo Replace with a better error message!
	if (!isset($old_version) && $context['uninstalling'])
	{
		deltree($packagesdir . '/temp');
		fatal_error('Hacker?', false);
	}
	// Uninstalling?
	elseif ($context['uninstalling'])
	{
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'uninstall');

		// Gadzooks!  There's no uninstaller at all!?
		if (empty($install_log))
			fatal_lang_error('package_uninstall_cannot', false);

		// They can only uninstall from what it was originally installed into.
		foreach ($theme_paths as $id => $data)
			if ($id != 1 && !in_array($id, $old_themes))
				unset($theme_paths[$id]);
	}
	elseif (isset($old_version) && $old_version != $packageInfo['version'])
	{
		// Look for an upgrade...
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'upgrade', $old_version);

		// There was no upgrade....
		if (empty($install_log))
			$context['is_installed'] = true;
		else
		{
			// Upgrade previous themes only!
			foreach ($theme_paths as $id => $data)
				if ($id != 1 && !in_array($id, $old_themes))
					unset($theme_paths[$id]);
		}
	}
	elseif (isset($old_version) && $old_version == $packageInfo['version'])
		$context['is_installed'] = true;

	if (!isset($old_version) || $context['is_installed'])
		$install_log = parsePackageInfo($packageInfo['xml'], false, 'install');

	$context['install_finished'] = false;

	// @todo Make a log of any errors that occurred and output them?

	if (!empty($install_log))
	{
		$failed_steps = array();
		$failed_count = 0;

		foreach ($install_log as $action)
		{
			$failed_count++;

			if ($action['type'] == 'modification' && !empty($action['filename']))
			{
				if ($action['boardmod'])
					$mod_actions = parseBoardMod(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
				else
					$mod_actions = parseModification(file_get_contents($packagesdir . '/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);

				// Any errors worth noting?
				foreach ($mod_actions as $key => $action)
				{
					if ($action['type'] == 'failure')
						$failed_steps[] = array(
							'file' => $action['filename'],
							'large_step' => $failed_count,
							'sub_step' => $key,
							'theme' => 1,
						);

					// Gather the themes we installed into.
					if (!empty($action['is_custom']))
						$themes_installed[] = $action['is_custom'];
				}
			}
			elseif ($action['type'] == 'code' && !empty($action['filename']))
			{
				// This is just here as reference for what is available.
				global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $forum_version, $smcFunc;

				// Now include the file and be done with it ;).
				if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
					require($packagesdir . '/temp/' . $context['base_path'] . $action['filename']);
			}
			elseif ($action['type'] == 'credits')
			{
				// Time to build the billboard
				$credits_tag = array(
					'url' => $action['url'],
					'license' => $action['license'],
					'licenseurl' => $action['licenseurl'],
					'copyright' => $action['copyright'],
					'title' => $action['title'],
				);
			}
			elseif ($action['type'] == 'hook' && isset($action['hook'], $action['function']))
			{
				if ($action['reverse'])
					remove_integration_function($action['hook'], $action['function'], true, $action['include_file'], $action['object']);
				else
					add_integration_function($action['hook'], $action['function'], true, $action['include_file'], $action['object']);
			}
			// Only do the database changes on uninstall if requested.
			elseif ($action['type'] == 'database' && !empty($action['filename']) && (!$context['uninstalling'] || !empty($_POST['do_db_changes'])))
			{
				// These can also be there for database changes.
				global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $forum_version, $smcFunc;
				global $db_package_log;

				// We'll likely want the package specific database functionality!
				db_extend('packages');

				// Let the file work its magic ;)
				if (file_exists($packagesdir . '/temp/' . $context['base_path'] . $action['filename']))
					require($packagesdir . '/temp/' . $context['base_path'] . $action['filename']);
			}
			// Handle a redirect...
			elseif ($action['type'] == 'redirect' && !empty($action['redirect_url']))
			{
				$context['redirect_url'] = $action['redirect_url'];
				$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']);
				$context['redirect_timeout'] = $action['redirect_timeout'];

				// Parse out a couple of common urls.
				$urls = array(
					'$boardurl' => $boardurl,
					'$scripturl' => $scripturl,
					'$session_var' => $context['session_var'],
					'$session_id' => $context['session_id'],
				);

				$context['redirect_url'] = strtr($context['redirect_url'], $urls);
			}
		}

		package_flush_cache();

		// See if this is already installed, and change it's state as required.
		$request = $smcFunc['db_query']('', '
			SELECT package_id, install_state, db_changes
			FROM {db_prefix}log_packages
			WHERE install_state != {int:not_installed}
				AND package_id = {string:current_package}
				' . ($context['install_id'] ? ' AND id_install = {int:install_id} ' : '') . '
			ORDER BY time_installed DESC
			LIMIT 1',
{'fraction_non_alphanumeric': 0.2096129652926811, 'fraction_numerical': 0.002343422383383902, 'mean_word_length': 4.365916611515552, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 361, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 20}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6095537', 'n_tokens_mistral': 30911, 'n_tokens_neox': 26437, 'n_words': 5124}