<?php

define('IN_COPPERMINE', true);

require('include/init.inc.php');

if (!GALLERY_ADMIN_MODE) cpg_die(ERROR, $lang_errors['access_denied'], __FILE__, __LINE__);


$usertable = $CONFIG['TABLE_USERS'];

pageheader('User importer');

starttable('100%', 'User importer');

function clean($string){

	return addslashes(trim($string, "\x00..\x1F" . '"'));


}

if (count($_FILES)){

	if ($_FILES['userfile']['error']) die('Upload errror ' . $_FILES['userfile']['error']);


	$data = file($_FILES['userfile']['tmp_name']);

	unset($data[0]);
 
	$accounts = array();


	// "Password","UserName","FullName","E-Mail"

	foreach ($data as $line){
		$parts = explode(',', $line);
		$accounts[] = array(
			'username' => $parts[1],
			'password' => $parts[0],
			'fullname' => $parts[2],
			'email' => $parts[3]
		);
	}


	foreach ($accounts as $account){
		$account = array_map("clean", $account);
		extract($account);
		$result = db_query("INSERT IGNORE INTO $usertable (`user_name`, `user_password`, `user_email`, `user_active`, `user_regdate`) VALUES ( '$username', '$password', '$email', 'YES', NOW())");
		$status = mysql_affected_rows() ? "User '$username' added" : "<font color=\"red\">User '$username' already exists</font>" ;
		echo '<tr><td class="tableb" align="center">'.$status.'</td></tr>';
	}

} else {

	echo <<< EOT
<tr>
	 <td class="tableb" align="center">
		<p>Upload a CSV file to import</p>
		<form action="import.php" METHOD="post" enctype="multipart/form-data">
			<input name="userfile" type="file" size="50">
			<input type="submit" value="Upload">
		</form>
	</td>
</tr>

EOT;


}

endtable();
pagefooter();
?>