<?php
/******************************************************************************
* coppermine_to_smf.php                                                       *
*******************************************************************************
* based on:                                                                   *
* SMF: Simple Machines Forum                                                  *
* Open-Source Project Inspired by Zef Hemel (zef@zefhemel.com)                *
* =========================================================================== *
* Software by:                Simple Machines (http://www.simplemachines.org) *
* Copyright 2001-2005 by:     Lewis Media (http://www.lewismedia.com)         *
* Support, News, Updates at:  http://www.simplemachines.org                   *
*******************************************************************************
* This program is free software; you may redistribute it and/or modify it     *
* under the terms of the provided license as published by Lewis Media.        *
*                                                                             *
* This program is distributed in the hope that it is and will be useful,      *
* but WITHOUT ANY WARRANTIES; without even any implied warranty of            *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                        *
*                                                                             *
* See the "license.txt" file for details of the Simple Machines license.      *
* The latest version can always be found at http://www.simplemachines.org.    *
******************************************************************************/

// Search for "// ***" to find things you might want to change if you are
// adapting this converter for another forum type.

// *** Converting from stuff.... **********************************************
//     (anything that needs to be done for things to work properly.)
// The name of the forum this is converting from.
$converting_name = 'phpKit';
// ****************************************************************************

// Set up SMF's required stuff. (define, etc.)
#define('IN_COPPERMINE', 1);
#define('FIRST_USER_CAT', 10000);
$time_start = time();

// speziell für diesen Konverter
include('mainfile.php');
$_POST['path_to'] = dirname(__FILE__);
$_POST['path_from'] = dirname(__FILE__);
$_POST['prefix_from'] = (isset($_POST['prefix_from'])) ? $_POST['prefix_from'] : '';
// ENDE speziell für diesen Konverter

initialize_inputs();

if (!function_exists($_GET['step']))
	$_GET['step'] = 'doStep0';

show_header();
$_GET['step']();
show_footer();

function initialize_inputs()
{
	// Clean up after unfriendly php.ini settings.
	@set_magic_quotes_runtime(0);
	error_reporting(E_ALL);
	#session_start();

	// Add slashes, as long as they aren't already being added.
	if (get_magic_quotes_gpc() != 0)
	{
		foreach ($_POST as $k => $v)
			$_POST[$k] = stripslashes($v);
	}

	// This is really quite simple; if ?delete is on the URL, delete the installer...
	if (isset($_GET['delete']))
	{
		@unlink(__FILE__);
		exit;
	}

	// The current step - starts at 0.
	$_GET['step'] = 'doStep' . (int) @$_GET['step'];
	$_REQUEST['start'] = (int) @$_REQUEST['start'];
}

// Load and verify the include files for pragmaMx and the convertee.
function loadSettings()
{
	global $from_prefix, $to_prefix, $to_prefix_u, $converting_name;

	if (isset($to_prefix) && isset($from_prefix))
		return;

	// Check for the password...
	if (isset($_POST['db_pass']))
		$_SESSION['convert_db_pass'] = $_POST['db_pass'];
	else
		$_POST['db_pass'] = $_SESSION['convert_db_pass'];

	$_POST['path_from'] = substr($_POST['path_from'], -1) == '/' ? substr($_POST['path_from'], 0, -1) : $_POST['path_from'];
	$_POST['path_to'] = substr($_POST['path_to'], -1) == '/' ? substr($_POST['path_to'], 0, -1) : $_POST['path_to'];

	// Cannot find /include/config.inc.php?
	if (!file_exists($_POST['path_to'] . '/config.php'))
		return doStep0('This installer was unable to find pragmaMx in the path you specified.<br /><br />Please double check the path, and that it is already installed there.');

	// Everything should be alright now... no cross server includes, we hope...
	require($_POST['path_to'] . '/config.php');

	// $GLOBALS wird in config.inc.php von Coppermine benötigt
	$GLOBALS['dbhost']  = $dbhost;   // Your database server
	$GLOBALS['dbuname'] = $dbuname;  // Your mysql username
	$GLOBALS['dbpass']  = $dbpass;   // Your mysql password
	$GLOBALS['dbname']  = $dbname;   // Your mysql database name

	if ($_SESSION['convert_db_pass'] != $dbpass)
		doStep0('The database password you entered was incorrect.  Please make sure you are using the right password (for the pragmaMx user!) and try it again.');

// *** Look for the settings file. ********************************************
#	if (!file_exists($_POST['path_from'] . '/include/config.inc.php'))
#		return doStep0('Unable to find the settings for ' . $converting_name . '.  Please double check the path and try again.');
// ****************************************************************************

	// Persist?
	if (empty($db_persist))
		mysql_connect($dbhost, $dbuname, $dbpass);
	else
		mysql_pconnect($dbhost, $dbuname, $dbpass);

	$to_prefix = '`' . $dbname . '`.' . $prefix;
	$to_prefix_u = '`' . $dbname . '`.' . $user_prefix;

	#$GLOBALS['boardurl'] = $boardurl;

	#$request = mysql_query("
	#	SELECT value
	#	FROM {$to_prefix}settings
	#	WHERE variable = 'smfVersion'
	#	LIMIT 1");
	#$row = mysql_fetch_assoc($request);
	#mysql_free_result($request);

	#if (empty($row['value']) || $row['value'] > '1.0.99')
	#	doStep0('The installation of pragmaMx in the path you specified is not a version this converter can deal with.  If it is older than pragmaMx 1.0, you need to upgrade first.  If it is newer, you need to use a different converter.');

// *** Figure out the prefix... ***********************************************
	loadOldSettings();
// ****************************************************************************

	echo '
			<div class="panel">
				<h2>Converting...</h2>';
}

// Coppermine Specific!
function loadOldSettings()
{
	global $from_prefix;
	global $language, $timeout, $timeoffset, $MembersPerPage, $Show_RecentBar;
	global $userpic_width, $userpic_height, $facesdir, $facesurl, $maxmessagedisplay, $maxdisplay, $Cookie_Length, $RegAgree;
	global $emailpassword, $emailnewpass, $emailwelcome, $allow_hide_email, $timeformatstring, $guestaccess, $MaxMessLen, $MaxSigLen, $enable_ubbc;
	global $JrPostNum, $FullPostNum, $SrPostNum, $GodPostNum;

	#require_once($_POST['path_from'] . '/include/config.inc.php');
	// Everything should be alright now... no cross server includes, we hope...
	require($_POST['path_from'] . '/config.php');
	$from_prefix = '`' . $dbname . '`.' . $_POST['prefix_from'];
	#mxDebugFuncVars($from_prefix);
	#$GLOBALS['boardurl'] = $boardurl;
}

function doStep0($error_message = null)
{
	global $converting_name;

	// If these aren't set (from an error..) default to the current directory.
	if (!isset($_POST['path_from']))
		$_POST['path_from'] = dirname(__FILE__);
	if (!isset($_POST['path_to']))
		$_POST['path_to'] = dirname(__FILE__);

// *** Check for the from settings. *******************************************
	// This will do for SMF...
	$test_from = file_exists($_POST['path_from'] . '/include/config.inc.php');
// ****************************************************************************

	// Check for pragmaMx's config.php.
	#$test_to = file_exists($_POST['path_to'] . '/config.php');

	// Was an error message specified?
	if ($error_message !== null)
		echo '
			<div class="error_message">
				<div style="color: red;">', $error_message, '</div>
			</div>
			<br />';

	echo '
			<div class="panel">
				<form name="autoSubmit" action="', $_SERVER['PHP_SELF'], '?step=1" method="post">
					<h2>Where are they?</h2>
					<h4>The converter should only need to know where the two installs are, and then it should be able to handle it from there.</h4>

					<table width="100%" cellpadding="0" cellspacing="0" border="0" align="center" style="margin-bottom: 2ex;">
						<tr>
							<td valign="top" class="textbox"><label for="prefix_from">table prefix from ', $converting_name, ':</label></td>
							<td style="padding-bottom: 1ex;">
								<input type="text" name="prefix_from" id="prefix_from" value="', $_POST['prefix_from'], '" size="60" />
								<div style="font-style: italic; font-size: smaller;">', $test_from ? 'This looks like the right path.' : 'You will need to change the value in this box.', '</div>
							</td>
						</tr><tr>
							<td valign="top" class="textbox" style="padding-top: 2ex;"><label for="db_pass">pragmaMx Database password:</label></td>
							<td valign="top" style="padding-top: 2ex; padding-bottom: 1ex;">
								<input type="password" name="db_pass" size="30" class="text" />
								<div style="font-style: italic; font-size: smaller;">(for verification, you know.)</div>
							</td>
						</tr>
					</table>

					<h2>Before you continue</h2>
					<h4>Make sure you have already installed ',$converting_name,' and pragmaMx, and gotten them working.  This converter takes members and other data from ', $converting_name, ' into pragmaMx, but it won\'t work without an installation to put them in.</h4>
					<div style="margin-bottom: 2ex;">Also note that the MySQL user you installed pragmaMx with will need access to both the pragmaMx database and the ', $converting_name, ' database, unless they are in the same database.  Either way, both have to be installed on the same MySQL server.</div>
					<div style="margin-bottom: 2ex;">Another important piece of information is that all the data currently in the pragmaMx install - members, moderators, usergroups, etc. - <b>will be deleted</b> during the conversion process.  Nothing on your ', $converting_name, ' forum will be hurt - just pragmaMx.</div>

					<div align="right" style="margin: 1ex;"><input name="b" type="submit" value="Continue" class="submit" /></div>
				</form>
			</div>';

	if ($error_message !== null)
	{
		show_footer();
		exit;
	}
}

// Step 1: correct Membernames.
function doStep1()
{
	global $from_prefix, $to_prefix, $to_prefix_u, $current_step;

	$current_step = 1;

	// Load the settings.
	loadSettings();

	// wenn Formular abgeschickt wurde
	if (isset($_POST['newname']) && is_array($_POST['newname'])) {
		#echo '<pre>';
		#print_r($_POST['newname']);
		foreach($_POST['newname'] as $old_name => $new_name) {
			$new_name = stripslashes($new_name);
			if (preg_match('#[^a-zA-Z0-9 _-]#', $new_name) || strlen($new_name) > 25) {
				continue;
			}
			$qry = "UPDATE {$from_prefix}user SET user_name='".$new_name."' WHERE user_name='".mysql_escape_string(base64_decode($old_name))."'";
			mysql_query($qry);
			// wenn da Fehler entstehen, dann wird der User nochmal unten gelistet...
		}
		#print_r($qry);
		#echo '</pre>';
	}
	
	
	// alle ungültigen Usernamen aus der Tabelle auslesen
	$result = mysql_query("
		SELECT user_id, user_name
		FROM {$from_prefix}user
		WHERE user_name REGEXP '[^a-zA-Z0-9 _-]'
		OR LENGTH(user_name) > 25");
	if ($result === false)
		doStep0('Sorry, the database connection information used in the specified installation of pragmaMx cannot access the installation of ' . $GLOBALS['converting_name'] . '.  This may either mean that the installation doesn\'t exist, or that the MySQL account used does not have permissions to access it.');
	
	// Array erstellen, mit den aktuellen Usernamen und den Änderungsvorschlägen
	while ($row = mysql_fetch_assoc($result)) {
		$new = str_replace(array('ä', 'ö', 'ü', 'ß', 'Ä', 'Ö', 'Ü'), array('ae', 'oe', 'ue', 'ss', 'Ae', 'Oe', 'Ue'), $row['user_name']);
		$new = preg_replace('#\s*_\s*#','_',preg_replace('#[^a-zA-Z0-9 _-]#', '_', $new));
		$fields[$row['user_name']] = trim($new);
	}
	mysql_free_result($result);

	// wenn keine Datensätze vorhanden, gleich weiter zum nächsten Schritt
	if (!isset($fields)) {
		$_REQUEST['start'] = 0;
		return doStep3();
	}

	// First empty out the table.
	#if ($_REQUEST['start'] == 0)
	#{
	#}

	$out = '';
	foreach($fields as $old_name => $new_name) {
		$out .= '<tr><td><strong>'.$old_name.'</strong></td><td><input type="text" name="newname['.base64_encode($old_name).']" value="'.htmlentities(substr($new_name, 0, 25)).'" size="35" maxlength="25" /></td></tr>';
	}
	echo '
	<div class="panel">
		<form name="autoSubmit" action="', $_SERVER['PHP_SELF'], '?step=1" method="post">
			<h3>Some of the user names can\'t be used in pragmaMx. These user names should be corrected before proceeding.</h3>
			<ul>
				<li>Changes will be performed in the original table of the database.</li>
				<li>User names are allowed to be maximum of 25 characters. There are no special characters allowed, but space, "_" and "-".</li>
				<li>All special characters will be replaced by "_". German "umlauts" will be replaced by the vowel and an "e", e.g. ä=ae.</p></li>
			</ul>			
			<table cellpadding="3" cellspacing="0" border="1" style="margin-bottom: 2ex;">
				<tr><th>invalid name</th><th>new name</th>
				</tr>
				'.$out.'
			</table>
			<div align="left" style="margin: 1ex;"><input name="b" type="submit" value="Continue" class="submit" /></div>
			<input type="hidden" name="path_to" id="path_to" value="', $_POST['path_to'], '" />
			<input type="hidden" name="prefix_from" id="prefix_from" value="', $_POST['prefix_from'], '" />
		</form>
	</div>';


mxDebugFuncVars($_POST, $fields, $out);
exit;

	show_footer();
	exit;
}

// Step 2: membergroups
function doStep2()
{
	global $from_prefix, $to_prefix, $to_prefix_u, $current_step;

// dieser Schritt fällt aus ;)
	$_REQUEST['start'] = 0;
	return doStep3();

	$current_step = 2;

	// Load the settings.
	loadSettings();

	// Everything should be alright now... no cross server includes, we hope...
	require($_POST['path_to'] . '/config.php');
	if (empty($default_group) || $default_group<1) {
		$default_group = 1;
	}

	// Tell ummm...
	echo '
		Converting membergroups... ';

	$result = mysql_query("
		SELECT *
		FROM {$from_prefix}usergroups 
		LIMIT 1");
	if ($result === false) {
		doStep0('Sorry, the database connection information used in the specified installation of pragmaMx cannot access the installation of ' . $GLOBALS['converting_name'] . '.  This may either mean that the installation doesn\'t exist, or that the MySQL account used does not have permissions to access it.');
	#} else {
	#	$row = mysql_fetch_assoc($result);
		/// falls das mx-Gruppenfeld noch nicht vorhanden ist
		#if (!isset($row['mx_group'])) {
		#	mysql_query("ALTER TABLE {$from_prefix}usergroups ADD `mx_group` INT( 10 ) DEFAULT '0' NOT NULL");
		#	mysql_query("ALTER TABLE {$from_prefix}usergroups ADD INDEX mx_group( `mx_group` )");
		#}
	}
	mysql_free_result($result);
	
	// pragmaMx Gruppentabelle optimieren, wegen insert_id
	#mysql_query("OPTIMIZE TABLE {$to_prefix}_groups_access");
	
	// die Gruppen vom pragmaMx
	$request = mysql_query("
		SELECT access_id, access_title
		FROM {$to_prefix}_groups_access
		");
	$mx_default_groupname = '';
	$mx_groups = array();
	while ($row = mysql_fetch_assoc($request)) {
		$mx_groups[$row['access_title']] = $row['access_id'];
        if ($row['access_id'] == $default_group) {
            $mx_default_groupname = $row['access_title']; # $mx_default_groupname.' (default)'
        } 
	}
	mysql_free_result($request);
	// falls pragmaMx Defaultgruppe fehlen sollte, diese anfügen
	if (!in_array($default_group, $mx_groups)) {
		mysql_query("INSERT INTO {$to_prefix}_groups_access VALUES (".intval($default_group).", 'User_".intval($default_group)."')");
		$mx_groups['User_'.intval($default_group)] = intval($default_group);
	}

	// die Gruppen von Coppermine
	#INSERT INTO CPG_usergroups VALUES (1, 'Administrators', 0, 1, 1, 1, 1, 1, 1, 0, 0, 3, 0, 5, 3);
	#INSERT INTO CPG_usergroups VALUES (2, 'Registered', 1024, 0, 1, 1, 1, 1, 1, 1, 0, 3, 0, 5, 3);
	#INSERT INTO CPG_usergroups VALUES (3, 'Anonymous', 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 5, 3);
	#INSERT INTO CPG_usergroups VALUES (4, 'Banned', 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 5, 3);

	$request = mysql_query("
		SELECT  group_id, group_name, has_admin_access
		FROM {$from_prefix}usergroups
		WHERE group_id > 4 
		AND group_name 
		NOT IN('Administrators','Registered','Anonymous','Banned','-Admins','-Registered','-Anonymous','-banned','-Gallery-Admins', '" . $mx_default_groupname . " (default)')
		");
	$groups = array();
	while ($row = mysql_fetch_assoc($request)) {
		#print_r ($row);
		if (isset($mx_groups[$row['group_name']])) {
			// gruppe im pragmaMx vorhanden, dann muss die ID an die pragmaMx Gruppe angepasst werden und auch bei den Usern eingetragen werden
			#$new_cp_group[$row['group_id']] = $mx_groups[$row['group_name']];
		} else {
			// gruppe nicht im pragmaMx vorhanden, 
			// dann in pragmaMx einfügen
			mysql_query("INSERT INTO {$to_prefix}_groups_access VALUES (NULL, '".addslashes($row['group_name'])."')");
			#print mysql_error();
		}
		
	}

	mysql_free_result($request);
	mysql_query("ALTER TABLE {$to_prefix}_groups_access ORDER BY `access_id` ");

	echo '
		successful.<br />';

	$_REQUEST['start'] = 0;
	return doStep3();
}


// Step 1: Members. (they're the most important part, right?)
function doStep3()
{
	global $from_prefix, $to_prefix, $to_prefix_u, $current_step;

	$current_step = 3;

	// Load the settings.
	loadSettings();

	// Everything should be alright now... no cross server includes, we hope...
	require($_POST['path_to'] . '/config.php');
	if (empty($default_group) || $default_group<1) {
		$default_group = 1;
	}

	echo '
			Converting members... ';

	$result = mysql_query("
		SELECT COUNT(*)
		FROM {$from_prefix}user");
	if ($result === false)
		doStep0('Sorry, the database connection information used in the specified installation of pragmaMx cannot access the installation of ' . $GLOBALS['converting_name'] . '.  This may either mean that the installation doesn\'t exist, or that the MySQL account used does not have permissions to access it.');
	mysql_free_result($result);

	// First empty out the table.
	if ($_REQUEST['start'] == 0)
	{
		// Usertabelle leeren
		mysql_query("
			TRUNCATE {$to_prefix_u}_users");
		mysql_query("
			DELETE FROM {$to_prefix_u}_users");
	}
	
	// die Gruppen vom pragmaMx
	$request = mysql_query("
		SELECT access_id, access_title
		FROM {$to_prefix}_groups_access
		");
	$mx_default_groupname = '';
	$mx_groups = array();
	while ($row = mysql_fetch_assoc($request)) {
		$mx_groups[$row['access_title']] = $row['access_id'];
        if ($row['access_id'] == $default_group) {
            $mx_default_groupname = $row['access_title']; # $mx_default_groupname.' (default)'
        } 
	}
	mysql_free_result($request);

	// die Gruppen von Coppermine
	#$request = mysql_query("
	#	SELECT  group_id, group_name, has_admin_access
	#	FROM {$from_prefix}usergroups
	#	WHERE group_id > 4 
	#	AND group_name 
	#	NOT IN('Administrators','Registered','Anonymous','Banned','-Admins','-Registered','-Anonymous','-banned','-Gallery-Admins', '" . $mx_default_groupname . " (default)')
	#	");
	#$groups = array();
	#while ($row = mysql_fetch_assoc($request)) {
	#	if (isset($mx_groups[$row['group_name']])) {
	#		$groups[$row['group_id']] = $mx_groups[$row['group_name']];
	#	}
	#}
	#mysql_free_result($request);
	#print_r ($groups);

// *** pragmaMx column => SMF's column. ************************************
	
	/*
	Coppermine Felder
	
	user_id
	user_group
	user_active
	user_name
	user_password
	user_lastvisit
	user_regdate
	user_group_list
	user_email
	*/

	$members_table = array(
		'uid' => 'u.user_id',
		'name' => 'u.user_name',
		'uname' => 'u.user_nick',
		'email' => 'u.user_email',
		'femail' => 'IF(u.user_emailshow=1, u.user_email, "")',
		'url' => 'u.user_hpage',
		'user_avatar' => 'u.user_avatar',
		'user_regdate' => 'DATE_FORMAT( u.signin , "%b %d, %Y" ) ',
		'user_icq' => 'IF(u.user_icqid=0, "", u.user_icqid)',
		'user_occ' => 'u.user_qou',
		'user_from' => '',
		'user_intrest' => 'u.user_hobby',
		// signature needs conversion!
		'user_sig' => 'u.user_sig',
		'user_viewemail' => 'u.user_emailshow',
		'user_theme' => '',
		'user_aim' => 'u.user_aimid',
		'user_yim' => 'u.user_yim',
		'user_msnm' => 'u.user_msnid',
		'pass' => 'u.user_pw',
		'storynum' => '',
		'umode' => '',
		'uorder' => '',
		'thold' => '',
		'noscore' => '',
		'bio' => '',
		'ublockon' => '',
		'ublock' => '',
		'theme' => '',
		'commentmax' => '',
		'counter' => 'u.user_posts',
		'newsletter' => '',
		'user_posts' => 'u.user_posts',
		'user_attachsig' => '',
		// user_rank speichert die Adminberechtigungen zwischen
		'user_rank' => '0',
		'user_level' => '',
		// user_ingroup needs conversion!
		'user_ingroup' => '9999999',
		'user_regtime' => 'u.signin',
		'user_lastvisit' => 'u.logtime',
		'user_lastip' => '',
		'user_lastmod' => '',
		'user_lasturl' => '',
		'user_stat' => 'IF(u.user_activate=1, 1, 0)',
		'user_pm_poptime' => '',
		'user_bday' => 'CONCAT_WS("-", u.user_bd_year, u.user_bd_month, u.user_bd_day)',
		'user_sexus' => 'IF(u.user_sex="m", 2, IF(u.user_sex="w", 1, 0))',
		'user_guestbook' => '',
		);
// ****************************************************************************

	while ($_REQUEST['start'] != -1)
	{
		pastTime($_REQUEST['start']);

// *** Might want to change the table/where. **********************************
		$result = mysql_query("
			SELECT " . arrayToClause($members_table) . "
			FROM {$from_prefix}user AS u
			ORDER BY user_id
			LIMIT $_REQUEST[start], 500");
		#print_r (mysql_error());
// ****************************************************************************


		$rows = array();
		while ($row = mysql_fetch_assoc($result))
		{
			// Usergruppe mit defaultwert aus config.php belegen
			$row['user_ingroup'] = intval($default_group);
			#// alle eingetragenen Usergruppen des Benutzers ermitteln
			#if ($row['user_group_list']) {
			#	$user_groups = explode(',', $row['user_group_list']);
			#}
			#if ($row['user_group']) {
			#	$user_groups[] = $row['user_group'];
			#}
			#// nur, wenn nicht überall 0 als Gruppe eingetragen
			#if (isset($user_groups)) {
			#	// doppelte ausfiltern und Gruppen-ID als Arrayschlüssel
			#	$user_groups = array_flip(array_unique($user_groups));
			#	// evtl. noch verbliebene Nullwerte entfernen
			#	unset($user_groups[0]);
			#	// wenn Admingruppe eingetragen
			#	if (isset($user_groups[1])) {
			#		$row['user_rank'] = 1;
			#	#// oder wenn globaler Moderator eingetragen
			#	#} else if (isset($user_groups[2])) {
			#	#	$row['user_rank'] = 2;
			#	}
			#	// die Coppermine-Standardgruppen und evtl. noch verbliebene Nullwerte aus dem array entfernen
			#	unset($user_groups[0], $user_groups[1], $user_groups[2], $user_groups[3], $user_groups[4]);
			#	// die erste gültige und vorhandene Usergruppe des Users ermitteln
			#	foreach ($user_groups as $groupid => $temp) {
			#		if (!empty($groups[$groupid])) {
			#			// und diese als Usergruppe in pragmaMx eintragen
			#			$row['user_ingroup'] = $groups[$groupid];
			#			break;
			#		}
			#	}
			#}
			#// unnötige Feldwerte entfernen
			unset($row['user_group'],$row['user_group_list']);
			// das Array mit den Feldwerten zum einfügen des Datensatzes ergänzen
			$rows[] = "'" . implode("', '", addslashes_recursive($row)) . "'";
		}

			#unset($user_groups);
		// die Gruppenfelder entfernen, die dürfen nicht in der Abfrage sein, die Werte wurden bereits in der Schleife gelöscht
		#$new_members_table = $members_table;
		#unset($new_members_table['user_group'],$new_members_table['user_group_list']);
		
		$qry = "
			INSERT INTO {$to_prefix_u}_users
				(" . implode(', ', array_keys($members_table)) . ")
			VALUES (" . implode('),
				(', $rows) . ")";
		mysql_query($qry);

		$_REQUEST['start'] += 500;
		if (mysql_num_rows($result) < 500)
			break;

		mysql_free_result($result);
	}

	echo '
		successful.<br />';

	$_REQUEST['start'] = 0;
	return doStep5();
}

// Convert over moderators
function doStep4()
{
	global $from_prefix, $to_prefix, $to_prefix_u, $current_step;

/// dieser Schritt fällt aus...
	$_REQUEST['start'] = 0;
	return doStep5();

	$current_step = 4;

	// Load the settings.
	loadSettings();

	// Tell ummm...
	echo '
		Converting moderators... ';
	
	$adminfields = 'aid, name, email, pwd, radminsuper, user_uid';
	
	$admins = array();
	$result = mysql_query("SELECT ".$adminfields." FROM {$to_prefix}_authors");
	while ($row = mysql_fetch_assoc($result)) {
		$admins[$row['aid']] = $row;
		// zwischenspeichern, ob God-Account bereits besteht
		if ($row['name'] == 'God') {
			$godfound = true;
		}
	}
	#print_r($admins);
	
	$result = mysql_query("
		SELECT *
		FROM {$to_prefix_u}_users
		WHERE  user_rank > 0
		ORDER BY uid ");
	
	$minuid = 0;
	$first_uname = '';
	while ($row = mysql_fetch_assoc($result)) {
		#print_r($row); #continue;
		// kleinest uid von Superadmin ermitteln
		if ($row['user_rank'] == 1 && (empty($minuid) || $minuid > $row['uid'])) {
			$minuid = $row['uid'];
			$first_uname = $row['uname'];
		}
		
		// Daten ändern oder einfügen
		if (isset($admins[$row['uname']])) {
			unset($qry);
			// Admin bereits vorhanden > aktualisieren
			#print($admins[$row['uname']]['name'].'<br>');
			if (empty($admins[$row['uname']]['name'])) {
				$qry[] = "name=aid";
			}
			if (empty($admins[$row['uname']]['email']) && !empty($row['email'])) {
				$qry[] = "email='".addslashes($row['email'])."'";
			}
			if (($row['user_rank'] == 1 || $admins[$row['uname']]['name'] == 'God') && empty($admins[$row['uname']]['radminsuper'])) {
				$qry[] = "radminsuper='1'";
			}
			if ($admins[$row['uname']]['user_uid'] != $row['uid']) {
				$qry[] = "user_uid='".$row['uid']."'";
			}
			if (isset($qry)) {
				$qry = "UPDATE {$to_prefix}_authors SET ".implode(',', $qry)." WHERE aid='".addslashes($row['uname'])."'";
				mysql_query($qry);
				#print_r($qry);
			}
		} else {
			// Admin nicht vorhanden > einfügen
			$qry = "INSERT INTO {$to_prefix}_authors (".$adminfields.") VALUES (
			'".addslashes($row['uname'])."', 
			'".addslashes($row['uname'])."', 
			'".addslashes($row['email'])."', 
			'".addslashes($row['pass'])."', 
			".(($row['user_rank'] == 1) ? 1 : 0).", 
			".intval($row['uid'])."
			)";
			mysql_query($qry);
			#print_r($qry);
		}
	}
	mysql_free_result($result);
	
	// Tabelle neu sortieren
	mysql_query("ALTER TABLE {$to_prefix}_authors ORDER BY `user_uid` ");
	
	// God-Account bei Bedarf einfügen
	// Das Passwort ist der Username, weil bei der Übernahme vom SMF alle Passwörter als SHA vorliegen
	if (empty($godfound) && !empty($first_uname)) {
		$qry = "UPDATE {$to_prefix}_authors SET name='God', pwd='".md5($first_uname)."' WHERE aid='".addslashes($first_uname)."'";
		mysql_query($qry);
	}

	echo '
		successful.<br />';

	$_REQUEST['start'] = 0;
	return doStep5();
}


/// TODO:
//  user_id abgleichen, wenn die 1 in der Tabelle vorhanden ist
/* 
{$from_prefix}comments >> author_id
{$from_prefix}banned >> user_id
{$from_prefix}categories >> owner_id
{$from_prefix}favpics >> user_id
{$from_prefix}pictures >> owner_id
{$from_prefix}votes >> user_md5_id (die user_id, als md5)
{$from_prefix}user >> user_id
{$to_prefix}_authors >> user_uid
{$to_prefix_u}_users >> uid
 */

function doStep5()
{
	global $from_prefix, $to_prefix, $to_prefix_u, $current_step;

	$current_step = 5;

	// Load the settings.
	loadSettings();
	
	// suchen nach User, mit ID 1
	
	$old_id = 1;
	
	$result = mysql_query("
		SELECT uid, uname, email
		FROM {$to_prefix_u}_users 
		WHERE uid=".intval($old_id)."");
	list($old_id, $new_username, $new_email) = mysql_fetch_row($result);

	// wenn nicht gefunden, dann gleich weiter mit nächstem Schritt
	if (empty($old_id)) {
		return doStep6();
	}
	// falls gefunden, alle bestehenden Einträge ändern
	
	// nächste freie ID ermitteln
	$new_id = mxGetNextFreeID($to_prefix_u.'_users', 'uid', true);
	// wenn nicht gefunden, dann gleich weiter mit nächstem Schritt
	if (empty($new_id) || $new_id <= $old_id ) {
		return doStep6();
	}
#print_r($new_id); exit;
	// Usertabelle ändern
	$result = mysql_query("
		UPDATE {$to_prefix_u}_users 
		SET uid = ".$new_id."
		WHERE uid=".$old_id."");
	// wenn irgendwas schiefgelaufen, dann gleich weiter mit nächstem Schritt
	if (!$result) {
		return doStep6();
	}
	

	// Everything should be alright now... no cross server includes, we hope...

	// Tell ummm...
	echo '
		Converting user with ID #'.$old_id.'... ';

    // die einzelnen Datenbankabfragen als Array erstellen

	// admintabelle
	$qry[] = "UPDATE {$to_prefix}_authors 
          SET user_uid=".$new_id." 
		  WHERE user_uid=".$old_id."";
	
	/* 
	// alle Coppermine-Tabellen
    $qry[] = "UPDATE {$from_prefix}comments 
          SET author_id = {$new_id} 
		  WHERE author_id = {$old_id}";
    $qry[] = "UPDATE {$from_prefix}banned 
          SET user_id = {$new_id} 
		  WHERE user_id = {$old_id}";
    $qry[] = "UPDATE {$from_prefix}categories 
          SET owner_id = {$new_id} 
		  WHERE owner_id = {$old_id}";
    $qry[] = "UPDATE {$from_prefix}favpics 
          SET user_id = {$new_id} 
		  WHERE user_id = {$old_id}";
    $qry[] = "UPDATE {$from_prefix}pictures 
          SET owner_id = {$new_id} 
		  WHERE owner_id = {$old_id}";
    $qry[] = "UPDATE {$from_prefix}user 
          SET user_id = {$new_id} 
		  WHERE user_id = {$old_id}";
	# (die user_id, als md5) 
    $qry[] = "UPDATE {$from_prefix}votes 
          SET user_md5_id = '".md5($new_id)."'  
		  WHERE user_md5_id = '".md5($old_id)."'";
	 */

    // Alle Datenbankabfragen ausführen
    foreach ($qry as $i => $sql) {
        mysql_query($sql);
        if (mysql_error()) {
            $errors[] = "<p>" . mysql_error() . "<br /><em>$sql</em></p>";
        } 
    } 
	
	if (isset($errors)) {
		echo '<hr ><h3>Es sind folgende Fehler aufgetreten:</h3>' . implode("\n", $errors);
	}
	
	echo '
		successful.<br />';

	$_REQUEST['start'] = 0;
	return doStep6();
}


// Ende
function doStep6()
{
	global $from_prefix, $to_prefix, $to_prefix_u, $current_step, $converting_name;

	$current_step = 5;

	// Load the settings.
	loadSettings();

	echo '
				<h2 style="margin-top: 2ex;">Conversion Complete</h2>
				<h4>Congratulations, the conversion has completed sucessfully.  If you have or had any problems with this converter, or need help using pragmaMx/SMF, please feel free to <a href="http://www.pragmamx.org/Forum.html">look to us for support</a>.</h4>';

	if (is_writable(__FILE__))
		echo '
				<div style="margin: 1ex; font-weight: bold;">
					<label for="delete_self"><input type="checkbox" id="delete_self" onclick="doTheDelete();" /> Please check this box to delete the converter right now for security reasons.</label> (doesn\'t work on all servers.)
				</div>
				<script language="JavaScript" type="text/javascript"><!--
					function doTheDelete()
					{
						var theImage = document.getElementById ? document.getElementById("delete_converter") : document.all.delete_converter;
						var theCheck = document.getElementById ? document.getElementById("delete_self") : document.all.delete_self;

						theImage.src = "', $_SERVER['PHP_SELF'], '?delete&" + (new Date().getTime());
						theImage.width = 0;
						theCheck.disabled = true;
					}
				// --></script>
				<img src="images/spacer.gif" alt="" id="delete_converter" /><br />
				<br />';
	echo '
				Now that everything is converted over, your pragmaMx installation should have all the members from the ', $converting_name, ' installation.<br />
				<br />
				We hope you had a smooth transition,<br />
				Coppermine & pragmaMx';
}

function show_header()
{
	global $converting_name;

	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<title>', $converting_name, ' to pragmaMx Converter</title>
		<style type="text/css"><!--
			body
			{
				font-family: Verdana, sans-serif;
				background-color: #ABD140;
				margin: 0;
			}
			body, td
			{
				font-size: 10pt;
			}
			div#header
			{
				background-color: white;
				padding: 22px 4% 12px 4%;
				font-family: Georgia, serif;
				font-size: xx-large;
				border-bottom: 1px solid black;
				height: 40px;
			}
			div#content
			{
				margin: 20px 30px;
			}
			div.error_message
			{
				border: 2px dashed red;
				background-color: #FFF8DC;
				margin: 1ex 4ex;
				padding: 1.5ex;
			}
			div.panel
			{
				border: 1px solid gray;
				background-color: #ECF4D7;
				margin: 1ex 0;
				padding: 1.2ex;
			}
			div.panel h2
			{
				margin: 0;
				margin-bottom: 0.5ex;
				padding-bottom: 3px;
				border-bottom: 1px dashed black;
				font-size: 14pt;
				font-weight: normal;
			}
			div.panel h4
			{
				margin: 0;
				margin-bottom: 2ex;
				font-size: 10pt;
				font-weight: normal;
			}
			form
			{
				margin: 0;
			}
			td.textbox
			{
				padding-top: 2px;
				font-weight: bold;
				white-space: nowrap;
				padding-right: 2ex;
			}
		--></style>
	</head>
	<body>
		<div id="header">
			<div title="Bahamut!">', $converting_name, ' to pragmaMx Converter</div>
		</div>
		<div id="content">';
}

// Show the footer.
function show_footer()
{
	if ($_GET['step'] != 'doStep0')
		echo '
			</div>';

	echo '
		</div>
	</body>
</html>';
}

// Check if we've passed the time limit..
function pastTime($position)
{
	global $time_start, $current_step;

	@set_time_limit(300);

	if (time() - $time_start > 10)
	{
		echo '
			incomplete.<br />

			<h2 style="margin-top: 2ex;">Not quite done yet!</h2>
			<h4>
				This conversion has paused to avoid overloading your server, and hence not working properly.<br />
				Don\'t worry though, <b>nothing\'s wrong</b> - simply click the <label for="continue">continue button</label> below to start the converter from where it left off.
			</h4>

			<form action="', $_SERVER['PHP_SELF'], '?step=', $current_step, '&amp;start=', $position, '" method="post" name="autoSubmit">
				<input type="hidden" name="prefix_from" value="' . $_POST['prefix_from'] . '" />
				<input type="hidden" name="path_to" value="' . $_POST['path_to'] . '" />
				<div align="right" style="margin: 1ex;"><input name="b" type="submit" value="Continue" /></div>
			</form>
			<script language="JavaScript" type="text/javascript"><!--
					window.onload = doAutoSubmit;
					var countdown = 3;

					function doAutoSubmit()
					{
						if (countdown == 0)
							document.autoSubmit.submit();
						else if (countdown == -1)
							return;

						document.autoSubmit.b.value = "Continue (" + countdown + ")";
						countdown--;

						setTimeout("doAutoSubmit();", 1000);
					}
				// --></script>';

		show_footer();
		exit;
	}
	else
		return false;
}

function addslashes_recursive($var)
{
	if (!is_array($var))
		return addslashes($var);
	else
	{
		foreach ($var as $k => $v)
			$var[$k] = addslashes($v);
		return $var;
	}
}

function arrayToClause(&$table_data)
{
	$select = '';
	foreach ($table_data as $to_col => $from_col)
	{
		if ($from_col == '')
		{
			unset($table_data[$to_col]);
			continue;
		}

		$select .= '
			' . $from_col . ' AS ' . $to_col . ',';
	}

	return substr($select, 0, -1);
}

function ip2range($fullip)
{
	$ip_parts = explode('.', $fullip);
	if (count($ip_parts) != 4)
		return array();
	$ip_array = array();
	for ($i = 0; $i < 4; $i++)
	{
		if ($ip_parts[$i] == '*')
			$ip_array[$i] = array('low' => '0', 'high' => '255');
		elseif (preg_match('/^(\d{1,3})\-(\d{1,3})$/', $ip_parts[$i], $range))
			$ip_array[$i] = array('low' => $range[1], 'high' => $range[2]);
		elseif (is_numeric($ip_parts[$i]))
			$ip_array[$i] = array('low' => $ip_parts[$i], 'high' => $ip_parts[$i]);
	}
	if (count($ip_array) == 4)
		return $ip_array;
	else
		return array();
}

function convertSettingstoOptions()
{
	global $modSettings, $to_prefix;

	// Format: new_setting -> old_setting_name.
	$values = array(
		'calendar_start_day' => 'cal_startmonday',
		'view_newest_first' => 'viewNewestFirst',
		'view_newest_pm_first' => 'viewNewestFirst',
	);

	$setString = '';

	// Do a row for guests and defaults on register...
	foreach ($values as $variable => $value)
	{
		if (isset($modSettings[$value[0]]) && !empty($modSettings[$value[0]]))
			$setString .= '
				(-1, 1, \'' . $variable . '\', \'' . $modSettings[$value[0]] . '\'),';
		else
			unset($values[$variable]);
	}

	// Do the actual (monster) insert.
	if (!empty($setString))
	{
		mysql_query("
			INSERT IGNORE INTO {$to_prefix}themes
				(user_id, ID_THEME, variable, value)
			VALUES" . substr($setString, 0, -1));
		if ($db_error)
			return false;
	}

	// Redo it now for the members.
	$setString = array();
	foreach ($values as $variable => $value)
	{
		mysql_query("
			INSERT IGNORE INTO {$to_prefix}themes
				(user_id, ID_THEME, variable, value)
			SELECT user_id, 1 AS ID_THEME, '$variable' AS variable, '" . $modSettings[$value[0]] . "' AS value
			FROM {$to_prefix_u}_users");
		if ($db_error)
			return false;
	}

	return true;
}

function fixRelativePath($path)
{
	// Fix the . at the start, clear any duplicate slashes, and fix any trailing slash...
	return addslashes(preg_replace(array('~^\.([/\\\]|$)~', '~[/]+~', '~[\\\]+~', '~[/\\\]$~'), array(dirname(__FILE__) . '$1', '/', '\\', ''), $path));
}

function mxGetNextFreeID($tablename, $fieldname, $between = 0)
{
    $freeid = 0;
    $count = 0;
    if ($between) {
        $qry = "select $fieldname from $tablename order by $fieldname";
        $result = mysql_query($qry);
        while (list($id) = mysql_fetch_row($result)) {
            $count ++; 
            // print "$count <br>";
            if ($count < $id) {
                return $id - 1;
            } else {
                $freeid = $id;
            } 
        } 
    } else {
        $qry = "select max($fieldname) from $tablename;";
        $result = mysql_query($qry);
        list($freeid) = mysql_fetch_row($result);
    } 
    if (empty($freeid)) $freeid = 0;
    return $freeid + 1;
} 


?>