<?php
/**
 * SMF Arcade
 *
 * @package SMF Arcade
 * @version 2.57
 * @license https://web-develop.ca/index.php?page=arcade_license_BSD2 BSD 2
 */

if (!defined('SMF'))
	die('Hacking attempt...');

function list_getNumGamesInstalled($filter)
{
	global $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT COUNT(*)
		FROM {db_prefix}arcade_files AS f
			INNER JOIN {db_prefix}arcade_games AS g ON (g.id_game = f.id_game)
		WHERE (status = 1 OR status = 2)' . ($filter == 'disabled' || $filter == 'enabled' ? '
			AND g.enabled = {int:enabled}' : ''),
		array(
			'enabled' => $filter == 'disabled' ? 0 : 1,
		)
	);

	list ($count) = $smcFunc['db_fetch_row']($request);
	$smcFunc['db_free_result']($request);

	return $count;
}

function list_getGamesInstalled($start, $items_per_page, $sort, $filter)
{
	global $smcFunc, $scripturl, $context, $txt;

	$request = $smcFunc['db_query']('', '
		SELECT f.id_file, g.game_name, g.internal_name, f.status, g.id_game, cat.id_cat, cat.cat_name
		FROM {db_prefix}arcade_files AS f
			INNER JOIN {db_prefix}arcade_games AS g ON (g.id_game = f.id_game)
			LEFT JOIN {db_prefix}arcade_categories AS cat ON (cat.id_cat = g.id_cat)
		WHERE (f.status = 1 OR f.status = 2)' . ($filter == 'disabled' || $filter == 'enabled' ? '
			AND g.enabled = {int:enabled}' : '') . '
		ORDER BY {raw:sort}
		LIMIT {int:start}, {int:games_per_page}',
		array(
			'start' => $start,
			'games_per_page' => $items_per_page,
			'sort' => $sort,
			'enabled' => $filter == 'disabled' ? 0 : 1,
		)
	);

	$return = array();

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$return[] = array(
			'id' => $row['id_game'],
			'id_file' => $row['id_file'],
			'name' => $row['game_name'],
			'href' => $scripturl . '?action=admin;area=managegames;sa=edit;game=' . $row['id_game'],
			'category' => array(
				'id' => $row['id_cat'],
				'name' => $row['cat_name'],
			),
			'error' => $row['status'] != 1 ? $txt['arcade_missing_files'] : false,
		);
	$smcFunc['db_free_result']($request);

	return $return;
}

function list_getNumGamesInstall()
{
	global $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT COUNT(*)
		FROM {db_prefix}arcade_files AS f
		WHERE status = 10',
		array(
		)
	);

	list ($count) = $smcFunc['db_fetch_row']($request);
	$smcFunc['db_free_result']($request);

	return $count;
}

function list_getGamesInstall($start, $items_per_page, $sort)
{
	global $smcFunc, $scripturl, $context, $txt;

	$request = $smcFunc['db_query']('', '
		SELECT f.id_file, f.game_name, f.status
		FROM {db_prefix}arcade_files AS f
		WHERE status = 10
		ORDER BY {raw:sort}
		LIMIT {int:start}, {int:games_per_page}',
		array(
			'start' => $start,
			'games_per_page' => $items_per_page,
			'sort' => $sort,
		)
	);

	$return = array();

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$return[] = array(
			'id_file' => $row['id_file'],
			'name' => $row['game_name'],
			'href' => $scripturl . '?action=admin;area=managegames;sa=install2;file=' . $row['id_file'],
		);
	$smcFunc['db_free_result']($request);

	return $return;
}

// Creates new game. Returns false on error and id of game on success
function createGame($game)
{
	global $scripturl, $txt, $db_prefix, $user_info, $smcFunc, $modSettings;

	$smcFunc['db_insert']('ignore',
		'{db_prefix}arcade_games',
		array(
			'id_cat' => 'int',
			'internal_name' => 'string',
			'game_name' => 'string',
			'submit_system' => 'string',
			'description' => 'string',
			'help' => 'string',
			'thumbnail' => 'string',
			'thumbnail_small' => 'string',
			'enabled' => 'int',
			'num_rates' => 'int',
			'num_plays' => 'int',
			'game_file' => 'string',
			'game_directory' => 'string',
			'extra_data' => 'string',
		),
		array(
			$game['category'],
			$game['internal_name'],
			$game['name'],
			$game['submit_system'],
			$game['description'],
			$game['help'],
			!empty($game['thumbnail']) ? arcadeSanitizeImg($game['thumbnail']) : '',
			!empty($game['thumbnail_small']) ? arcadeSanitizeImg($game['thumbnail_small']) : '',
			1,
			0,
			0,
			$game['game_file'],
			$game['game_directory'],
			!empty($game['extra_data']) ? serialize($game['extra_data']) : '',
		),
		array('id_game')
	);

	$request = $smcFunc['db_query']('', '
		SELECT id_game, internal_name
		FROM {db_prefix}arcade_games
		WHERE internal_name = {string:name}',
		array('name' => $game['internal_name'])
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$internalId = $row['id_game'];

	$smcFunc['db_free_result']($request);

	$id_game = !empty($internalId) ? (int)$internalId : 0;

	if (empty($id_game))
		return false;

	// Post message with game info if enabled
	$modSettings['arcadeEnablePosting'] = !empty($modSettings['arcadeEnablePosting']) ? $modSettings['arcadeEnablePosting'] : false;
	if (!empty($modSettings['arcadeEnablePosting']) && !empty($modSettings['gamesBoard']))
	{
		$gameid = $id_game;
		postArcadeGames($game, $gameid);
	}

	// Update does the rest...
	//updateGame($id_game, $game);
	unset($game['internal_name'], $game['name'], $game['submit_system'], $game['game_file'], $game['game_directory']);

	logAction('arcade_install_game', array('game' => $id_game));
	return $id_game;
}

function deleteGame($id, $remove_files)
{
	global $scripturl, $txt, $db_prefix, $user_info, $smcFunc, $modSettings;

	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}arcade_scores
		WHERE id_game = {int:game}',
		array(
			'game' => $id,
		)
	);
	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}arcade_favorite
		WHERE id_game = {int:game}',
		array(
			'game' => $id,
		)
	);
	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}arcade_rates
		WHERE id_game = {int:game}',
		array(
			'game' => $id,
		)
	);

	if ($remove_files)
		$smcFunc['db_query']('', '
			DELETE FROM {db_prefix}arcade_files
			WHERE id_game = {int:game}',
			array(
				'game' => $id,
			)
		);
	else
		$smcFunc['db_query']('', '
			UPDATE {db_prefix}arcade_files
			SET id_game = 0, status = 10
			WHERE id_game = {int:game}',
			array(
				'game' => $id,
			)
		);

	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}arcade_games
		WHERE id_game = {int:game}',
		array(
			'game' => $id,
		)
	);

	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}arcade_pdl2
		WHERE pdl_gameid = {int:game}',
		array(
			'game' => $id,
		)
	);

	logAction('arcade_delete_game', array('game' => $id));

	return true;
}

// Install games by game cache ids
function installGames($games, $set_category, $move_games = false)
{
	global $scripturl, $txt, $db_prefix, $modSettings, $context, $sourcedir, $smcFunc, $boarddir, $settings;

	loadClassFile('Class-Package.php');

	// SWF Reader will be needed
	require_once($sourcedir . '/SWFReader.php');
	list($swf, $masterGameinfo, $status, $directories, $modSettings['gamesDirectory']) = array(new SWFReader(), array(), array(), array(), str_replace('\\', '/', $modSettings['gamesDirectory']));
	$modSettings['gamesDirectory'] = rtrim($modSettings['gamesDirectory'], '/');
	$set_category = !empty($set_category) ? $set_category : 0;

	$request = $smcFunc['db_query']('', '
		SELECT game_directory
		FROM {db_prefix}arcade_games
		WHERE id_game > 0',
		array(
		)
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$directories[] = !empty($row['game_directory']) ? $row['game_directory'] : '';
	$smcFunc['db_free_result']($request);

	$request = $smcFunc['db_query']('', '
		SELECT f.id_file, f.game_name, f.status, f.game_file, f.game_directory, f.submit_system
		FROM {db_prefix}arcade_files AS f
		WHERE id_file IN ({array_int:games})
			AND f.status = 10',
		array(
			'games' => $games,
		)
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		unset($game, $gameinfo, $gameOptions, $masterGameinfo, $skip, $html53);
		list($errors, $failed, $moveFail, $exists, $masterGameinfo, $gameinfo, $game, $numb) = array(array(), true, false, false, array(), array(), array(), 0);
		$row['game_directory'] = (!empty($row['game_directory']) ? trim($row['game_directory'], '/') : '');
		$pop = explode('.', $row['game_file']);
		$dirs = !empty($row['game_directory']) ? str_replace('\\', '/', $row['game_directory']) : '';
		$allDirs = explode('/', $dirs);
		$countDirs = count($allDirs)-1;
		$checkz = substr($row['game_file'], -10) == 'index.html' ? 9 : (substr($row['game_file'], -9) == 'index.php' ? 8 : 0);
		$filename = $checkz && strlen($row['game_file']) > $checkz ? basename($dirs) : substr($row['game_file'], 0, -strlen('.' . end($pop)));
		$gamePath = $modSettings['gamesDirectory'] . '/' . (!empty($row['game_directory']) ? $row['game_directory'] . '/' . trim($filename, '/') : trim($filename, '/'));
		$gamePathProper = $modSettings['gamesDirectory'] . '/' . (!empty($row['game_directory']) ? str_replace(' ', '_', $row['game_directory']) . '/' . trim($filename, '/') : trim($filename, '/'));

		/*
		if ($gamePath != $gamePathProper && file_exists($gamepath))
		{
			die($row['game_directory']);
			@rename($gamepath, $gamePathProper);
			$gamePath = $gamePathProper;

			if (!file_exists($gamepath))
				fatal_lang_error('arcade_file_non_read', false);
		}
		*/
		// sanitize some stuff
		$mainFile = substr($row['game_file'], 0, (strlen ($row['game_file'])) - (strlen (strrchr($row['game_file'],'.'))));
		$directory = $modSettings['gamesDirectory'] . (!empty($row['game_directory']) ? '/' . $row['game_directory'] : '');
		$iname = basename($dirs);
		$iname = stripos($iname, 'gamepack') === false && stripos($iname, 'gamespack') === false ? $iname : $mainFile;
		$internal_name = !empty($iname) && $iname != "." && $iname != ".." && !empty($checkz) ? $iname : $mainFile;
		$saveType = !empty($row['submit_system']) ? $row['submit_system'] : '';

		//$internal_name = $checkz && strlen($row['game_file']) > $checkz ? trim($dirs, '/') : substr($row['game_file'], 0, -strlen('.' . end($pop)));

		// change internal name if a like one exists
		$internals = arcadeInternalName($internal_name);
		while(in_array($internal_name, $internals))
		{
			$numb++;
			$internal_name = $numb > 1 ? substr($internal_name, 0, -1) . (string)$numb : $internal_name . (string)$numb;
		}

		// Search for gamedata
		if (is_dir($directory))
			chdir($directory);

		if (basename(dirname($directory)) !== basename($modSettings['gamesDirectory']) && file_exists(dirname($directory) . '/master-info.xml'))
		{
			$masterGameinfo = array();
			$masterGameinfo = readGameInfo(dirname($directory) . '/master-info.xml');

			if (!isset($gameinfo['submit']))
				unset($gameinfo);
		}

		if (file_exists($directory . '/game-info.xml'))
		{
			$gameinfo = readGameInfo($directory . '/game-info.xml');
			if (!isset($gameinfo['id']))
				unset($gameinfo);
		}
		elseif (file_exists($directory . '/' . $internal_name . '-game-info.xml'))
		{
			$gameinfo = readGameInfo($directory . '/' . $internal_name . '-game-info.xml');

			if (!isset($gameinfo['id']))
				unset($gameinfo);
		}

		foreach ($masterGameinfo as $key => $masterSetting)
			if (!empty($masterGameinfo[$key]))
				$gameinfo[$key] = $masterGameinfo[$key];

		$thumbnail = glob($internal_name . '1.{png,gif,jpg}', GLOB_BRACE);
		if (empty($thumbnail))
			$thumbnail = glob($internal_name . '.{png,gif,jpg}', GLOB_BRACE);

		$thumbnailSmall = glob($internal_name . '2.{png,gif,jpg}', GLOB_BRACE);
		$thumbnail = empty($thumbnail) ? '' : $thumbnail;
		$thumbnailSmall = empty($thumbnailSmall) ? '' : $thumbnailSmall;
		$gameinfo['thumbnail'] = empty($gameinfo['thumbnail']) ? $thumbnail : $gameinfo['thumbnail'];
		$gameinfo['thumbnail-small'] = empty($gameinfo['thumbnail-small']) ? $thumbnailSmall : $gameinfo['thumbnail-small'];
		$gameinfo['help'] = empty($gameinfo['help']) ? '' : $gameinfo['help'];

		$game = array(
			'id_file' => $row['id_file'],
			'name' => $row['game_name'],
			'directory' => $row['game_directory'],
			'file' => $row['game_file'],
			'internal_name' => str_replace(array('/', '\\'), array('', ''), trim($internal_name, '.')),
			'thumbnail' => !empty($thumbnail[0]) ? $thumbnail[0] : !empty($gameinfo['thumbnail']) ? $gameinfo['thumbnail'] : '',
			'thumbnail_small' => !empty($thumbnailSmall[0]) ? $thumbnailSmall[0] : !empty($gameinfo['thumbnail-small']) ? $gameinfo['thumbnail-small'] : '',
			'extra_data' => array(
				'width' => !empty($gameinfo['flash']['width']) && is_numeric($gameinfo['flash']['width']) ? $gameinfo['flash']['width'] : '',
				'height' => !empty($gameinfo['flash']['height']) && is_numeric($gameinfo['flash']['height']) ? $gameinfo['flash']['height'] : '',
				'flash_version' => !empty($gameinfo['flash']['version']) && is_numeric($gameinfo['flash']['version']) ? $gameinfo['flash']['version'] : 0,
				'type' => !empty($gameinfo['flash']['type']) ? ArcadeSpecialChars($gameinfo['flash']['type'], 'name') : '',
				'background_color' => !empty($gameinfo['flash']['bgcolor']) && strlen($gameinfo['flash']['bgcolor']) == 6 ? array(
					hexdec(mb_substr($gameinfo['flash']['bgcolor'], 0, 2)),
					hexdec(mb_substr($gameinfo['flash']['bgcolor'], 2, 2)),
					hexdec(mb_substr($gameinfo['flash']['bgcolor'], 4, 2))
				) : array(
					hexdec('00'),
					hexdec('00'),
					hexdec('00')
				),
			),
			'help' => isset($gameinfo['help']) ? $gameinfo['help'] : '',
			'description' => isset($gameinfo['description']) ? $gameinfo['description'] : '',
			'submit_system' => $saveType,
		);

		unset($thumbnail, $thumbnailSmall);

		// Get information from flash
		if (mb_substr($row['game_file'], -4) == '.swf')
		{
			if (file_exists($directory . '/' . $row['game_file']))
			{
				$swf->open($directory . '/' . $row['game_file']);

				// Add possible flash read values
				if (!$swf->error)
				{
					$gameinfo['flash']['version'] = $swf->header['version'];
					$gameinfo['flash']['bgcolor'] = empty($game['extra_data']['background_color']) ? $swf->header['background'] : $game['extra_data']['background_color'];
					$gameinfo['flash']['width'] = empty($game['extra_data']['width']) ? $swf->header['width'] : $game['extra_data']['width'];
					$gameinfo['flash']['height'] = empty($game['extra_data']['height']) ? $swf->header['height'] : $game['extra_data']['height'];
					$gameinfo['flash']['type'] = empty($game['extra_data']['type']) ? '' : $game['extra_data']['type'];
				}

				$swf->close();
			}

			if (!empty($gameinfo['flash']['bgcolor']) && is_array($gameinfo['flash']['bgcolor']))
				$gameinfo['flash']['bgcolor'] = implode($gameinfo['flash']['bgcolor']);
			if (!empty($gameinfo['flash']['bgcolor']) && strlen($gameinfo['flash']['bgcolor']) == 3)
				$gameinfo['flash']['bgcolor'] = $gameinfo['flash']['bgcolor'] . $gameinfo['flash']['bgcolor'];

			if (isset($gameinfo['flash']))
			{
				if (!empty($gameinfo['flash']['width']) && is_numeric($gameinfo['flash']['width']))
					$game['extra_data']['width'] = (int)$gameinfo['flash']['width'];
				if (!empty($gameinfo['flash']['height']) && is_numeric($gameinfo['flash']['height']))
					$game['extra_data']['height'] = (int)$gameinfo['flash']['height'];
				if (!empty($gameinfo['flash']['version']) && is_numeric($gameinfo['flash']['version']))
					$game['extra_data']['flash_version'] = (int)$gameinfo['flash']['version'];
				if (!empty($gameinfo['flash']['type']))
					$game['extra_data']['type'] = ArcadeSpecialChars($gameinfo['flash']['type'], 'name');
				if (!empty($gameinfo['flash']['bgcolor']) && strlen($gameinfo['flash']['bgcolor']) == 3)
					$gameinfo['flash']['bgcolor'] = $gameinfo['flash']['bgcolor'] . $gameinfo['flash']['bgcolor'];
				if (!empty($gameinfo['flash']['bgcolor']) && strlen($gameinfo['flash']['bgcolor']) == 6)
				{
					$game['extra_data']['background_color'] = array(
						hexdec(mb_substr($gameinfo['flash']['bgcolor'], 0, 2)),
						hexdec(mb_substr($gameinfo['flash']['bgcolor'], 2, 2)),
						hexdec(mb_substr($gameinfo['flash']['bgcolor'], 4, 2))
					);
				}
				else
				{
					$game['extra_data']['background_color'] = array(
						hexdec('00'),
						hexdec('00'),
						hexdec('00')
					);
				}
			}
		}

		// Detect submit system
		if (empty($row['submit_system']))
		{
			if (isset($gameinfo['submit']))
				$row['submit_system'] = $gameinfo['submit'];
			elseif (mb_substr($row['game_file'], -5) == '.html')
				$row['submit_system'] = 'html5';
			elseif (mb_substr($row['game_file'], -3) == 'php')
				$row['submit_system'] = 'custom_game';
			elseif (mb_substr($row['game_file'], -3) == 'xap')
				$row['submit_system'] = 'silver';
			elseif (file_exists($boarddir . '/arcade/gamedata/' . $internal_name . '/v32game.txt') || file_exists($boarddir . '/arcade/gamedata/' . $mainFile . '/v32game.txt'))
				$row['submit_system'] = 'ibp32';
			elseif (file_exists($boarddir . '/arcade/gamedata/' . $internal_name . '/v3game.txt') || file_exists($boarddir . '/arcade/gamedata/' . $mainFile . '/v3game.txt'))
				$row['submit_system'] = 'ibp3';
			elseif (file_exists($directory . '/' . $internal_name . '.ini') || file_exists($directory . '/' . $mainFile . '.ini'))
				$row['submit_system'] = 'pnflash';
			elseif (file_exists($directory . '/' . $internal_name . '.php'))
			{
				$file = file_get_contents($directory . '/' . $internal_name . '.php');

				list($row['submit_system'], $row['game_file']) = checkArcadeHtmlGameFiles($directory, $internal_name);
				$game['file'] = $row['game_file'];
				$game['submit_system'] = $row['submit_system'];
				if (strpos(str_replace(' ', '', $file), '$config=array(') === false && $row['submit_system'] == 'ibp')
					$row['submit_system'] = 'custom_game';
				elseif ($row['submit_system'] == 'html5')
					$skip = $row['game_file'];

				unset($file);
			}
			elseif (file_exists($directory . '/' . $mainFile . '.php'))
			{
				$file = file_get_contents($directory . '/' . $mainFile . '.php');
				list($row['submit_system'], $row['game_file']) = checkArcadeHtmlGameFiles($directory, $internal_name);
				$game['file'] = $row['game_file'];
				$game['submit_system'] = $row['submit_system'];
				$game['submit'] = $row['submit_system'];
				if (strpos(str_replace(' ', '', $file), '$config=array(') === false && $row['submit_system'] == 'ibp')
					$row['submit_system'] = 'custom_game';
				elseif ($row['submit_system'] == 'html5')
					$skip = $row['game_file'];

				unset($file);
			}
			elseif (file_exists($directory . '/' . 'size.txt') && mb_substr($row['game_file'], -3) == 'swf')
				$row['submit_system'] = 'phpbb';
			elseif (!empty($saveType) && in_array($saveType, array('v1game', 'v2game', 'v3arcade', 'phpbb', 'mochi', 'custom_game', 'ibp', 'ibp3', 'html5', 'html52', 'html53')))
				$row['submit_system'] = $saveType;
			else
				$row['submit_system'] = 'v1game';
		}

		//check for PHP-Quick-Arcade or Origon HTML5 submit type
		if ($row['submit_system'] == 'custom_game' || strpos($row['submit_system'], 'html5') !== false)
		{
			if (empty($skip))
			{
				$fileX = file_exists($directory . '/gamedata/' . $internal_name . '/index.html') ? $directory . '/gamedata/' . $internal_name . '/index.html' : '';
				$fileX = !$fileX && file_exists($directory . '/gamedata/' . $internal_name . '/' . $internal_name . '.html') ? $directory . '/gamedata/' . $internal_name . '/' . $internal_name . '.html' : $fileX;
				//$fileX = !$fileX && file_exists($directory . '/' . $internal_name . '.html') ? $directory . '/' . $internal_name . '.html' : $fileX;

				if ($fileX)
				{
					$infoFile = false;
					if(file_exists($directory . '/' . $internal_name . '.php'))
					{
						$gameinfo = readPhpGameInfo($directory, $internal_name);
						$infoFile = true;
					}
					elseif (file_exists($directory . '/game-info.xml'))
					{
						$gameinfo = readGameInfo($directory . '/game-info.xml');
						$infoFile = true;
					}
					elseif (file_exists($directory . '/' . $internal_name . '_config.ini'))
					{
						$txt_file = file_get_contents($directory . '/' . $internal_name . '_config.ini');
						$iniInfo = explode("\n", preg_replace('~\r\n?~', "\n", $txt_file));
						$num = 0;
						$gameinfo['flash'] = array();
						$ini = array('name', 'internal', 'width', 'height', 'cheat_check', 'scoring', 'description', 'help', 'bgcolor', 'ignore', 'ignore', 'ignore', 'ignore');

						if (!empty($iniInfo) && is_array($iniInfo))
						{
							foreach ($iniInfo as $info)
							{
								foreach (array('nom', 'variable', 'largeur', 'hauteur', 'anti_triche', 'highscore_type', 'description', 'controle', 'bgcolor', 'nbdecimal', 'size', 'fps', 'jeuxhtml5') as $var)
								{
									if (strpos($info, $var) !== false && $ini[$num] != 'ignore')
									{
										$info = str_replace(array($var, '='), array('', ''), $info);
										$info = str_replace(array("'", '"'), array('', ''), $info);
										$info = trim($info);
										if ($var == 'bgcolor')
										{
											if (strlen($info) == 6)
											{
												$gameinfo['flash']['background_color'] = array(
													hexdec(mb_substr($info, 0, 2)),
													hexdec(mb_substr($info, 2, 2)),
													hexdec(mb_substr($info, 4, 2))
												);
											}
											else
											{
												$gameinfo['flash']['background_color'] = array(
													hexdec('00'),
													hexdec('00'),
													hexdec('00')
												);
											}
										}
										elseif ($var == 'largeur')
											$gameinfo['flash']['width'] = $info;
										elseif ($var == 'hauteur')
											$gameinfo['flash']['height'] = $info;
										elseif($var == 'controle')
										{
											$helpArray = array($txt['arcade_game_control_mouse_key'], $txt['arcade_game_control_mouse'], $txt['arcade_game_control_key']);
											$info = floatval($info);
											$gameinfo['help']  = $info>-1 && $info<3 ? $helpArray[$info] : '';
										}
										else
											$gameinfo[$ini[$num]] = $info;

										$num++;
									}
								}
							}
						}

						$gameinfo['submit'] = 'html52';
						$game['submit_system'] = 'html52';
						$game['file'] = $internal_name . '.html';
						$row['game_file'] = $game['file'];
						$infoFile = true;
						$html53 = true;
					}

					if (!empty($infoFile))
					{
						$game['help'] = isset($gameinfo['help']) ? $gameinfo['help'] : '';
						$game['description'] = isset($gameinfo['description']) ? $gameinfo['description'] : '';
						if (isset($gameinfo['flash']))
						{
							if (!empty($gameinfo['flash']['width']) && is_numeric($gameinfo['flash']['width']))
								$game['extra_data']['width'] = (int)$gameinfo['flash']['width'];
							if (!empty($gameinfo['flash']['height']) && is_numeric($gameinfo['flash']['height']))
								$game['extra_data']['height'] = (int)$gameinfo['flash']['height'];
							if (!empty($gameinfo['flash']['version']) && is_numeric($gameinfo['flash']['version']))
								$game['extra_data']['flash_version'] = (int)$gameinfo['flash']['version'];
							if (!empty($gameinfo['flash']['type']))
								$game['extra_data']['type'] =  ArcadeSpecialChars($gameinfo['flash']['type'], 'name');
							if (!empty($gameinfo['flash']['bgcolor']) && strlen($gameinfo['flash']['bgcolor']) == 6)
							{
								$game['extra_data']['background_color'] = array(
									hexdec(mb_substr($gameinfo['flash']['bgcolor'], 0, 2)),
									hexdec(mb_substr($gameinfo['flash']['bgcolor'], 2, 2)),
									hexdec(mb_substr($gameinfo['flash']['bgcolor'], 4, 2))
								);
							}
							else
							{
								$game['extra_data']['background_color'] = array(
									hexdec('00'),
									hexdec('00'),
									hexdec('00')
								);
							}
						}
					}

					$filez = file_get_contents($fileX);
					$row['submit_system'] = empty($html53) ? 'html52' : 'html53';
				}
				elseif (file_exists($directory . '/gamedata/' . $internal_name . '/index.php'))
				{
					$filez = file_get_contents($directory . '/gamedata/' . $internal_name . '/index.php');
					if (strpos($filez, 'function ajax2') !== false)
					{
						$row['submit_system'] = 'html52';
						$game['file'] = 'gamedata/' . $game['internal_name'] . '/index.php';
					}
				}

				$fileX = empty($fileX) ? 'mismatch' : $fileX;
			}
		}

		// check for Phpbb v3Arcade save type ~ game settings file will override some defaults
		if (file_exists($directory . '/' . $mainFile . '.game.php'))
		{
			$filez = file($directory . '/' . $mainFile . '.game.php', FILE_SKIP_EMPTY_LINES);
			$phpFile = implode('', $filez);
			if (stripos($phpFile, 'v3arcade') !== false || stripos($phpFile, 'v3 arcade') !== false)
			{
				foreach($filez as $line)
				{
					$linex = trim(preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $line));
					$linex = preg_replace("#/\*.*?\*/#si", '', $linex);
					if (strpos($linex, '$title=') !== false)
						$game['name'] = str_replace(array('$title=', "'", ';'), array('', '', ''), $linex);

					if (strpos($linex, '$description=') !== false)
						$game['description'] = str_replace(array('$description=', "'", ";"), array('', '', ''), $linex);

					if (strpos($linex, '$help=') !== false)
						$game['help'] = str_replace(array('$help=', "'", ";"), array('', '', ''), $linex);

					if (strpos($linex, '$game_width=') !== false)
						$game['extra_data']['width'] = str_replace(array('$game_width=', "'", ";"), array('', '', ''), $linex);

					if (strpos($linex, '$game_height=') !== false)
						$game['extra_data']['height'] = str_replace(array('$game_height=', "'", ";"), array('', '', ''), $linex);

					preg_match("/games(.*)values/is",$line, $results);
					$parse = !empty($results) ? $results[0] : '';
					$inserts = str_replace(array('(', ')', '\'', '"'), array('', '', '', ''), $parse);

					preg_match("/values(.*)\)/is",$line, $results);
					$parse = !empty($results) ? $results[0] : '';
					$values = str_replace(array('(', ')', '\'', '"'), array('', '', '', ''), $parse);

					if (!empty($inserts) && !empty($values) && empty($game['description']))
					{
						$insertArray = explode(',', $inserts);
						$valuesArray = explode(',', $values);

						if (count($insertArray) == count($valuesArray))
						{
							for($i=0;$i<count($insertArray)-1;$i++)
							{
								$var = trim($insertArray[$i]);
								$$var = trim($valuesArray[$i]);
							}

							$game['description'] = !empty($descr) ? ArcadeSpecialChars($descr, 'name') : '';
							$game['extra_data']['type'] = !empty($highscore) ? ArcadeSpecialChars($highscore, 'name') : 0;
							$game['name'] = !empty($title) ? ArcadeSpecialChars($title, 'name') : $row['game_name'];
							$game['thumbnail'] = !empty($stdimage) ? $stdimage : (!empty($game['thumbnail']) ? $game['thumbnail'] : '');
							$game['thumbnail_small'] = !empty($miniimage) ? $miniimage : (!empty($game['thumbnail_small']) ? $game['thumbnail_small'] : '');
							$game['extra_data']['width'] = !empty($width) ? $width : (!empty($game['extra_data']['width']) ? $game['extra_data']['width'] : 0);
							$game['extra_data']['height'] = !empty($height) ? $height : (!empty($game['extra_data']['height']) ? $game['extra_data']['height'] : 0);
						}
					}

					$row['submit_system'] = 'v3arcade';
					if (substr($game['file'], -4) == '.swf')
					{
						$swf->open($directory . '/' . $game['file']);

						// Add missing values
						if (!$swf->error)
						{
							$game['extra_data']['flash_version'] = $swf->header['version'];
							$game['extra_data']['background_color'] = empty($game['extra_data']['background_color']) ? $swf->header['background'] : $game['extra_data']['background_color'];
							$game['extra_data']['width'] = empty($game['extra_data']['width']) ? $swf->header['width'] : $game['extra_data']['width'];
							$game['extra_data']['height'] = empty($game['extra_data']['height']) ? $swf->header['height'] : $game['extra_data']['height'];
							$game['extra_data']['type'] = empty($game['extra_data']['type']) ? '' : $game['extra_data']['type'];
						}
						$swf->close();

						if (!empty($game['extra_data']['background_color']) && is_array($game['extra_data']['background_color']))
							$game['extra_data']['background_color'] = implode($game['extra_data']['background_color']);

						if (!empty($game['extra_data']['background_color']) && !is_array($game['extra_data']['background_color']) && strlen($game['extra_data']['background_color']) == 3)
							$game['extra_data']['background_color'] = $game['extra_data']['background_color'] . $game['extra_data']['background_color'];
						if (!empty($game['extra_data']['background_color']) && !is_array($game['extra_data']['background_color']) && strlen($game['extra_data']['background_color']) == 6)
						{
							$game['extra_data']['background_color'] = array(
								hexdec(mb_substr($game['extra_data']['background_color'], 0, 2)),
								hexdec(mb_substr($game['extra_data']['background_color'], 2, 2)),
								hexdec(mb_substr($game['extra_data']['background_color'], 4, 2))
							);
						}
						else
						{
							$game['extra_data']['background_color'] = array(
								hexdec('00'),
								hexdec('00'),
								hexdec('00')
							);
						}
					}
				}
			}

			// best to delete this php file after gathering its data
			@unlink($directory . '/' . $mainFile . '.game.php');
		}

		$game['submit_system'] = $row['submit_system'];
		$game['score_type'] = isset($gameinfo) && isset($gameinfo['scoring']) ? (int) $gameinfo['scoring'] : 0;

		if (!empty($gameinfo['thumbnail']))
			$game['thumbnail'] = $gameinfo['thumbnail'];
		if (!empty($gameinfo['thumbnail-small']))
			$game['thumbnail_small'] = $gameinfo['thumbnail-small'];


		$game_directory = $game['directory'];

		// Move files if necessary
		if ($game_directory != $internal_name && $move_games)
		{
			if (!is_dir($modSettings['gamesDirectory'] . '/' . $internal_name) && !mkdir($modSettings['gamesDirectory'] . '/' . $internal_name, 0755))
			{
				$moveFail = true;
				$game['error'] = array('directory_make_failed', array($modSettings['gamesDirectory'] . '/' . $internal_name));

				continue;
			}

			if (!is_writable($modSettings['gamesDirectory'] . '/' . $internal_name))
				@chmod($modSettings['gamesDirectory'] . '/' . $internal_name, 0755);

			$renames = array(
				$directory . '/' . $game['file'] => $modSettings['gamesDirectory'] . '/' . $internal_name . '/' . $game['file'],
			);

			if (!empty($game['thumbnail']))
				$renames[$directory . '/' . $game['thumbnail']] = $modSettings['gamesDirectory'] . '/' . $internal_name . '/' . $game['thumbnail'];

			if (!empty($game['thumbnail_small']))
				$renames[$directory . '/' . $game['thumbnail_small']] = $modSettings['gamesDirectory'] . '/' . $internal_name . '/' . $game['thumbnail_small'];

			foreach ($renames as $from => $to)
			{
				if (!file_exists($from) && file_exists($to))
					continue;

				if (!rename($from, $to))
				{
					$moveFail = true;
					$game['error'] = array('file_move_failed', array($from, $to));
					continue;
				}
			}

			if (!$moveFail)
			{
				$game_directory = $internal_name;
				$directory = $modSettings['gamesDirectory'] . '/' . $game_directory;
			}
		}

		// override some settings if the xml configuration file is available
		if(file_exists($modSettings['gamesDirectory'] . '/' .$game_directory . '/game-info.xml'))
			$mainXmlFileFind = $modSettings['gamesDirectory'] . '/' .$game_directory . '/game-info.xml';
		elseif (file_exists($modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $mainFile . '.xml'))
			$mainXmlFileFind = $modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $mainFile . '.xml';
		elseif(file_exists($modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $game['internal_name'] . '.xml'))
			$mainXmlFileFind = $modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $game['internal_name'] . '.xml';
		else
			$mainXmlFileFind = '';

		// override some settings if the php configuration file is available and the xml file is not available
		if (file_exists($modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $mainFile . '.php'))
			$mainPhpFileFind = $modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $mainFile . '.php';
		elseif(file_exists($modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $game['internal_name'] . '.php'))
			$mainPhpFileFind = $modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $game['internal_name'] . '.php';
		else
			$mainPhpFileFind = '';

		$infoFile = false;
		if (!empty($mainXmlFileFind))
		{
			$gameinfo = readGameInfo($mainXmlFileFind);
			$infoFile = true;
		}
		elseif(!empty($mainPhpFileFind))
		{
			$gameinfo = readPhpGameInfo($game_directory, basename($mainPhpFileFind, ".php"));
			$infoFile = true;
			if (!empty($skip))
			{
				$gameinfo['submit'] = 'html5';
				$gameinfo['file'] = $skip;
			}
		}

		if (!empty($infoFile))
		{
			$game['help'] = isset($gameinfo['help']) ? $gameinfo['help'] : '';
			$game['description'] = isset($gameinfo['description']) ? $gameinfo['description'] : '';
			if (isset($gameinfo['flash']))
			{
				if (!empty($gameinfo['flash']['width']) && is_numeric($gameinfo['flash']['width']))
					$game['extra_data']['width'] = (int)$gameinfo['flash']['width'];
				if (!empty($gameinfo['flash']['height']) && is_numeric($gameinfo['flash']['height']))
					$game['extra_data']['height'] = (int)$gameinfo['flash']['height'];
				if (!empty($gameinfo['flash']['version']) && is_numeric($gameinfo['flash']['version']))
					$game['extra_data']['flash_version'] = (int)$gameinfo['flash']['version'];
				if (!empty($gameinfo['flash']['type']))
					$game['extra_data']['type'] =  ArcadeSpecialChars($gameinfo['flash']['type'], 'name');
				if (!empty($gameinfo['flash']['bgcolor']) && strlen($gameinfo['flash']['bgcolor']) == 6)
				{
					$game['extra_data']['background_color'] = array(
						hexdec(mb_substr($gameinfo['flash']['bgcolor'], 0, 2)),
						hexdec(mb_substr($gameinfo['flash']['bgcolor'], 2, 2)),
						hexdec(mb_substr($gameinfo['flash']['bgcolor'], 4, 2))
					);
				}
				else
				{
					$game['extra_data']['background_color'] = array(
						hexdec('00'),
						hexdec('00'),
						hexdec('00')
					);
				}
			}
		}

		if(!empty($mainPhpFileFind))
		{
			$imageArray = array('gif', 'png', 'jpg');
			/*
			$file = file_get_contents($mainPhpFileFind);
			if (strpos($file, '$config = array(') !== false)
				@require_once($mainPhpFileFind);
			*/

			foreach ($imageArray as $type)
			{
				if (empty($game['thumbnail']))
				{
					if (file_exists($gamePath . '1.' . $type))
						$game['thumbnail'] = $filename . '1.' . $type;
					elseif (file_exists($gamePath . '.' . $type))
						$game['thumbnail'] = $filename . '.' . $type;
				}

				if (empty($game['thumbnail_small']))
					if (file_exists($gamePath . '2.' . $type))
						$game['thumbnail_small'] = $filename . '2.' . $type;
			}

			if (substr($game['file'], -4) == '.swf')
			{
				$swf->open($modSettings['gamesDirectory'] . '/' . $game_directory . '/' . $game['file']);

				// Add missing values
				if (!$swf->error)
				{
					$game['extra_data']['flash_version'] = $swf->header['version'];
					$game['extra_data']['background_color'] = empty($game['extra_data']['background_color']) ? $swf->header['background'] : $game['extra_data']['background_color'];
					$game['extra_data']['width'] = empty($game['extra_data']['width']) ? $swf->header['width'] : $game['extra_data']['width'];
					$game['extra_data']['height'] = empty($game['extra_data']['height']) ? $swf->header['height'] : $game['extra_data']['height'];
					$game['extra_data']['type'] = empty($game['extra_data']['type']) ? '' : $game['extra_data']['type'];
				}

				$swf->close();

				if (!empty($game['extra_data']['background_color']) && is_array($game['extra_data']['background_color']))
					$game['extra_data']['background_color'] = implode($game['extra_data']['background_color']);
				if (!empty($game['extra_data']['background_color']) && !is_array($game['extra_data']['background_color']) && strlen($game['extra_data']['background_color']) == 3)
					$game['extra_data']['background_color'] = $game['extra_data']['background_color'] . $game['extra_data']['background_color'];

				if (!empty($game['extra_data']['background_color']) && strlen($game['extra_data']['background_color']) == 6)
				{
					$game['extra_data']['background_color'] = array(
						hexdec(mb_substr($game['extra_data']['background_color'], 0, 2)),
						hexdec(mb_substr($game['extra_data']['background_color'], 2, 2)),
						hexdec(mb_substr($game['extra_data']['background_color'], 4, 2))
					);
				}
				else
				{
					$game['extra_data']['background_color'] = array(
						hexdec('00'),
						hexdec('00'),
						hexdec('00')
					);
				}
			}
		}

		// Ensure game icons are set if they exist
		$imageArray = array('gif', 'png', 'jpg');
		$imgFileCheck = str_replace('\\', '/', $modSettings['gamesDirectory'] . (!empty($row['game_directory']) ? '/' . $row['game_directory'] : ''));
		$defaultArcIconsDir = str_replace('\\', '/', $settings['default_theme_dir'] . '/images/arc_icons');
		foreach ($imageArray as $type)
		{
			$game['thumbnail_small'] = empty($game['thumbnail_small']) || is_array($game['thumbnail_small']) ? '' : $game['thumbnail_small'];
			$game['thumbnail'] = empty($game['thumbnail']) || is_array($game['thumbnail']) ? '' : $game['thumbnail'];

			if (empty($game['thumbnail']) || !file_exists($imgFileCheck . '/' . $game['thumbnail']))
			{
				if (file_exists($gamePath . '1.' . $type))
					$game['thumbnail'] = $filename . '1.' . $type;
				elseif (file_exists($gamePath . '.' . $type))
					$game['thumbnail'] = $filename . '.' . $type;
			}

			if (empty($game['thumbnail_small']) || !file_exists($imgFileCheck . '/' . $game['thumbnail_small']))
			{
				if (file_exists($gamePath . '2.' . $type))
					$game['thumbnail_small'] = $filename . '2.' . $type;
			}
		}
		$game['thumbnail'] = is_array($game['thumbnail'])? $game['thumbnail'][0] : $game['thumbnail'];
		$game['thumbnail_small'] = is_array($game['thumbnail_small']) ? $game['thumbnail_small'][0] : $game['thumbnail_small'];

		// if they were not set then we can use the default..
		if (empty($game['thumbnail']) || !file_exists($imgFileCheck . '/' . $game['thumbnail']))
		{
			if (file_exists($defaultArcIconsDir . '/game.gif') && !file_exists($imgFileCheck . '/game.gif'))
				@copy($defaultArcIconsDir . '/game.gif', $imgFileCheck . '/game.gif');
			if (file_exists($imgFileCheck . '/game.gif'))
				@chmod('0644', $imgFileCheck . '/game.gif');

			$game['thumbnail'] = 'game.gif';
		}

		if (empty($game['thumbnail_small']) || !file_exists($imgFileCheck . '/' . $game['thumbnail_small']))
		{
			if ($game['thumbnail'] == 'game.gif')
			{
				if (file_exists($defaultArcIconsDir . '/game.gif') && !file_exists($imgFileCheck . '/game.gif'))
					@copy($defaultArcIconsDir . '/game.gif', $imgFileCheck . '/game.gif');
				if (file_exists($imgFileCheck . '/game.gif'))
					@chmod('0644', $imgFileCheck . '/game.gif');

				$game['thumbnail_small'] = '/game.gif';
			}
			elseif (!empty($game['thumbnail']))
				$game['thumbnail_small'] = $game['thumbnail'];
		}


		// Ensure extra data was set for swf file
		if ((empty($game['extra_data']['width']) || empty($game['extra_data']['height']) || empty($game['extra_data']['version']) || empty($game['extra_data']['background_color'])) && substr($game['file'], -4) == '.swf')
		{
			$dimensions = '';
			$swf->open($gamePath . '.swf');
			if (!$swf->error)
			{
				$game['extra_data'] += array(
					'width' => !empty($game['extra_data']['width']) ? $game['extra_data']['width'] : $swf->header['width'],
					'height' => !empty($game['extra_data']['height']) ? $game['extra_data']['height'] : $swf->header['height'],
					'flash_version' => !empty($game['extra_data']['version']) ? $game['extra_data']['version'] : $swf->header['version'],
					'background_color' => !empty($game['extra_data']['background_color']) ? $game['extra_data']['background_color'] : $swf->header['background'],
					'type' => !empty($gameinfo['flash']['type']) ? ArcadeSpecialChars($gameinfo['flash']['type'], 'name') : '',
				);
			}

			$swf->close();

			if (!empty($game['extra_data']['background_color']) && is_array($game['extra_data']['background_color']))
				$game['extra_data']['background_color'] = implode($game['extra_data']['background_color']);

			if (!empty($game['extra_data']['background_color']) && !is_array($game['extra_data']['background_color']) && strlen($game['extra_data']['background_color']) == 3)
				$game['extra_data']['background_color'] = $game['extra_data']['background_color'] . $game['extra_data']['background_color'];

			if(empty($game['extra_data']['width']))
			{
				// Ensure game dimensions were set for phpbb type
				$tihi = array();
				if ($row['submit_system'] == 'phpbb')
				{
					$tihi_file = $modSettings['gamesDirectory'] . '/' . (!empty($row['game_directory']) ? $row['game_directory'] . '/size.txt' : 'size.txt');
					if (file_exists($tihi_file))
					{
						$file = fopen($tihi_file, 'r');
						$dimensions .= fgets($file);
						fclose($file);
						$tihi = explode('x', mb_strtolower($dimensions));
					}
				}

				$width = !empty($tihi) ? preg_replace("/[^0-9]/", '', $tihi[0]) : (!empty($game['extra_data']['width']) ? $game['extra_data']['width'] : 600);
				$height = !empty($tihi) ? preg_replace("/[^0-9]/", '', $tihi[1]) : (!empty($game['extra_data']['height']) ? $game['extra_data']['height'] : 400);
				$game['extra_data'] = array(
					'width' => (int)$width,
					'height' => (int)$height,
					'flash_version' => !empty($game['extra_data']['flash_version']) ? $game['extra_data']['flash_version'] : 0,
					'background_color' => !empty($game['extra_data']['background_color']) ? $game['extra_data']['background_color'] : array(
						hexdec('00'),
						hexdec('00'),
						hexdec('00')
					),
					'type' => !empty($game['extra_data']['type']) ? $game['extra_data']['type'] : '',
				);
			}
		}

		// Final install data
		$game['name'] = !empty($gameinfo['name']) ? $gameinfo['name'] : (!empty($game['name']) ? $game['name'] : '');
		$game['description'] = !empty($gameinfo['description']) ? $gameinfo['description'] : (!empty($game['description']) ? $game['description'] : '');
		$gameinfo['help'] = !empty($gameinfo['help']) && $gameinfo['help'] != $game['description'] ? $gameinfo['help'] : '';
		$game['help'] = !empty($gameinfo['help']) ? $gameinfo['help'] : (!empty($game['help']) && $game['help'] != $game['description'] ? $game['help'] : '');
		$game['description'] = str_replace(array('&#039;', '&apos;', '&#034;', '&#34;', '&#038', '&#38;'), array('&#39;', '&#39;', '&quot;', '&quot;', '&amp;', '&amp;'), $game['description']);
		$game['help'] = str_replace(array('&#039;', '&apos;', '&#034;', '&#34;', '&#038', '&#38;'), array('&#39;', '&#39;', '&quot;', '&quot;', '&amp;', '&amp;'), $game['help']);
		$game['category'] = $set_category;
		$gameOptions = array(
			'internal_name' => $game['internal_name'],
			'name' => $game['name'],
			'description' => !empty($game['description']) ? $game['description'] : '',
			'thumbnail' => $game['thumbnail'],
			'thumbnail_small' => $game['thumbnail_small'],
			'help' => (!empty($game['help']) ? $game['help'] : !empty($gameinfo['help']) ? $gameinfo['help'] : ''),
			'game_file' => $game['submit_system'] == 'html52' ? 'gamedata/' . $game['internal_name'] . '/index.html' : $game['file'],
			'game_directory' => $game_directory,
			'submit_system' => empty($skip) ? $game['submit_system'] : 'html5',
			'score_type' => $game['score_type'],
			'extra_data' => $game['extra_data'],
			'category' => $set_category,
		);

		$success = false;

		if (!isset($game['error']) && $id_game = createGame($gameOptions))
			$success = true;
		elseif (!in_array($game_directory, $directories))
		{
			$gamefile = $game['submit_system'] == 'html52' || $game['submit_system'] == 'html53' ? $game['internal_name'] . '.php' : $game['file'];
			$files = array_unique(
				array(
					$gamefile,
					!empty($game['thumbnail']) ? $game['thumbnail'] : '',
					!empty($game['thumbnail_small']) ? $game['thumbnail_small'] : '',
					mb_substr($gamefile, 0, -4) . '.php',
					mb_substr($gamefile, 0, -4) . '-game-info.xml',
					mb_substr($gamefile, 0, -4) . '.xap',
					mb_substr($gamefile, 0, -5) . '.html',
					mb_substr($gamefile, 0, -4) . '.ini',
					mb_substr($gamefile, 0, -4) . '.gif',
					mb_substr($gamefile, 0, -4) . '.png',
					mb_substr($gamefile, 0, -4) . '.jpg',
				)
			);
			$dest = $modSettings['gamesDirectory'] . '/' . $game_directory;
			$dest = rtrim($dest, '/');
			foreach ($files as $key => $data)
			{
				if ((!empty($files[$key])) && file_exists($dest . '/' . $files[$key]))
					unlink($dest . '/' . $files[$key]);
			}

			if ((!empty($dest)) && $dest !== $modSettings['gamesDirectory'] && $dest !== $boarddir)
			{
				if (dirname($dest) !== $modSettings['gamesDirectory'])
					arcadeRmdir($dest);

				$gfiles = ArcadeAdminScanDir($dest, '');
				if (empty($gfiles) && is_dir($dest))
					arcadeRmdir($dest);
				elseif ((count($gfiles) == 1) && $gfiles[0] == 'master-info.xml')
				{
					unlink($dest . '/master-info.xml');
					arcadeRmdir($dest);
				}
			}

			if (is_dir($boarddir . '/arcade/gamedata/' . $game['internal_name']))
			{
				$gdfiles = ArcadeAdminScanDir($boarddir . '/arcade/gamedata/' . $game['internal_name'], '');
				foreach ($gdfiles as $file)
					unlink($file);

				deleteArcadeArchives($boarddir . '/arcade/gamedata/' . $game['internal_name']);
			}

			$game['error'] = array('arcade_install_general_fail', array('path', $game_directory));
		}
		else
		{
			$exists = true;
			$game['error'] = array('arcade_install_exists_fail_del', array('path', $game_directory));
			$gameDir = str_replace('\\', '/', $game_directory);
			$gameDir = rtrim($gameDir, '/');
			if (!empty($gameDir))
				$gameDirx = explode('/', $gameDir);
			else
				$gameDirx[0] = '';

			if (!empty($game_directory) && $modSettings['gamesDirectory'] . '/' !== $modSettings['gamesDirectory'] . '/' . $gameDirx[0])
			{
				foreach (array('.zip', '.tar', '.rar', '.tar.gz', '.ZIP', '.TAR', '.RAR', '.TAR.gz', 'TAR.GZ') as $ext)
					if (file_exists($modSettings['gamesDirectory'] . '/' . $gameDirx[0] . $ext))
						unlink($modSettings['gamesDirectory'] . '/' . $gameDirx[0] . $ext);
			}
		}

		if (empty($exists))
		{
			$check = !empty($fileX) && $fileX == 'mismatch' ? false : true;

			if ($check)
			{
				$smcFunc['db_query']('', '
					UPDATE {db_prefix}arcade_files
					SET id_game = {int:game}, status = {int:status}, game_directory = {string:directory}
					WHERE id_file = {int:file}',
					array(
						'game' => empty($success) ? 0 : $id_game,
						'status' => empty($success) ? 10 : 1,
						'file' => $game['id_file'],
						'directory' => $game_directory,
					)
				);
			}
		}

		$status[] = array(
			'id' => $id_game,
			'name' => $game['name'],
			'error' => isset($game['error']) ? $game['error'] : false,
		);
	}
	$smcFunc['db_free_result']($request);

	return $status;
}

function unpackGames($games, $move_games = false)
{
	global $scripturl, $txt, $db_prefix, $modSettings, $context, $sourcedir, $smcFunc, $boarddir;

	if (!is_writable($modSettings['gamesDirectory']) && !chmod($modSettings['gamesDirectory'], 0755))
		fatal_lang_error('arcade_not_writable', false, array($modSettings['gamesDirectory']));

	require_once($sourcedir . '/Tar.php');
	if (!class_exists('RarArchiver') && version_compare(phpversion(), '5.5.10', '>'))
		require_once($sourcedir . '/Subs-ArcadeRarClass.php');

	require_once($sourcedir . '/Subs-Package.php');
	$smfVersion = version_compare((!empty($modSettings['smfVersion']) ? mb_substr($modSettings['smfVersion'], 0, 3) : '2.0'), '2.1', '<') ? 'v2.0' : 'v2.1';
	$modSettings['gamesDirectory'] = str_replace('\\', '/', $modSettings['gamesDirectory']);
	$modSettings['gamesDirectory'] = rtrim($modSettings['gamesDirectory'], '/');
	list($countz, $saveType, $gameinfo, $_SESSION['arcade_exists']) = array(0, '', array(), array());

	$request = $smcFunc['db_query']('', '
		SELECT f.id_file, f.game_file, f.game_directory
		FROM {db_prefix}arcade_files AS f
		WHERE id_file IN ({array_int:games})
			AND (f.status = 10)',
		array(
			'games' => $games,
		)
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$countz++;
		$saveType = '';
		$fileTemp = '';
		$row['game_directory'] = trim(str_replace('\\', '/', $row['game_directory']), '/');
		$from = str_replace('\\', '/', $modSettings['gamesDirectory']) . '/' . (!empty($row['game_directory']) ? str_replace('\\', '/', $row['game_directory']) . '/' : '') . str_replace('\\', '/', $row['game_file']);
		$data = '';
		for ($i=0; $i<2; $i++)
		{
			if (empty($row['game_file']))
				continue;

			$pop = explode('.', $row['game_file']);
			$target = !empty($row['game_directory']) ? basename($row['game_directory']) : substr($row['game_file'], 0, -strlen('.' . end($pop)));
		}
		$target = strlen(mb_substr($target, 6)) > 0 && mb_substr(mb_strtolower($target), 0, 5) == 'game_' ? mb_substr($target, 5) : $target;
		$target = strlen(mb_substr($target, 7)) > 0 && mb_substr(mb_strtolower($target), 0, 6) == 'html5_' ? mb_substr($target, 6) : $target;
		$target = strlen(mb_substr($target, 8)) > 0 && mb_substr(mb_strtolower($target), 0, 7) == 'html52_' ? mb_substr($target, 7) : $target;
		$target = strlen(mb_substr($target, 8)) > 0 && mb_substr(mb_strtolower($target), 0, 7) == 'html53_' ? mb_substr($target, 7) : $target;
		$target = strlen(mb_substr($target, 10)) > 0 && mb_substr(mb_strtolower($target), 0, 9) == 'v3arcade_' ? mb_substr($target, 9) : $target;
		$target = substr(mb_strtolower($target), -3) == '.gz' ? substr_replace($target, '', -3) : $target;
		$target = substr(mb_strtolower($target), -4) == '.zip' || substr(mb_strtolower($target), -4) == '.tar' || substr(mb_strtolower($target), -4) == '.rar' ? substr_replace($target, '', -4) : $target;
		$target = str_replace(array(' ', '-'), array('', '_'), $target);
		$target = trim($target, "_./");

		if (file_exists($modSettings['gamesDirectory'] . '/' . $target))
		{
			// if the directory is empty we can still use it otherwise abort the installation
			$dir_iterator = new RecursiveDirectoryIterator($modSettings['gamesDirectory'] . '/' . $target);
			$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::CHILD_FIRST);
			$dirFiles = array();

			foreach ($iterator as $file)
				if (mb_substr($file, -1) != '.' && mb_substr($file, -2) != '..')
					$dirFiles[] = $file;

			// if directory exists containing files, remove compressed archives that will resolve to the same directory & display an error message
			if (count($dirFiles) > 0)
			{
				$targety = explode('/', trim($target, '/'));
				$targetx = !empty($targety) ? $targety[0] : trim($target, '/');

				foreach (array('.ZIP', '.TAR', '.TAR.GZ', '.RAR', 'TAR.gz') as $xfile)
				{
					foreach (array('GAME_', 'HTML5_', 'HTML52_', 'HTML53_', 'V3ARCADE') as $prefix)
					{
						if (file_exists($modSettings['gamesDirectory'] . '/' . $prefix . $targetx . $xfile))
							unlink($modSettings['gamesDirectory'] . '/' . $prefix . $targetx . $xfile);
						if (file_exists($modSettings['gamesDirectory'] . '/' . mb_strtolower($prefix) . $targetx . mb_strtolower($xfile)))
							unlink($modSettings['gamesDirectory'] . '/' . mb_strtolower($prefix) . $targetx . mb_strtolower($xfile));
						if (file_exists($modSettings['gamesDirectory'] . '/' . $prefix . $targetx . mb_strtolower($xfile)))
							unlink($modSettings['gamesDirectory'] . '/' . $prefix . $targetx . mb_strtolower($xfile));
						if (file_exists($modSettings['gamesDirectory'] . '/' . mb_strtolower($prefix) . $targetx . $xfile))
							unlink($modSettings['gamesDirectory'] . '/' . mb_strtolower($prefix) . $targetx . $xfile);
					}
				}

				if (file_exists($from) && (mb_substr(mb_strtolower($from), -4) == '.zip' || mb_substr(mb_strtolower($from), -4) == '.tar' || mb_substr(mb_strtolower($from), -4) == '.rar' || mb_substr(mb_strtolower($from), -7) == '.tar.gz'))
					unlink($from);

				$exname = basename($target);
				$_SESSION['arcade_exists'][] = preg_replace('/\\.[^.\\s]{3,4,6}$/', '', $exname);
				continue;
				//fatal_lang_error('arcade_directory_make_exists', false, $target);
			}
		}

		if (mb_substr(mb_strtolower($row['game_file']) , -4) == '.zip')
		{
			$path = rtrim($modSettings['gamesDirectory'], '/') . '/' . $target;
			if ($smfVersion === 'v2.1')
				$files = arcadeUnzip($from, $path . '/', true, false);
			else
				$files = read_tgz_file($from, $path);

			$check_parents = arcadeReturnPaths($path);
			if (file_exists($path . '/master-info.xml'))
			{
				$gameinfo = readGameInfo($path . '/master-info.xml');
				$saveType = !empty($gameinfo['submit']) && in_array($gameinfo['submit'], array('v1game', 'v2game', 'v3arcade', 'phpbb', 'mochi', 'custom_game', 'ibp', 'ibp3', 'html5', 'html52', 'html53')) ? $gameinfo['submit'] : '';
			}

			if (!empty($check_parents) && strpos(mb_strtolower($path), 'gamepack') !== false)
			{
				foreach ($check_parents as $parent)
				{
					$fix_parent = mb_strtolower(str_replace(array(' ', '-'), array('', '_'), $parent));
					if (!is_dir(rtrim($modSettings['gamesDirectory'], '/') . '/' . $fix_parent))
						rename($path . '/' . $parent, rtrim($modSettings['gamesDirectory'], '/') . '/' . $fix_parent);
					else
					{
						for($i=0;$i<7;$i++)
						{
							if ($i == 6)
							{
								deleteArcadeArchives($path . '/' . $parent);
								break;
							}
							if (!is_dir(rtrim($modSettings['gamesDirectory'], '/') . '/' . $fix_parent . $i))
							{
								@rename($path . '/' . $parent, rtrim($modSettings['gamesDirectory'], '/') . '/' . $fix_parent . $i);
								break;
							}
						}
					}

					$data = gameCacheInsertGames(getAvailableGames($fix_parent, 'unpack'), $saveType, true);
				}
				$check_parents = arcadeReturnPaths($path);
				if (empty($check_parents))
					arcadeRmdir($path);
			}
			else
				$data = gameCacheInsertGames(getAvailableGames($target, 'unpack'), $saveType, true);

			if (file_exists($path . '/' . rtrim($row['game_file'], '.swf') . '.game.php'))
				@unlink($path . '/' . rtrim($row['game_file'], '.swf') . '.game.php');

		}

		if(mb_substr(mb_strtolower($row['game_file']) , -4) == '.tar' || mb_substr(mb_strtolower($row['game_file']) , -7) == '.tar.gz')
		{
			$path = rtrim($modSettings['gamesDirectory'], '/') . '/';
			if (mb_substr(mb_strtolower($row['game_file']) , -3) == '.gz')
				$tar = new Archive_Tar($path . $row['game_file'], true);
			else
				$tar = new Archive_Tar($path . $row['game_file']);

			$data = $tar->listContent();

			if ($data == false)
				fatal_lang_error('arcade_file_non_read', false);
			else
			{
				$folder = $path . trim($target);

				if(!file_exists($folder))
					@mkdir($folder, 0755);

				$tar->extract($folder);
			}

			$check_parents = arcadeReturnPaths($folder);
			if (file_exists($folder . '/master-info.xml'))
			{
				$gameinfo = readGameInfo($path . '/master-info.xml');
				$saveType = !empty($gameinfo['submit']) && in_array($gameinfo['submit'], array('v1game', 'v2game', 'v3arcade', 'phpbb', 'mochi', 'custom_game', 'ibp', 'ibp3', 'html5', 'html52', 'html53')) ? $gameinfo['submit'] : '';
			}

			if (!empty($check_parents) && strpos(mb_strtolower($folder), 'gamepack') !== false)
			{
				foreach ($check_parents as $parent)
				{
					$fix_parent = mb_strtolower(str_replace(array(' ', '-'), array('', '_'), $parent));
					if (!is_dir($path . $fix_parent))
						@rename($folder . '/' . $parent, $path . $fix_parent);
					else
					{
						for($i=0;$i<7;$i++)
						{
							if ($i == 6)
							{
								deleteArcadeArchives($folder . '/' . $parent);
								break;
							}
							if (!is_dir($path . $fix_parent . $i))
							{
								@rename($path . $parent, $path . $fix_parent . $i);
								break;
							}
						}
					}

					$data = gameCacheInsertGames(getAvailableGames($fix_parent, 'unpack'), $saveType, true);
				}
				$check_parents = arcadeReturnPaths($folder);
				if (empty($check_parents))
					arcadeRmdir($folder);
			}
			else
				$data = gameCacheInsertGames(getAvailableGames($target, 'unpack'), $saveType, true);

			if (file_exists($path . rtrim($row['game_file'], '.swf') . '.game.php'))
				@unlink($path . rtrim($row['game_file'], '.swf') . '.game.php');
		}

		// decompressing rar archives will have to rely on the PECL RarArchive class at this time
		if (mb_substr(mb_strtolower($row['game_file']) , -4) == '.rar' && class_exists('RarArchive'))
		{
			$path = rtrim($modSettings['gamesDirectory'], '/') . '/';
			$folder = $path . trim($target);
			if(!file_exists($folder))
				@mkdir($folder, 0755);

			$archive = RarArchive::open($path . $row['game_file']);
			$entries = $archive->getEntries();
			foreach ($entries as $entry)
				$entry->extract($folder);

			$archive->close();

			if (file_exists($path . $row['game_file']))
			{
				unset($rar);
				if (@unlink($path . $row['game_file']))
					$smcFunc['db_query']('', '
						DELETE FROM {db_prefix}arcade_files
						WHERE id_file = {int:file}',
						array(
							'file' => $row['id_file'],
						)
					);

				if (file_exists($path . rtrim($row['game_file'], '.swf') . '.game.php'))
					@unlink($path . rtrim($row['game_file'], '.swf') . '.game.php');
			}

			$check_parents = arcadeReturnPaths($folder);
			if (file_exists($folder . '/master-info.xml'))
			{
				$gameinfo = readGameInfo($path . '/master-info.xml');
				$saveType = !empty($gameinfo['submit']) && in_array($gameinfo['submit'], array('v1game', 'v2game', 'v3arcade', 'phpbb', 'mochi', 'custom_game', 'ibp', 'ibp3', 'html5', 'html52', 'html53')) ? $gameinfo['submit'] : '';
			}
			if (!empty($check_parents) && strpos(mb_strtolower($folder), 'gamepack') !== false)
			{
				foreach ($check_parents as $parent)
				{
					$fix_parent = mb_strtolower(str_replace(array(' ', '-'), array('', '_'), $parent));
					if (!is_dir($path . $fix_parent))
						@rename($folder . '/' . $parent, $path . $fix_parent);
					else
					{
						for($i=0;$i<7;$i++)
						{
							if ($i == 6)
							{
								deleteArcadeArchives($folder . '/' . $parent);
								break;
							}
							if (!is_dir($path . $fix_parent . $i))
							{
								@rename($path . '/' . $parent, $path . $fix_parent . $i);
								break;
							}
						}
					}
					$data = gameCacheInsertGames(getAvailableGames($fix_parent, 'unpack'), $saveType, true);
				}
				$check_parents = arcadeReturnPaths($folder);
				if (empty($check_parents))
					arcadeRmdir($folder);
			}
			else
				$data = gameCacheInsertGames(getAvailableGames($target, 'unpack'), $saveType, true);
		}

		$path = rtrim($modSettings['gamesDirectory'], '/') . '/' . $target;
		$internalName = basename($target);
		if (file_exists($modSettings['gamesDirectory'] . '/' . $target . '/' . $internalName . '.php'))
			$fileTemp = file_get_contents($modSettings['gamesDirectory'] . '/' . $target . '/' . $internalName . '.php');

		if (!empty($fileTemp) && strpos(str_replace(' ', '', $fileTemp), '$config=array(') !== false)
		{
			list($saveTypeCheck, $na) = checkArcadeHtmlGameFiles($modSettings['gamesDirectory'] . '/' . $target, $internalName);
			$saveType = $saveTypeCheck == 'html5' ? 'html5' : $saveType;
		}
		elseif (!empty($fileTemp) && strpos(str_replace(' ', '', $fileTemp), '$game_data=array(') !== false)
		{
			list($saveTypeCheck, $na) = checkArcadeHtmlGameFiles($modSettings['gamesDirectory'] . '/' . $target, $internalName);
			$saveType = $saveTypeCheck == 'html5' ? 'html5' : $saveType;
		}

		if (file_exists($path . '/master-info.xml'))
			@unlink($path . '/master-info.xml');

		if (file_exists(dirname($path) . '/master-info.xml'))
			@unlink(dirname($path) . '/master-info.xml');

		if (@unlink($from))
			$smcFunc['db_query']('', '
				DELETE FROM {db_prefix}arcade_files
				WHERE id_file = {int:file}',
				array(
					'file' => $row['id_file'],
				)
			);
	}
	$smcFunc['db_free_result']($request);

	return !empty($saveType) ? $saveType : true;

	if ($countz == count($_SESSION['arcade_exists']) && count($_SESSION['arcade_exists']) > 0)
	{
		$targets = '';
		foreach ($_SESSION['arcade_exists'] as $gamex)
			$targets .= ' ' . $gamex . ',';

		$targets = rtrim($targets, ',');
		fatal_lang_error('arcade_directory_make_exists', false, $targets);
	}
}

function uninstallGames($games, $delete_files = false)
{
	global $smcFunc, $modSettings, $sourcedir, $boarddir;

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

	$request = $smcFunc['db_query']('', '
		SELECT id_game, internal_name, game_name, game_file, thumbnail, thumbnail_small, game_directory, id_topic, submit_system
		FROM {db_prefix}arcade_games
		WHERE id_game IN({array_int:games})',
		array(
			'games' => $games
		)
	);

	list($status, $topics) = array(array(), array());

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$maindir = rtrim(str_replace('\\', '/', $modSettings['gamesDirectory']), '/');
		$directory = $modSettings['gamesDirectory'] . (!empty($row['game_directory']) ? '/' . $row['game_directory'] : '');
		$directory = preg_replace('#/+#','/',implode('/', array_map(function($value) {return rtrim($value, '.');}, explode('/', str_replace('\\', '/', $directory)))));
		$gamedir = preg_replace('#/+#','/',implode('/', array_map(function($value) {return trim($value, '.');}, explode('/', str_replace('\\', '/', $row['game_directory'])))));
		$internal_name = str_replace(array('/', '\\'), array('', ''), trim($row['internal_name'], '.'));
		$directory = rtrim($directory, '/');

		if (!empty($row['id_topic']))
			$topics[] = $row['id_topic'];

		$files = array_unique(
			array(
				$row['game_file'],
				$row['thumbnail'],
				$row['thumbnail_small'],
				'master-info.xml',
				mb_substr($row['game_file'], 0, -4) . '.php',
				mb_substr($row['game_file'], 0, -4) . '-game-info.xml',
				mb_substr($row['game_file'], 0, -5) . '.html',
				mb_substr($row['game_file'], 0, -4) . '.xap',
				mb_substr($row['game_file'], 0, -4) . '.ini',
				mb_substr($row['game_file'], 0, -4) . '.game.php',
			)
		);

		// edit file deletion routines below at your own risk
		if ($delete_files)
		{
			if (!empty($row['game_directory']))
				arcadeRmdir($directory);

			if (basename(dirname($directory)) !== basename($modSettings['gamesDirectory']) && basename($directory) !== basename($modSettings['gamesDirectory']))
			{
				//if (is_dir($directory))
					//deleteArcadeArchives($directory);

				$dir = dirname($directory);
				$base = $directory;
				$gd = $modSettings['gamesDirectory'];
				$bd = $boarddir;
				foreach (array('/', '\\') as $sep)
				{
					$base = rtrim($base, $sep);
					$dir = rtrim($dir, $sep);
					$gd = rtrim($gd, $sep);
					$bd = rtrim($bd, $sep);
				}

				if (is_dir($base) && $base !== $gd && $base !== $bd)
				{
					// additional sub-directories?
					if ($base !== $dir)
					{
						$files = ArcadeAdminScanDir($base, '');
						foreach ($files as $file)
							if (!is_dir($file))
								unlink($file);

						if (count(scandir($base)) == 2)
							arcadeRmdir($base);

						$paths = arcadeReturnPaths($base);
						if (!empty($paths))
						{
							foreach($paths as $path)
								arcadeRmdir($base . '/' . $path);
						}

						if (empty(arcadeReturnPaths($base)))
						{
							if (file_exists($dir . '/master-info.xml'))
								unlink($dir . '/master-info.xml');

							arcadeRmdir($base);
						}

						if (empty(arcadeReturnPaths($dir)))
							arcadeRmdir($dir);
					}
					else
					{
						$files = ArcadeAdminScanDir($dir, '');
						foreach ($files as $file)
							if (!is_dir($file))
								unlink($file);

						if (count(scandir($dir)) == 2)
							arcadeRmdir($dir);

						if (empty(arcadeReturnPaths($dir)))
							arcadeRmdir($dir);
					}
				}


			}
			elseif (basename($gamedir) == $internal_name && $internal_name !== basename($modSettings['gamesDirectory']))
			{
				if (is_dir($directory) && basename($directory) !== $modSettings['gamesDirectory'])
				{
					$files = ArcadeAdminScanDir($directory, '');
					$dirs = array($directory);
					foreach ($files as $file)
					{
						unlink($file);
						if(!in_array(dirname($file), $dirs))
							$dirs[] = dirname($file);
					}
					foreach ($dirs as $dir)
					{
						$dir = rtrim($dir, '/');
						if (is_dir($dir) && $dir !== $directory)
						{
							if ($modSettings['gamesDirectory'] . '/' !== $modSettings['gamesDirectory'] . '/' . $dir && $dir !== $modSettings['gamesDirectory'])
								arcadeRmdir($dir);
						}
					}

					if (is_dir($directory) && $modSettings['gamesDirectory'] . '/' !== $modSettings['gamesDirectory'] . '/' . $directory && $directory !== $modSettings['gamesDirectory'])
						arcadeRmdir($directory);

					if (empty(arcadeReturnPaths($gamedir)))
						arcadeRmdir($gamedir);

					if (empty(arcadeReturnPaths($directory)))
						arcadeRmdir($directory);
				}
			}
			elseif (is_dir($directory . '/gamedata/' . $internal_name) && $directory != $boarddir && in_array($row['submit_system'], array('html5', 'html52', 'html53')) && $directory != $modSettings['gamesDirectory'])
				arcadeRmdir($directory);
			else
			{
				foreach ($files as $f)
				{
					if ((!empty($f)) && file_exists($directory . '/' . $f))
						unlink($directory . '/' . $f);
				}

				if (basename($directory) !== basename($modSettings['gamesDirectory']))
				{
					$check = ArcadeAdminScanDir($directory, '');
					if (empty($check) && $modSettings['gamesDirectory'] . '/' !== $modSettings['gamesDirectory'] . '/' . $directory && $directory !== $modSettings['gamesDirectory'] && is_dir($directory))
						arcadeRmdir($directory);
					elseif (count($check) == 1 && $check[0] == $directory . '/master-info.xml')
					{
						unlink($directory . '/master-info.xml');

						if ($modSettings['gamesDirectory'] . '/' !== $modSettings['gamesDirectory'] . '/' . $directory && $directory !== $modSettings['gamesDirectory'])
							arcadeRmdir($directory);
					}
				}
			}

			if (is_dir($boarddir . '/arcade/gamedata/' . $internal_name) || file_exists($boarddir . '/arcade/gamedata/' . $internal_name))
				arcadeRmdir($boarddir . '/arcade/gamedata/' . $internal_name);
		}

		$noUnderscore = str_replace('_', '', mb_strtolower(basename($directory)));
		if (mb_strtolower(basename($directory)) == mb_strtolower($internal_name) ||  $noUnderscore == mb_strtolower($internal_name) && !empty(basename($directory)) && $directory != $boarddir && $directory != $maindir)
		{
			if ($delete_files)
			{
				arcadeRmdir($directory);
				arcadeRmdir($directory);
			}
		}

		deleteGame($row['id_game'], $delete_files);

		$status[] = array(
			'id' => $row['id_game'],
			'name' => $row['game_name'],
		);
	}

	$smcFunc['db_free_result']($request);

	// remove related topics if they exist
	if (!empty($topics))
		removeTopics($topics, false, false);

	return $status;
}

function moveGames()
{
	global $db_prefix, $modSettings, $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT id_game, internal_name, game_directory, game_file, thumbnail, thumbnail_small
		FROM {db_prefix}arcade_games');

	if (!is_writable($modSettings['gamesDirectory']))
		fatal_lang_error('arcade_not_writable', false, array($modSettings['gamesDirectory']));

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$from = $modSettings['gamesDirectory']  . '/' . (!empty($row['game_directory']) ? $row['game_directory'] . '/' : '');
		$to = $modSettings['gamesDirectory'] . '/' . str_replace(array('/', '\\'), array('', ''), trim($row['internal_name'], '.')) . '/';
		$to = preg_replace('#/+#','/',implode('/', array_map(function($value) {return rtrim($value, '.');}, explode('/', str_replace('\\', '/', $to)))));

		if ($from == $to)
			continue;

		if ((file_exists($to) && !is_dir($to)) || !mkdir($to))
			fatal_lang_error('arcade_not_writable', false, array($to));

		chdir($from);

		// These should be at least there
		$files = array();
		$files[] = $row['game_file'];
		$files[] = $row['thumbnail'];
		$files[] = $row['thumbnail_small'];

		foreach ($files as $file)
		{
			if (file_exists($from . $file))
				if (!rename($from . $row['gameFile'], $to . $file))
					fatal_lang_error('arcade_unable_to_move', false, array($file, $from, $to));
		}

		updateGame($row['id_game'], array('game_directory' => $row['internal_name']));
	}
	$smcFunc['db_free_result']($request);
}

function updateCategoryStats()
{
	global $smcFunc;

	$smcFunc['db_query']('', '
		UPDATE {db_prefix}arcade_categories
		SET num_games = {int:num_games}',
		array(
			'num_games' => 0,
		)
	);

	$request = $smcFunc['db_query']('', '
		SELECT id_cat, COUNT(*) as games
		FROM {db_prefix}arcade_games
		GROUP BY id_cat');

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$smcFunc['db_query']('', '
			UPDATE {db_prefix}arcade_categories
			SET num_games = {int:num_games}
			WHERE id_cat = {int:category}',
			array(
				'category' => $row['id_cat'],
				'num_games' => $row['games'],
			)
		);
	$smcFunc['db_free_result']($request);

	return true;
}

function readGameInfo($file)
{
	if (!file_exists($file))
		return false;

	$gameinfo = new xmlArray(file_get_contents($file));
	$gameinfo = $gameinfo->path('game-info[0]');
	return $gameinfo->to_array();
}

function readPhpGameInfo($directory, $name='')
{
	global $modSettings, $txt;

	list($mainPhpFileFind, $game) = array('', array());
	if (empty($name))
	{
		$files = array_diff(scandir($modSettings['gamesDirectory'] . '/' . $directory), array('..', '.'));
		foreach ($files as $file)
		{
			$info = new SplFileInfo($file);
			$ext = ($info->getExtension());
			if ($ext == 'php')
			{
				$mainPhpFileFind = $modSettings['gamesDirectory'] . '/' . $directory . '/' . $file;
				$name = rtrim($file, '.php');
				break;
			}
		}
	}
	elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $name . '.php'))
		$mainPhpFileFind = $modSettings['gamesDirectory'] . '/' . $directory . '/' . $name . '.php';
	else
		$mainPhpFileFind = '';

	if(!empty($mainPhpFileFind) && file_exists($mainPhpFileFind))
	{
		$imageArray = array('gif', 'png', 'jpg');
		$game_info = array('gname', 'gtitle', 'gwords', 'gkeys', 'type', 'savetype');
		$arcade_info = array('file', 'name', 'description', 'help', 'type', 'savetype');
		$x = 0;
		$phpbb = false;
		$file = file_get_contents($mainPhpFileFind);

		// phpbb game types
		if (strpos(str_replace(' ', '', $file), '$game_data=array(') !== false && strpos(str_replace(' ', '', $file), 'IN_PHPBB_ARCADE') !== false)
		{
			$phpbb = true;
			if (!defined('IN_PHPBB_ARCADE'))
			{
				define('IN_PHPBB_ARCADE', 'true');
				define('IN_PHPBB', 'true');
				define('GAME_TYPE_HTML5', 'html52');
				define('GAME_TYPE_FLASH', 'flash');
				define('GAME_CONTROL_KEYBOARD_MOUSE', $txt['arcade_game_control_mouse_key']);
				define('GAME_CONTROL_KEYBOARD', $txt['arcade_game_control_key']);
				define('GAME_CONTROL_MOUSE', $txt['arcade_game_control_mouse']);
				define('SCORETYPE_HIGH', '2');
				define('SCORETYPE_LOW', '1');
				define('AMOD_GAME', 'v1game');
				define('IBPRO_GAME', 'ibp');
				define('ARCADELIB_GAME', 'v1game');
				define('V3ARCADE_GAME', 'v3arcade');
				define('IBPROV3_GAME', 'ibp32');
				define('PHPBB_RA_GAME', 'v1game');
				define('OLYMPUS_GAME', 'v1game');
				define('PHPBBARCADE_GAME', 'phpbb');
				define('NOSCORE_GAME', 'no_scoring');
				define('AR_GAME', 'v1game');
			}

			@require($mainPhpFileFind);
			foreach ($game_data as $key => $info)
			{
				if (!empty($info))
					$config[$key] = un_htmlspecialchars($info);

				$x++;
			}

			$htmlType = !empty($config['game_type']) ? $config['game_type'] : '';
			if (!empty($config['game_control']))
				$game['help'] = $config['game_control'];
			if (!empty($config['game_control_desc']))
				$game['help'] = !empty($game['help']) ? $game['help'] . ' | ' . $config['game_control_desc'] : $config['game_control_desc'];
			if (!empty($config['game_desc']))
				$game['description'] = $config['game_desc'];
			if (!empty($config['game_name']))
				$game['name'] = ArcadeSpecialChars($config['game_name'], 'name');
			if (!empty($config['gtitle']))
				$game['name'] = ArcadeSpecialChars($config['gtitle'], 'name');
			if (!empty($config['gname']))
				$game['file'] = ArcadeSpecialChars($config['gname'], 'name');
			if (!empty($config['game_scorevar']))
				$game['id'] = ArcadeSpecialChars($config['game_scorevar'], 'name');
			if (!empty($config['game_width']) && is_numeric($config['game_width']))
				$game['flash']['width'] = (int)$config['game_width'];
			if (!empty($config['game_height']) && is_numeric($config['game_height']))
				$game['flash']['height'] = (int)$config['game_height'];
			if (!empty($config['game_image']) && file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $config['game_image']))
				$game['thumbnail'] = $config['game_image'];
			$game['flash']['type'] = '';
			if (!empty($config['game_save_type']) && in_array($config['game_save_type'], array('auto', 'v1game', 'v2game', 'v3game', 'pnflash', 'silver', 'custom_game', 'phpbb', 'ibp', 'ibp3', 'ibp32', 'html5', 'html52', 'html53', 'v3arcade', 'mochi')))
				$game['submit'] = $config['game_save_type'];
			if ($htmlType == 'html52')
				$game['submit'] = 'html52';
			if ($htmlType == 'html53')
				$game['submit'] = 'html53';
			if (!empty($config['game_bgcolor']) && strlen($config['game_bgcolor']) == 6)
			{
				$game['flash']['background_color'] = array(
					hexdec(mb_substr($config['game_bgcolor'], 0, 2)),
					hexdec(mb_substr($config['game_bgcolor'], 2, 2)),
					hexdec(mb_substr($config['game_bgcolor'], 4, 2))
				);
			}
			else
			{
				$game['extra_data']['background_color'] = array(
					hexdec('00'),
					hexdec('00'),
					hexdec('00')
				);
			}

			if (!empty($config['game_image']))
				$game['thumbnail'] = $config['game_image'];
			if (!empty($config['game_image']))
				$game['thumbnail_small'] = $config['game_image'];
			$game['id'] = str_replace(array(' '), array('_'), ArcadeSpecialChars($name, 'name'));
			//$game['name'] = !empty($config['name']) ? $config['name'] : ArcadeSpecialChars($name, 'name');
			$game['scoring'] = 0;
			if (!empty($config['game_scoretype']))
			{
				$tempType = floatval($config['game_scoretype']);
				if ($tempType == 2)
					$game['scoring'] = 1;
			}
			if (!empty($config['game_save_type']) && $config['game_save_type'] == 'no_scoring')
				$game['scoring'] = 2;

			if (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/index.html'))
			{
				$game['file'] = 'index.html';
				$game['submit'] = 'html52';
			}
			elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $name . '.html'))
			{
				$game['file'] = $name . '.html';
				$game['submit'] = 'html52';
			}
			elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/gamedata/' . $name . '/index.html'))
			{
				$game['file'] = 'gamedata/' . $name . '/index.html';
				$game['submit'] = 'html52';
			}
			elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/gamedata/' . $name . '/' . $name . '.html'))
			{
				$game['file'] = 'gamedata/' . $name . '/' . $name . '.html';
				$game['submit'] = 'html52';
			}
			elseif (!empty($config['game_type']) && $config['game_type'] == 'html52')
			{
				$game['file'] = $name . '.html';
				$game['submit'] = 'html52';
			}
			else
			{
				$game['file'] = $name . '.swf';
				if (!empty($config['game_swf']))
				{
					$file = ArcadeSpecialChars($config['game_swf'], 'name');
					if (strlen($file) > 4 && substr($file, -4) == '.swf' && file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $file))
						$game['file'] = $file;
				}
			}

			$game['flash']['version'] = 6;
		}

		// ibp game types
		if (!$phpbb && strpos(str_replace(' ', '', $file), '$config=array(') !== false)
		{
			@require($mainPhpFileFind);
			foreach ($game_info as $info)
			{
				if (!empty($config[$info]))
				{
					$config[$info] = un_htmlspecialchars($config[$info]);
				}
				$x++;
			}

			if (!empty($config['gkeys']))
				$game['help'] = $config['gkeys'];

			if (!empty($config['gwords']))
				$game['description'] = $config['gwords'];
			if (!empty($config['gname']))
				$game['file'] = $config['gname'];
			if (!empty($config['gtitle']))
				$game['name'] = ArcadeSpecialChars($config['gtitle'], 'name');
			if (!empty($config['gwords']))
				$game['help'] = $config['gwords'];
			if (!empty($config['gwidth']) && is_numeric($config['gwidth']))
				$game['flash']['width'] = (int)$config['gwidth'];
			if (!empty($config['gheight']) && is_numeric($config['gheight']))
				$game['flash']['height'] = (int)$config['gheight'];
			if (!empty($config['gtype']))
				$game['flash']['type'] = ArcadeSpecialChars($config['gtype'], 'name');
			if (!empty($config['savetype']) && in_array($config['savetype'], array('auto', 'v1game', 'v2game', 'v3game', 'pnflash', 'silver', 'custom_game', 'phpbb', 'ibp', 'ibp3', 'ibp32', 'html5', 'html52', 'html53', 'v3arcade', 'mochi')))
				$game['submit'] = ArcadeSpecialChars($config['savetype'], 'name');
			if (!empty($config['bgcolor']) && strlen($config['bgcolor']) == 6)
			{
				$game['flash']['background_color'] = array(
					hexdec(mb_substr($config['bgcolor'], 0, 2)),
					hexdec(mb_substr($config['bgcolor'], 2, 2)),
					hexdec(mb_substr($config['bgcolor'], 4, 2))
				);
			}
			else
			{
				$game['extra_data']['background_color'] = array(
					hexdec('00'),
					hexdec('00'),
					hexdec('00')
				);
			}

			if (!empty($config['thumbnail']))
				$game['thumbnail'] = $config['thumbnail'];
			if (!empty($config['thumbnail_small']))
				$game['thumbnail_small'] = $config['thumbnail_small'];
			$game['id'] = !empty($config['id']) ? $config['id'] : str_replace(array(' '), array('_'), ArcadeSpecialChars($name, 'name'));
			// ?
			$game['name'] = !empty($game['name']) ? $game['name'] : (!empty($config['name']) ? $config['name'] : ArcadeSpecialChars($name, 'name'));
			$game['scoring'] = !empty($config['scoring']) ? $config['scoring'] : '0';
			if (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/index.html'))
			{
				$game['file'] = 'index.html';
				$game['submit'] = 'html5';
			}
			elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $name . '.html'))
			{
				$game['file'] = $name . '.html';
				$game['submit'] = 'html5';
			}
			elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/gamedata/' . $name . '/index.html'))
			{
				$game['file'] = 'gamedata/' . $name . '/index.html';
				$game['submit'] = 'html52';
			}
			elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/gamedata/' . $name . '/' . $name . '.html'))
			{
				$game['file'] = 'gamedata/' . $name . '/' . $name . '.html';
				$game['submit'] = 'html52';
			}
			else
				$game['file'] = $name . '.swf';

			$game['flash']['version'] = 6;
		}
	}

	if (empty($game['submit']))
	{
		if (file_exists($directory . '/gamedata/' . $name . '/index.html') || file_exists($directory . '/gamedata/' . $name . '/' . $name . '.html'))
			$game['submit'] = 'html52';
		elseif (file_exists($directory . '/index.html') || file_exists($directory . '/' . $name . '.html'))
			$game['submit'] = 'html5';
		elseif (file_exists($directory . '/gamedata/' . $name . '/v32game.txt'))
			$game['submit'] = 'ibp32';
		elseif (file_exists($directory . '/gamedata/' . $name . '/v3game.txt'))
			$game['submit'] = 'ibp3';
		elseif (file_exists($directory . '/' . $name . '.xap'))
			$game['submit'] = 'silver';
		elseif (file_exists($directory . '/' . $name . '.ini'))
			$game['submit'] = 'pnflash';
		elseif (file_exists($directory . '/' . 'size.txt'))
			$row['submit_system'] = 'phpbb';
		elseif (file_exists($directory . '/' . $name . '.php'))
		{
			$game['submit'] = 'ibp';
		}
		else
			$game['submit'] = 'v1game';
	}

	// Ensure game icons are set if they exist
	$imageArray = array('gif', 'png', 'jpg');
	foreach ($imageArray as $type)
	{
		if (empty($game['thumbnail']))
		{
			if (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $name . '1.' . $type))
				$game['thumbnail'] = $name . '1.' . $type;
			elseif (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $name . '.' . $type))
				$game['thumbnail'] = $name . '.' . $type;
		}

		if (empty($game['thumbnail_small']))
		{
			if (file_exists($modSettings['gamesDirectory'] . '/' . $directory . '/' . $name . '2.' . $type))
				$game['thumbnail_small'] = $name . '2.' . $type;
		}
	}
	$game['thumbnail'] = !empty($game['thumbnail']) ? $game['thumbnail'] : $name . '.png';
	$game['thumbnail_small'] = !empty($game['thumbnail_small']) ? $game['thumbnail_small'] : $game['thumbnail'];

	$game['thumbnail'] = is_array($game['thumbnail'])? $game['thumbnail'][0] : $game['thumbnail'];
	$game['thumbnail_small'] = is_array($game['thumbnail_small']) ? $game['thumbnail_small'][0] : $game['thumbnail_small'];

	return $game;
}

function check_empty_folder($folder)
{
	if(is_dir($folder))
	{
		$files = array();
		if ($handle = opendir($folder))
		{
			while (false !== ($file = readdir($handle)))
			{
				if ($file != "." && $file != "..")
					$files [] = $file;
			}
			closedir ($handle);
		}
	}

	return (count($files) > 0) ? FALSE : TRUE;
}

function getGameName($internal_name)
{
	global $smcFunc;

	$internal_name = str_replace(array('_', '-'), ' ', $internal_name);

	if (strtolower(mb_substr($internal_name, -2)) == 'ch' || strtolower(mb_substr($internal_name, -2)) == 'gc')
		$internal_name = mb_substr($internal_name, 0, strlen($internal_name) - 2);
	elseif (strtolower(mb_substr($internal_name, -2)) == 'v2')
		$internal_name = mb_substr($internal_name, 0, strlen($internal_name) - 2) . ' v2';

	$internal_name = trim(str_replace(array('/', '\\'), array('', ''), trim($internal_name, '.')));
	return ucwords($internal_name);
}

function getInternalName($file, $directory)
{
	if (is_dir($directory . '/' . $file))
	{
		if (file_exists($directory . '/' . $file . '/game-info.xml'))
		{
			$gameinfo = readGameInfo($directory . '/' . $file . '/game-info.xml');
			return $gameinfo['id'];
		}
		else
			return $file;
	}

	$pos = strrpos($file, '.');

	if ($pos === false)
		return $file;

	return mb_substr($file, 0, $pos);
}

function isGame($file, $directory)
{
	// single file game?
	if (!is_dir($directory . '/' . $file) && mb_substr($file, -3) == 'swf')
		return array(true, $directory, array('file' => $file));
	// game directory?
	elseif (is_dir($directory . '/' . $file))
	{
		if (file_exists($directory . '/' . $file . '/' . $file . '.swf'))
			return array(
				true,
				$directory . '/' . $file,
				array('file' => $file . '.swf')
			);
		elseif (file_exists($directory . '/' . $file . '/' . $file . '.html'))
			return array(
				true,
				$directory . '/' . $file,
				array('file' => $file . '.html')
			);
		elseif (file_exists($directory . '/' . $file . '/' . $file . '.xap'))
			return array(
				true,
				$directory . '/' . $file,
				array('file' => $file . '.xap')
			);
		elseif (file_exists($directory . '/' . $file . '/' . $file . '.php') && file_exists($directory . '/' . $file . '/gamedata/' . $file . '/index.html'))
			return array(
				true,
				$directory . '/' . $file,
				array('file' => 'gamedata/' . $file . '/index.html')
			);
		elseif (file_exists($directory . '/' . $file . '/' . $file . '.php') && file_exists($directory . '/' . $file . '/gamedata/' . $file . '/index.php'))
			return array(
				true,
				$directory . '/' . $file,
				array('file' => 'gamedata/' . $file . '/index.php')
			);
		elseif (file_exists($directory . '/' . $file . '/' . $file . '.php'))
			return array(
				true,
				$directory . '/' . $file,
				array('file' => $file . '.php')
			);
		elseif (file_exists($directory . '/' . $file . '/game-info.xml'))
			return array(
				true,
				$directory . '/' . $file,
				readGameInfo($directory . '/' . $file . '/game-info.xml')
			);
	}
	elseif (file_exists($directory . '/' . $file . '.php'))
		return array(
			true,
			$directory,
			array('file' => $file . '.html')
		);
	elseif (file_exists($directory . '/gamedata/' . $file . '.html'))
		return array(
			true,
			$directory,
			array('file' => 'gamedata/' . $file . '.html')
		);
	elseif (file_exists($directory . '/index.html'))
		return array(
			true,
			$directory,
			array('file' => 'index.html')
		);
	elseif (file_exists($directory . '/gamedata/index.html'))
		return array(
			true,
			$directory,
			array('file' => 'gamedata/index.html')
		);

	if (substr($file, -9) == '.htaccess' || substr($file, -9) == 'index.php')
		return array(false, false, false);

	return array(false, false, false);
}

function getAvailableGames($subpath = '', $recursive = true)
{
	global $modSettings, $filesDirArc;

	if (mb_substr($subpath, -1) == '/')
		$subpath = mb_substr($subpath, 0, -1);

	$directory = $modSettings['gamesDirectory'] . (!empty($subpath) ? '/' . $subpath : '');
	$games = array();
	$filesDirArc = !empty($filesDirArc) ? $filesDirArc : array();

	if ($subpath != '' && $recursive == 'unpack')
	{
		list ($is_game, $gdir, $extra) = isGame(basename($subpath), dirname($directory));

		if ($is_game)
		{
			$gdir_rel = mb_substr($gdir, strlen($modSettings['gamesDirectory']));

			if (mb_substr($gdir_rel, 0, 1) == '/')
				$gdir_rel = mb_substr($gdir_rel, 1);

			$games[] = array(
				'type' => 'game',
				'directory' => $gdir_rel,
				'filename' => $extra['file'],
			);
			$filesDirArc[] = $extra['file'];

			return $games;
		}
	}

	$recursive = (bool) $recursive;
	if (is_dir($directory) && $directoryHandle = opendir($directory))
	{
		while ($file = readdir($directoryHandle))
		{
			if ($file == '.' || $file == '..')
				continue;

			list ($is_game, $gdir, $extra) = isGame($file, $directory);

			if ($is_game)
			{
				$gdir_rel = mb_substr($gdir, strlen($modSettings['gamesDirectory']));

				if (mb_substr($gdir_rel, 0, 1) == '/')
					$gdir_rel = mb_substr($gdir_rel, 1);

				$games[] = array(
					'type' => 'game',
					'directory' => $gdir_rel,
					'filename' => $extra['file'],
				);

				$filesDirArc[] = $extra['file'];
			}
			elseif ($recursive)
			{
				$games = array_merge($games, getAvailableGames((!empty($subpath) ? $subpath . '/' : '') . $file, false));
				$filesDirArc[] = $file;
			}

			unset($is_game, $gdir, $extra);
		}
		closedir($directoryHandle);
	}

	return $games;
}

function updateGameCache($saveType = '')
{
	global $scripturl, $txt, $db_prefix, $modSettings, $context, $sourcedir, $smcFunc, $boarddir;

	// Clear entries
	$smcFunc['db_query']('truncate_table', '
		TRUNCATE {db_prefix}arcade_files'
	);

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

	// Try to get more memory
	@ini_set('memory_limit', '128M');

	// Do actual update
	gameCacheInsertGames(getAvailableGames(), $saveType);

	updateSettings(array('arcadeDBUpdate' => time()));
	cache_put_data('arcade_cats', null, 604800);
}

function gameCacheInsertGames($games, $type = '', $return = false)
{
	global $scripturl, $txt, $db_prefix, $modSettings, $context, $sourcedir, $smcFunc, $boarddir, $boardurl;

	list($filesAvailable, $filesKeys, $filesDirArc, $fileComps, $fileName, $fileId) = array(array(), array(), array(), array(), array(), 0);
	if (is_dir($modSettings['gamesDirectory']) && $handle = opendir($modSettings['gamesDirectory']))
	{
		while (false !== ($file = readdir($handle)))
		{
			if ($file != "." && $file != ".." && in_array(substr($file, -3), array('rar', 'zip', 'tar', '.gz')) && !in_array($file, $filesDirArc))
			{
				foreach (array('.gz', '.rar', '.zip', '.tar') as $ext)
					$internalName = rtrim($file, $ext);

				$fileComps[$fileId] = str_replace('\\', '/', $internalName);
				$fileName[$fileId] = str_replace('\\', '/', $file);
			}
			$fileId++;
		}
		closedir($handle);
	}
	foreach ($games as $id => $game)
	{
		if (!empty($game['directory']) && is_dir(str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $game['directory'])))
		{
			$search = str_replace('\\', '/', $game['directory']);
			if (in_array($search, $fileComps))
			{
				$key = array_search ($search, $fileComps);
				$fileDel = str_replace('\\', '/',  $fileName[$key]);
				if (file_exists(str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $fileDel)))
					unlink(str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $fileDel));
			}
		}

		if ($game['type'] == 'game')
		{
			if (!empty($game['directory']))
			{
				$game_directory = str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $game['directory']);
				$game_file = str_replace('\\', '/', $game_directory . '/' . $game['filename']);
			}
			else
			{
				$game_directory = str_replace('\\', '/', $modSettings['gamesDirectory']);
				$game_file = str_replace('\\', '/', $game['filename']);
			}

			$filesAvailable[$game_file] = $id;
			$filesKeys[$game_file] = $id;

			// Move gamedata file for IBP arcade games
			if (file_exists($game_directory . '/gamedata') && mb_substr($game['filename'], -3) == 'swf')
			{
				$from = $game_directory . '/gamedata';
				$to = $boarddir . '/arcade/gamedata/' . mb_substr($game['filename'], 0, -4);

				if (!file_exists($boarddir . '/arcade/') && !mkdir($boarddir . '/arcade/', 0755))
					fatal_lang_error('unable_to_make', false, array($boarddir . '/arcade/'));
				if (!file_exists($boarddir . '/arcade/gamedata/') && !mkdir($boarddir . '/arcade/gamedata/', 0755))
					fatal_lang_error('unable_to_make', false, array($boarddir . '/arcade/gamedata/'));
				if (!file_exists($to) && !mkdir($to, 0755))
					fatal_lang_error('unable_to_make', false, array($to));
				elseif (!is_dir($to))
					fatal_lang_error('unable_to_make', false, array($to));

				if (!is_writable($to))
					fatal_lang_error('unable_to_chmod', false, array($to));

				copyArcadeDirectory($from, $boarddir . '/arcade/gamedata');
				deleteArcadeArchives($from);

				if (!@file_exists($to))
					fatal_lang_error('unable_to_move', false, array($from, $to));
			}
			elseif (file_exists($game_directory . '/gamedata'))
			{
				$from = $game_directory . '/gamedata';
				$dirs = str_replace('\\', '/', $game_directory);
				$allDirs = explode('/', $dirs);
				$dir = count($allDirs)-1;
				$to = $boarddir . '/arcade/gamedata/' . $allDirs[$dir];

				if (file_exists($game_directory . '/gamedata/' . $allDirs[$dir] . '/index.html'))
				{
					$filez = file_get_contents($game_directory . '/gamedata/' . $allDirs[$dir] . '/index.html');
					if (strpos($filez, 'function ajax2') !== false)
					{
						if (!file_exists($boarddir . '/arcade/') && !mkdir($boarddir . '/arcade/', 0755))
							fatal_lang_error('unable_to_make', false, array($boarddir . '/arcade/'));
						if (!file_exists($boarddir . '/arcade/gamedata/') && !mkdir($boarddir . '/arcade/gamedata/', 0755))
							fatal_lang_error('unable_to_make', false, array($boarddir . '/arcade/gamedata/'));
						if (!file_exists($to) && !mkdir($to, 0755))
							fatal_lang_error('unable_to_make', false, array($to));
						elseif (!is_dir($to))
							fatal_lang_error('unable_to_make', false, array($to));

						if (!is_writable($to))
							fatal_lang_error('unable_to_chmod', false, array($to));

						copyHtml52ArcadeDirectory($from, $boarddir . '/arcade/gamedata', $to);

						if (!@file_exists($to))
							fatal_lang_error('unable_to_move', false, array($from, $to));
					}
				}
			}
		}
	}

	// Installed games
	$request = $smcFunc['db_query']('', '
		SELECT id_game, game_name, internal_name, game_file, game_directory
		FROM {db_prefix}arcade_games'
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		if (!empty($row['game_directory']))
		{
			$game_file = str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $row['game_directory'] . '/' . $row['game_file']);
			$game_directory = str_replace('\\', '/', $row['game_directory']);
		}
		else
		{
			$game_file = str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $row['game_file']);
			$game_directory = '';
		}

		if (file_exists($game_file) && !empty($filesKeys[$game_file]))
		{
			$games[$filesKeys[$game_file]] += array(
				'type' => 'game',
				'id' => $row['id_game'],
				'name' => $row['game_name'],
				'directory' => $game_directory,
				'filename' => $row['game_file'],
				'internal_name' => $row['internal_name'],
				'installed' => true,
				'missing_files' => false,
				'compressed' => false,
			);

			$filesDirArc[] = $row['internal_name'];
		}
		elseif (file_exists($game_file))
		{
			$games[] = array(
				'type' => 'game',
				'id' => $row['id_game'],
				'name' => $row['game_name'],
				'directory' => $game_directory,
				'filename' => $row['game_file'],
				'internal_name' => $row['internal_name'],
				'installed' => true,
				'missing_files' => false,
				'compressed' => false,
			);

			$filesDirArc[] = $row['internal_name'];
		}
		else
		{
			$fileKeys[$game_file] = count($games);

			$games[] = array(
				'type' => 'game',
				'id' => $row['id_game'],
				'name' => $row['game_name'],
				'directory' => $game_directory,
				'filename' => $row['game_file'],
				'internal_name' => $row['internal_name'],
				'missing_files' => true,
				'compressed' => false,
			);

			$filesDirArc[] = $row['internal_name'];
		}
	}
	$smcFunc['db_free_result']($request);

	// check for compressed archives
	if (is_dir($modSettings['gamesDirectory']) && $handle = opendir($modSettings['gamesDirectory']))
	{
		while (false !== ($file = readdir($handle)))
		{
			if ($file != "." && $file != ".." && in_array(substr($file, -3), array('rar', 'zip', 'tar', '.gz')) && !in_array($file, $filesDirArc))
			{
				foreach (array('.gz', '.rar', '.zip', '.tar') as $ext)
					$internalName = rtrim($file, $ext);

				if (!in_array($internalName, $filesDirArc))
				{
					$games[] = array(
						'type' => 'gamepackage-multi',
						'directory' => '',
						'filename' => $file,
						'compressed' => true,
					);
				}
				elseif (file_exists(str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $file)))

				$filesDirArc[] = str_replace('\\', '/', $internalName);

			}
		}
		closedir($handle);
	}

	list($rows, $allDirs) = array(array(), array());
	// Last step
	foreach ($games as $id => $game)
	{
		$masterInfo = array();
		if (!empty($game['directory']))
		{
			$game_directory = str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $game['directory']);
			$game_file = str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $game['directory'] . '/' . $game['filename']);
		}
		else
		{
			$game_directory = str_replace('\\', '/', $modSettings['gamesDirectory']);
			$game_file = str_replace('\\', '/', $modSettings['gamesDirectory'] . '/' . $game['filename']);
		}

		// Regular game?
		if ($game['type'] == 'game')
		{
			// Use game info if possible
			if (file_exists($game_directory . '/game-info.xml') && !isset($game['gameinfo']))
				$gameinfo = readGameInfo($game_directory . '/game-info.xml');
		}
		// Single zipped game?
		elseif ($game['type'] == 'gamepackage')
		{
			$gameinfo = read_tgz_data(file_get_contents($game_file), 'game-info.xml', true);
			$gameinfo = new xmlArray($gameinfo);
			$gameinfo = $gameinfo->path('game-info[0]');
			$gameinfo = $gameinfo->to_array();
		}
		// Gamepackage
		elseif ($game['type'] == 'gamepackage-multi')
		{
			if (strrpos($game['filename'], 'index.html') !== false || strrpos($game['filename'], 'index.php') !== false && !empty($game_directory))
				$game['name'] = 'GamePack ' . basename($game_directory);
			else
				$game['name'] = 'GamePack ' . mb_substr($game['filename'], 0, strrpos(rtrim($game['filename'], '.gz'), '.'));
		}

		if (isset($gameinfo) && !isset($game['name']))
			$game['name'] = $gameinfo['name'];
		elseif (!isset($game['name']))
		{
			if (strrpos($game['filename'], 'index.html') !== false || strrpos($game['filename'], 'index.php') !== false && !empty($game_directory))
				$game['name'] = basename($game_directory);
			else
				$game['name'] = getGameName(getInternalName($game['filename'], $game_directory));
		}

		// Status of game
		$status = 10;

		// check if flagged incorrectly
		if($id == 0)
		{
			$request = $smcFunc['db_query']('', '
				SELECT id_game, game_name, internal_name, game_file, game_directory
				FROM {db_prefix}arcade_games
				WHERE game_file = {string:file} && game_directory = {string:directory}
				LIMIT 1',
				array('file' => $game['filename'], 'directory' => $game['directory'])
			);

			while ($row = $smcFunc['db_fetch_assoc']($request))
				$status = 1;

			$smcFunc['db_free_result']($request);
		}

		if (!empty($game['missing_files']))
			$status = 2;
		elseif (!empty($game['installed']))
			$status = 1;

		if (!isset($game['id']))
			$game['id'] = 0;

		if (!isset($game['directory']))
			$game['directory'] = '';

		if (!isset($game['filename']))
			$game['filename'] = '';

		if (!empty($game['compressed']))
			$status = 10;

		// Escape data to be inserted into database
		$rows[] = array(
			$game['id'],
			$game['type'],
			$game['name'],
			$status,
			$game['filename'],
			$game['directory'],
			!empty($type) ? $type : '',
		);

		unset($gameinfo);
	}

	// check if pending installations failed to be included likely due to file name mismatch (only xml or php config file can fix this)
	$getPaths = arcadeReturnPaths($modSettings['gamesDirectory']);
	foreach ($rows as $row)
		$allDirs[] = $row[5];

	foreach ($getPaths as $path)
	{
		$thisx = trim($path, '/');
		$thisx = trim($path, '\\');
		$thisx = arcadeFixPath($thisx);
		$files = array_diff(scandir($modSettings['gamesDirectory'] . '/' . $thisx), array('..', '.'));

		if (!in_array($thisx, $allDirs))
		{
			$mainFileFind = '';
			foreach ($files as $file)
			{
				$info = new SplFileInfo($file);
				$ext = ($info->getExtension());
				if ($ext == 'php' && $file != 'index.php')
				{
					$mainFileFind = $modSettings['gamesDirectory'] . '/' . $thisx . '/' . $file;
					break;
				}

				if ($ext == 'xml' && $file == 'game-info.xml')
				{
					$mainFileFind = $modSettings['gamesDirectory'] . '/' . $thisx . '/' . $file;
					break;
				}
			}

			if (!empty($mainFileFind) && file_exists($mainFileFind))
			{
				$flag = false;
				$gameinfo = array();
				if ($ext == 'php')
				{
					$file = file_get_contents($mainFileFind);
					if (strpos(str_replace(' ', '', $file), '$config=array(') !== false)
						@require($mainFileFind);
					$name = basename($mainFileFind, '.php');
				}
				else
				{
					$gameinfo = readGameInfo($mainFileFind);
					$name = !isset($gameinfo['id']) ? $gameinfo['id'] : '';
				}

				if (!empty($gameinfo) && $thisx != $name && !is_dir($modSettings['gamesDirectory']. '/' . $name) && is_dir($modSettings['gamesDirectory']. '/' . $thisx))
				{
					@chmod($modSettings['gamesDirectory'] . '/' . $thisx, 0755);
					$rename = copyArcadeDirectory($modSettings['gamesDirectory'] . '/' . $thisx, $modSettings['gamesDirectory'] . '/' . $name);
					if (is_dir($modSettings['gamesDirectory']. '/' . $name))
					{
						arcadeRmdir($modSettings['gamesDirectory'] . '/' . $thisx);
					}
					else
						continue;

					if (substr($mainFileFind, -4) == '.php')
					{
						$gameinfo = readPhpGameInfo($name, $name);
					}

					$y = 0;
					foreach($rows as $checkRow)
					{
						if ($checkRow[5] == $thisx)
							$rows[$y] = array();
						$y++;
					}

					$new[] = array(
						0,
						'game',
						$name,
						10,
						$gameinfo['file'],
						arcadeFixPath($name),
						$gameinfo['submit'],
					);

					$smcFunc['db_insert']('insert',
						'{db_prefix}arcade_files',
						array(
							'id_game' => 'int',
							'file_type' => 'string-30',
							'game_name' => 'string-255',
							'status' => 'int',
							'game_file' => 'string-255',
							'game_directory' => 'string-255',
							'submit_system' => 'string-255',
						),
						$new,
						array('id_file')
					);
					$count = 0;
					$request = $smcFunc['db_query']('', '
						SELECT id_file
						FROM {db_prefix}arcade_files
						ORDER BY id_file DESC
						LIMIT 1',
						array()
					);

					while ($row = $smcFunc['db_fetch_assoc']($request))
						$count = $row['id_file'];

					$smcFunc['db_free_result']($request);
					$gamesx[] = $count;
				}
			}
		}
	}

	if (!empty($rows))
		$smcFunc['db_insert']('insert',
			'{db_prefix}arcade_files',
			array(
				'id_game' => 'int',
				'file_type' => 'string-30',
				'game_name' => 'string-255',
				'status' => 'int',
				'game_file' => 'string-255',
				'game_directory' => 'string-255',
				'submit_system' => 'string-255',
			),
			$rows,
			array('internal_name')
		);

	if (!empty($gamesx))
	{
		$_POST['file'] = $gamesx;
		$_POST[$context['session_var']] = $context['session_id'];
		ManageGamesInstall2();
		$_POST['file'] = array();
		//$context['qaction_data'] = installgames($gamesx, false);
		//$_SESSION['qaction_data'] = $context['qaction_data'];
		//redirectexit('action=admin;area=managegames;sa=install2;sesc=' . $context['session_id']);
	}
	else
	{
		unset($_SESSION['qaction']);
		unset($_SESSION['qaction_data']);
	}

	if ($return)
		return $rows;
}

function arcadeGetGroups($selected = array())
{
	global $smcFunc, $txt, $sourcedir, $context;

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

	$return = array();

	// Default membergroups.
	$return = array(
		-2 => array(
			'id' => '-2',
			'name' => $txt['arcade_group_arena'],
			'checked' => $selected == 'all' || in_array('-2', $selected),
			'is_post_group' => false,
		),
		-1 => array(
			'id' => '-1',
			'name' => $txt['guests'],
			'checked' => $selected == 'all' || in_array('-1', $selected),
			'is_post_group' => false,
		),
		0 => array(
			'id' => '0',
			'name' => $txt['regular_members'],
			'checked' => $selected == 'all' || in_array('0', $selected),
			'is_post_group' => false,
		)
	);

	$groups = groupsAllowedTo('arcade_view');

	if (!in_array(-1, $groups['allowed']))
		unset($context['groups'][-1]);
	if (!in_array(0, $groups['allowed']))
		unset($context['groups'][0]);

	// Load membergroups.
	$request = $smcFunc['db_query']('', '
		SELECT mg.group_name, mg.id_group, mg.min_posts
		FROM {db_prefix}membergroups AS mg
		WHERE mg.id_group > 3 OR mg.id_group = 2
			AND mg.id_group IN({array_int:groups})
		ORDER BY mg.min_posts, mg.id_group != 2, mg.group_name',
		array(
			'groups' => $groups['allowed'],
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$return[(int) $row['id_group']] = array(
			'id' => $row['id_group'],
			'name' => trim($row['group_name']),
			'checked' => $selected == 'all' ||  in_array($row['id_group'], $selected),
			'is_post_group' => $row['min_posts'] != -1,
		);
	}
	$smcFunc['db_free_result']($request);

	return $return;
}

function postArcadeGames($game, $gameid)
{
	global $user_info, $arcSettings, $scripturl, $sourcedir, $modSettings, $boardurl, $txt, $settings, $smcFunc;

	// SMF 2.1.X behavior will differ
	$version = version_compare((!empty($modSettings['smfVersion']) ? substr($modSettings['smfVersion'], 0, 3) : '2.0'), '2.1', '<') ? 'v2.0' : 'v2.1';
	$start = $version == 'v2.1' ? '[html]' : '';
	$end = $version == 'v2.1' ? '[/html]' : '';

	loadLanguage('Arcade');
	$ranum = (RAND(1,1255));
	$gameid = !empty($gameid) ? (int)$gameid : 0;
	if (empty($modSettings['gamesBoard']) || empty($gameid))
		return 0;

	list($my_message, $board_id, $gamename, $game_width, $game_height, $id, $description, $thumbnail, $style) = array(
		!empty($modSettings['gamesMessage']) ? $modSettings['gamesMessage'] : '',
		$modSettings['gamesBoard'],
		$game['name'],
		200,
		200,
		'x' . $gameid.$ranum . 'x',
		'&nbsp;',
		$settings['default_theme_url'] . '/images/arc_icons/popup_play_btn.gif',
		'width: 50px; height: 14px;'
	);

	$enablePostCount = !empty($modSettings['arcadeEnablePostCount']) ? 'always' : 'never';
	$dimension = !empty($game['extra_data']) ? $game['extra_data'] : array();
	$gamefile_name = !empty($game['game_file']) ? $game['game_file'] : '';
	$gamename_name = !empty($game['name']) ? $game['name'] : '';
	$internal = !empty($game['internal_name']) ? $game['internal_name'] : '';
	$gamedirectory = !empty($game['game_directory']) ? $game['game_directory'] : '';
	$game_pic = !empty($game['thumbnail']) ? $game['thumbnail'] : '';
	$game_width =  !empty($dimension['width']) ? (int)$dimension['width'] : 400;
	$game_height = !empty($dimension['height']) ? (int)$dimension['height'] : 400;
	$help = !empty($game['help']) ? $txt['arcade_post_help'] . wordwrap($game['help'], 140, "<br />") : '&nbsp;';
	$description = !empty($game['description']) ? $txt['arcade_post_description'] . wordwrap($game['description'], 140, "<br />") : '&nbsp;';
	$directory = $modSettings['gamesDirectory'] . (!empty($gamedirectory) ? '/' . $gamedirectory : '');

	if (!empty($game_pic) && @file_exists($directory . '/' . $game_pic))
	{
		$thumbnail = $modSettings['gamesUrl'] . '/' . (!empty($gamedirectory) ? $gamedirectory . '/' : '') . $game_pic;
		$style = "width: 50px;height: 50px;";
	}
	else
	{
		$thumbnail = $settings['default_theme_url'] . '/images/arc_icons/game.gif';
		$style = "width: 50px;height: 50px;";
	}
	$popup = $start . '<a href="javascript:void(0)" onclick="return myGamePopupArcade(smf_prepareScriptUrl(smf_scripturl)+\'action=arcade;sa=play;game=' . $gameid . ';pop=1\',' . $game_width . ',' . $game_height . ',3);"><img style="' . $style . '" src="' . $thumbnail . '" alt="' . $txt['pdl_popplay'] . '" title="' . $txt['pdl_popplay'] . '" /></a>' . $end;
	require_once($sourcedir . '/Subs-Post.php');
	$topicTalk = '[center][b][url='.$scripturl.'?action=arcade;sa=play;game='.$gameid.']' . str_replace('%#@$', ' [i]' . $gamename . '[/i]', $txt['arcade_post']) . '[/url][/b][/center]';

	if (empty($modSettings['arcadeEnableDownload']))
		$modSettings['arcadeEnableDownload'] = false;

	if (empty($modSettings['arcadeEnableIframe']))
		$modSettings['arcadeEnableIframe'] = false;

	if (empty($modSettings['arcadePosterid']))
		$modSettings['arcadePosterid'] = $user_info['id'];

	if ($modSettings['arcadePosterid'] < 1)
		$modSettings['arcadePosterid'] = 0;

	if ($modSettings['arcadeEnableDownload'] == true)
		$topicTalk .= $start . '<br /><center><a style="color: red;text-decoration: none;" href="' . $scripturl . '?action=arcade;sa=download;game=' . $gameid . '"><img src="' . $settings['default_theme_url'] . '/images/arc_icons/dl_btn_popup.png" alt="' . $txt['arcade_download_game'] . '" title="' . $txt['arcade_download_game'] . '" /></a></center>' . $end;

	if ($modSettings['arcadeEnableIframe'] == true)
	{
		$topicTalk .= '
		[center]' . $popup . '[/center]' . $start . '
			<center>
				<p id="' . $id . '">' . $help . '<br /><br />' . $description . '</p>
			</center>
			<div style="margin-top: 3px; text-align: center" class="smalltext">' . $txt['pdl_arcade_copyright'] . '</div>' . $end;
	}

	$topicTalk .= $my_message;

	$msgOptions = array(
		'id' => 0,
		'subject' => $gamename,
		'body' => $topicTalk,
		'icon' => "xx",
		'smileys_enabled' => true,
		'attachments' => array(),
	);
	$topicOptions = array(
		'id' => 0,
		'board' => $board_id,
		'poll' => null,
		'lock_mode' => null,
		'sticky_mode' => null,
		'mark_as_read' => true,
		'is_approved' => true,
	);
	$posterOptions = array(
		'id' => $modSettings['arcadePosterid'],
		'name' => "Arcade",
		'email' => "arcade@here.com",
		'update_post_count' => $enablePostCount,
	);

	createPost($msgOptions, $topicOptions, $posterOptions);

	if (isset($topicOptions['id']))
	{
		$topicid = $topicOptions['id'];
		$smcFunc['db_query']('', '
			UPDATE {db_prefix}arcade_games
			SET id_topic = {int:id_topic}
			WHERE id_game = {int:gameid}',
			array(
				'gameid' => $gameid,
				'id_topic' => $topicid,
			)
		);
	}

	return $topicid;
}

function copyArcadeDirectory($source, $destination)
{
	if (is_dir($source))
	{
		if (!is_dir($destination))
			@mkdir($destination);

		$directory = @dir($source);
		while (FALSE !== ($readdirectory = $directory->read()))
		{
			if ($readdirectory == '.' || $readdirectory == '..')
				continue;

			$PathDir = $source . '/' . $readdirectory;

			if (is_dir($PathDir))
			{
				copyArcadeDirectory($PathDir, $destination . '/' . $readdirectory);
				continue;
			}
			copy($PathDir, $destination . '/' . $readdirectory);
		}

		$directory->close();
	}
	elseif (@file_exists($source) && !@file_exists($destination))
		@copy($source, $destination);
	else
		return false;

	return true;
}

function copyHtml52ArcadeDirectory($source, $destination, $dest2)
{
	if (is_dir($source))
	{
		$destination = str_replace('\\', '/', $destination);
		$dirs = explode('/', $destination);
		$countDirs = count($dirs)-2;
		if (!is_dir($destination) && $dirs[$countDirs] == 'gamedata')
			@mkdir($destination, 0755);

		$directory = @dir($source);
		while (FALSE !== ($readdirectory = $directory->read()))
		{
			if ($readdirectory == '.' || $readdirectory == '..')
				continue;

			$PathDir = $source . '/' . $readdirectory;

			if (is_dir($PathDir))
			{
				copyHtml52ArcadeDirectory($PathDir, $destination . '/' . $readdirectory, '');
				continue;
			}
			elseif (substr($PathDir, -4) == '.txt')
				copy($PathDir, $destination . '/' . $readdirectory);
		}
		$directory->close();
		$file = @fopen($destination . '/index.html', 'w');
		@fclose($file);
	}
	elseif (@file_exists($source) && !@file_exists($destination) && substr($source, -4) == '.txt')
		@copy($source, $destination);
	else
		return false;

	return true;
}

function deleteArcadeArchives($directory)
{
	global $boardurl, $boarddir;
	$directory = mb_substr($directory,-1) == "/" ? mb_substr($directory,0,-1) : $directory;

	if (is_dir($directory))
	{
		$directoryHandle = opendir($directory);
		while ($contents = readdir($directoryHandle))
		{
			if($contents != '.' && $contents != '..')
			{
				$path = $directory . "/" . $contents;
				if (is_dir($path))
					deleteArcadeArchives($path);
				elseif (file_exists($path))
					unlink($path);
			}
		}
		closedir($directoryHandle);
		arcadeRmdir($directory);
	}
	elseif (file_exists($directory))
		unlink($directory);
	else
		return false;

	return true;
}

function ArcadeAdminScanDir($dir, $ignore = '')
{
	$arrfiles = array();
	if (is_dir($dir))
	{
		if ($handle = opendir($dir))
		{
			chdir($dir);
			while (false !== ($file = readdir($handle)))
			{
				if ($file != "." && $file != "..")
				{
					if (is_dir($file))
					{
						$arr = ArcadeAdminScanDir($file, '');
						if (!empty($arr))
							foreach ($arr as $value)
								$arrfiles[] = $dir . '/' . $value;
						else
							$arrfiles[] = $dir;
                    }
					elseif ((!empty($ignore)) && basename($file) == $ignore)
                        continue;
					else
						$arrfiles[] = $dir . '/' . $file;
				}
			}
			chdir("../");
		}
		closedir($handle);
	}

	return $arrfiles;
}

function ArcadeAdminCategoryDropdown()
{
	// Admin Category drop down menu
	global $scripturl, $smcFunc, $txt, $modSettings;
	$count = 0;
	$current = !empty($modSettings['arcadeDefaultCategory']) ? (int)$modSettings['arcadeDefaultCategory'] : 0;
	$selected = version_compare((!empty($modSettings['smfVersion']) ? mb_substr($modSettings['smfVersion'], 0, 3) : '2.0'), '2.1', '<') ? ' selected="selected"' : ' selected';
	$display = '
		<select name="cat_default" style="font-size: 100%;" onchange="JavaScript:submit()">
			<option value="">' . $txt['arcade_admin_opt_cat'] . '</option>';

	$request = $smcFunc['db_query']('', '
		SELECT id_cat, cat_name, num_games, cat_order
		FROM {db_prefix}arcade_categories
		ORDER BY cat_order',
		array()
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		$count = $row['id_cat'];
		$cat_name[$count] = $row['cat_name'];

		$display .= '
			<option value="' . $count . '"'. ($current == $count ? $selected : '') . '>' . $cat_name[$count] . '</option>';
	}

	$smcFunc['db_free_result']($request);

	$display .= '
			<option value="all"'. ($current == 0 ? $selected : '') . '>' . $txt['arcade_all'] . '</option>
		</select>';

	return $display;
}

function return_bytes($val)
{
    $val = (float)$val;
    $last = strtolower($val{strlen($val) - 1});
	switch($last)
	{
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

// unpack zipped game archives
function arcadeUnzip($src_file, $dest_dir = false, $create_zip_name_dir = true, $overwrite = true)
{
	global $sourcedir;

	if (function_exists('zip_open'))
	{
		if ($zip = zip_open($src_file))
		{
			if ($zip)
			{
				$splitter = ($create_zip_name_dir === true) ? '.' : '/';
				if ($dest_dir === false)
				{
					$dest_dir = mb_substr($src_file, 0, strrpos($src_file, $splitter)) . '/';
					$dest_dir = preg_replace( "/^(game)_(.+?)\.(\S+)$/", "\\2",  $dest_dir);
				}

				arcadeCreateDirs($dest_dir);

				while ($zip_entry = zip_read($zip))
				{
					$pos_last_slash = strrpos(zip_entry_name($zip_entry), '/');
					if ($pos_last_slash !== false)
						arcadeCreateDirs($dest_dir . mb_substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));

					if (zip_entry_open($zip,$zip_entry, 'r'))
					{
						$file_name = $dest_dir . zip_entry_name($zip_entry);
						$dir_name = dirname($file_name);

							if ($overwrite === true || ($overwrite === false && !is_file($file_name)))
							{
								$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
								@file_put_contents($file_name, $fstream);
								@chmod($file_name, 0755);
							}

						zip_entry_close($zip_entry);
					}
				}

				zip_close($zip);
			}
		}
		else
			return false;
	}
	else
	{
		require_once($sourcedir . '/Subs-Package.php');
		$splitter = ($create_zip_name_dir === true) ? '.' : '/';
		if ($dest_dir === false)
		{
			$dest_dir = mb_substr($src_file, 0, strrpos($src_file, $splitter)) . '/';
			$dest_dir = preg_replace( "/^(game)_(.+?)\.(\S+)$/", "\\2",  $dest_dir);
		}

		arcadeCreateDirs($dest_dir);
		$zip = read_zip_file($src_file, $dest_dir, false, false, null);

		if (empty($zip))
			return false;
	}

  return true;
}

// create necessary recursive directories
function arcadeCreateDirs($path)
{
	if (!is_dir($path))
	{
		$directory_path = "";
		$directories = explode("/", $path);
		array_pop($directories);

		foreach($directories as $directory)
		{
			$directory_path .= $directory . '/';
			if (!is_dir($directory_path))
			{
				@mkdir($directory_path);
				@chmod($directory_path, 0755);
			}
		}
	}
}

function arcadeRmdir($dir)
{
	global $modSettings, $boarddir;

	// linux/windows compatibility
	$gamesdir = str_replace('\\', '/', $modSettings['gamesDirectory']);
	$boarddirx = str_replace('\\', '/', $boarddir);
	$thisPath = str_replace('\\', '/', $dir);


	$gamesdir = trim($gamesdir, '/');
	$boarddirx = trim($boarddirx, '/');
	$mainPathArray = array('Sources', 'Themes', 'Packages', 'Smileys', 'cache', 'avatars', 'attachments');
	$thisPath = trim($thisPath, '/');

	// make absolutely sure the deleted path is not an essential parent path
	if ($thisPath == $boarddirx || $thisPath == $boarddirx . '/' . $gamesdir)
		return;

	foreach ($mainPathArray as $path)
	{
		if ($thisPath == $boarddirx . '/' . $path)
			return;
	}

	if (is_dir($dir))
	{
		$objects = scandir($dir);
		foreach ($objects as $object)
		{
			if ($object != '.' && $object != '..')
			{
				if (filetype($dir . '/' . $object) == 'dir')
					arcadeRmdir($dir . '/' . $object);
				else
					unlink($dir . '/' . $object);
			}
		}

		reset($objects);
		if (count(scandir($dir)) == 2)
			rmdir($dir);
	}
}

function arcadeReturnPaths($path)
{
	$folders = array();

	if ((!empty($path)) && is_dir($path))
	{
		$dir = new DirectoryIterator($path);
		foreach ($dir as $fileinfo)
		{
			if ($fileinfo->isDir() && !$fileinfo->isDot())
				$folders[] = $fileinfo->getFilename();
		}
	}

	return $folders;
}

function arcadeInternalName($internal_name)
{
	global $smcFunc;

	$internals = array();
	$request = $smcFunc['db_query']('', '
		SELECT internal_name
		FROM {db_prefix}arcade_games
		ORDER BY internal_name',
		array()
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$internals[] = $row['internal_name'];

	$smcFunc['db_free_result']($request);

	return $internals;
}

function arcadeSanitizeImg($filename = '')
{
	return preg_replace('/[^a-zA-Z0-9\-\._]/', '' , $filename);
}

function arcadeFixPath($path)
{
	$path = str_replace('\\', '/', $path);
	return $path;
}

function checkBoardExistsArcadeAdmin($boardId = 0)
{
	global $smcFunc;

	$boardId = !empty($boardId) ? (int)$boardId : 0;
	$boardName = false;

	if ($boardId < 1)
		return false;

	$request = $smcFunc['db_query']('', '
		SELECT id_board, name
		FROM {db_prefix}boards
		WHERE id_board = {int:boardid}',
		array('boardid' => $boardId)
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$boardName = !empty($row['name']) ? true : false;

	$smcFunc['db_free_result']($request);

	return $boardName;
}

function checkUserExistsArcadeAdmin($userId = 0)
{
	global $smcFunc;

	$userId = !empty($userId) ? (int)$userId : 0;
	$userName = false;

	if ($userId < 1)
		return false;

	$request = $smcFunc['db_query']('', '
		SELECT id_member, member_name
		FROM {db_prefix}members
		WHERE id_member = {int:userid}',
		array('userid' => $userId)
	);

	while ($row = $smcFunc['db_fetch_assoc']($request))
		$userName = !empty($row['member_name']) ? true : false;

	$smcFunc['db_free_result']($request);

	return $userName;
}

function checkArcadeHtmlGameFiles($directory, $internal_name)
{
	list($submit_system, $file) = array('ibp', $internal_name . '.swf');
	if (file_exists($directory . '/' . $internal_name . '.html'))
	{
		$submit_system = 'html5';
		$file = $internal_name . '.html';
	}
	elseif (file_exists($directory . '/gamedata/' . $internal_name . '/index.html'))
	{
		$submit_system = 'html52';
		$file = 'gamedata/' . $internal_name . '/index.html';
	}
	elseif (file_exists($directory . '/' . $internal_name . '/gamedata/' . $internal_name . '.html'))
	{
		$submit_system = 'html52';
		$file = $internal_name . '/gamedata/' . $internal_name . '.html';
	}

	if (strpos($submit_system, 'html5') !== false && file_exists($directory . '/' . $internal_name . '.ini'))
		$submit_system = 'html53';

	return array($submit_system, $file);
}

?>