<?php

						/*************************************\
						
						    Handshakes Professional (3.0)
						            by DZOIC LTD
						       Copyright(c) 2005-2006
						        http://www.dzoic.com
						
						\*************************************/

						///////////////////////////////////////
						
						admin_validate_section("tools",3);
						$action = $GLOBALS["Get"]->val("action");
						
							switch($action){
									
								case '':
									import_options();
									break;
									
								case 'import':
									import_members();
									break;
									
								case 'do_import':
									do_import_members();
									break;
								
							}//switch
							
						///////////////////////////////////////

function import_options(){
	
	admin_validate();
	
	$data["section"] = "tools";
	$data["subsection"] = 3;
	$data["title_id"] = "19";	
	$vals = array("file","settings","columns");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if(empty($values["settings"]["male"]))
		$values["settings"]["male"] = "Male";
	if(empty($values["settings"]["female"]))
		$values["settings"]["female"] = "Female";
	if(empty($values["settings"]["birthdate"]))
		$values["settings"]["birthdate"] = "D/M/Y";
	
	$data["values"] = $values;
	
	$import_files = array ();
	
	$members_import_folder = DOC_ROOT."/import/members";
	$dirhandler = opendir($members_import_folder);
	while($file = readdir($dirhandler)){
		if($file!="." && $file!=".."){
			$import_file["file"] = $file;
			$import_file["size"] = filesize($members_import_folder."/".$file);			
			if($import_file["size"] < 1024)
				$import_file["size"].= " bytes";
			elseif($import_file["size"] >= 1024 && $import_file["size"] < 1048576)
				$import_file["size"] = round($import_file["size"]/1024,2)." KB";
			elseif($import_file["size"] >= 1048576)
				$import_file["size"] = round($import_file["size"]/1048576,2)." MB";
				
			$import_files[] = $import_file;
		}//if
	}//while
	
	$data["files"] = $import_files;
	
	$layout[0] = "members_import_options";
	
	admin_output($layout,$data);
	
}//import_options

function import_members(){
	
	admin_validate();
	
	$data["section"] = "tools";
	$data["subsection"] = 3;
	$data["title_id"] = "19";	
	$vals = array("file","settings","columns");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if(empty($values["file"]) || !file_exists(DOC_ROOT."/import/members/".$values["file"])){
		$GLOBALS["aerr_id"] = 12;
		import_options();
		exit;
	}//if
	
	$data["file"] = $values["file"];
	
	$data["link"] = "index.php?section=import_members&action=do_import";
	
	while(list($key,$val) = each($values)){
		if(is_array($val)){
			while(list($k,$v) = each($val)){
				$data["link"].= "&".$key."[".$k."]=".urlencode($v);
			}//while
		}//if
		else
			$data["link"].= "&".$key."=".urlencode($val);
	}//while
	
	$data["javascript"] = "
<script language=\"JavaScript\">
	function HS_PullReport( status ){
		MessageHandler = document.getElementById('status');
		MessageHandler.innerHTML = status;
	}//HS_PullReport
	function HS_StartImport(){
		ImportHandler = document.getElementById('import_processor');
		ImportHandler.src = \"".$data["link"]."\";
	}//HS_StartImport
</script>
";

	$data["onload"] = "HS_StartImport();HS_PullReport('Import in process...');";
	
	$layout[0] = "import_members";
	
	admin_output($layout,$data);
	
}//import_members

function do_import_members(){
	
	set_time_limit(0);
	
	admin_validate();
	
	$vals = array("file","settings","columns");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	extract($values);
	
	if(empty($file) || !file_exists(DOC_ROOT."/import/members/".$file)){
		load_page("index.php?section=import_members&err_id=12");
	}//if
	
	$data["file"] = $file;
	
	Header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    Header("Cache-Control: no-cache, must-revalidate"); 
	Header("Pragma: no-cache");
	
	$line_count = 1;
	$imported = 0;
	$report = "";	
	$file_handler = fopen(DOC_ROOT."/import/members/".$file,"r");
	while($line = @fgets($file_handler, 1024)){
		trim($line);
		$line  = ereg_replace("\r|\n","",$line);
		$items = explode("\t",$line);
		
		if($columns["email"])
			$email = $items[$columns["email"]-1];
			
		if($columns["username"])
			$username = $items[$columns["username"]-1];
			
		if($columns["password"])
			$password = $items[$columns["password"]-1];
			
		if($columns["fname"])
			$fname = $items[$columns["fname"]-1];
			
		if($columns["lname"])
			$lname = $items[$columns["lname"]-1];
		
		if($columns["country"])
			$country = $items[$columns["country"]-1];
			
		if($columns["state"])
			$state = $items[$columns["state"]-1];
			
		if($columns["city"])
			$city = $items[$columns["city"]-1];
			
		if($columns["postal_code"])
			$postal_code = $items[$columns["postal_code"]-1];
			
		if($columns["gender"])
			$gender = $items[$columns["gender"]-1];
			
		if($columns["birthdate"])
			$birthdate = $items[$columns["birthdate"]-1];
		
		if(!empty($email) && !empty($password)){
				
			if(!$settings["md5"])
				$password = md5($password);
				
			if($gender == $settings["male"])
				$gender = 1;
			elseif($gender == $settings["female"])
				$gender = 2;
			else
				$gender = 0;
				
			if($country){
				$sql_query = "SELECT con_id FROM geo_countries
							  WHERE name=':name:'";
				$GLOBALS["DB"]->values = array("name" => $country);
				$con_id = $GLOBALS["DB"]->single($sql_query);
				if(!$con_id && $settings["location"] == "add"){
					$sql_query = "INSERT INTO geo_countries (name)
								  VALUES (':name:')";
					$GLOBALS["DB"]->values = array("name" => $country);
					$con_id = $GLOBALS["DB"]->insert($sql_query);
				}//if
			}//if
			
			if($con_id && $state){
				$sql_query = "SELECT sta_id FROM geo_states
							  WHERE name=':name:'";
				$GLOBALS["DB"]->values = array("name" => $state);
				$sta_id = $GLOBALS["DB"]->single($sql_query);
				if(!$sta_id && $settings["location"] == "add"){
					$sql_query = "INSERT INTO geo_states (name)
								  VALUES (':name:')";
					$GLOBALS["DB"]->values = array("name" => $state);
					$sta_id = $GLOBALS["DB"]->insert($sql_query);
				}//if
			}//if
			
			if($sta_id && $city){
				$sql_query = "SELECT cty_id FROM geo_cities
							  WHERE name=':name:'";
				$GLOBALS["DB"]->values = array("name" => $city);
				$cty_id = $GLOBALS["DB"]->single($sql_query);
				if(!$cty_id && $settings["location"] == "add"){
					$sql_query = "INSERT INTO geo_cities (name)
								  VALUES (':name:')";
					$GLOBALS["DB"]->values = array("name" => $city);
					$cty_id = $GLOBALS["DB"]->insert($sql_query);
				}//if
			}//if
			
			$newmember["email"]    = $email;
			$newmember["username"] = $username;
			$newmember["password"] = $password;
			$newmember["fname"]    = $fname;
			$newmember["lname"]    = $lname;
			
			$GLOBALS["Member"]->values = $newmember;
			$mem_id = $GLOBALS["Member"]->create(1);
			if(!$mem_id){
				$report.= "Line ".$line_count.": email or username is already taken (".$email.")<br>";
				continue;
			}//if
			
			$sql_query = "UPDATE members SET verified='1'
						  WHERE mem_id=".$mem_id;
			$GLOBALS["DB"]->execute($sql_query);
			
			//building member's geo information
			$geo = build_geo_position($con_id,$sta_id,$cty_id,$postal_code);
			
			$dbvalues["latitude"]    = $geo["latitude"];
			$dbvalues["longitude"]   = $geo["longitude"]; 
			$dbvalues["state"]       = $geo["state"];
			$dbvalues["city"]        = $geo["city"];
			$dbvalues["country"]     = $con_id;
			$dbvalues["gender"]      = $gender;
			$dbvalues["birthdate"]   = $birthdate;
			$sql_query = "UPDATE profiles SET latitude=':latitude:',longitude=':longitude:',
						  state=':state:',city=':city:',country=':country:',gender=':gender:',
						  birthdate=':birthdate:'
						  WHERE mem_id=".$mem_id;
			$GLOBALS["DB"]->values = $dbvalues;
			$GLOBALS["DB"]->execute($sql_query);
			$imported++;
		}//if
		else
			$report.= "Line ".$line_count.": email or password is missing.<br>";
			
		$line_count++;
	}//while
	fclose($file_handler);
	
	$report = $imported." members successfully imported.<br>".$report;
	
	?><script language="JavaScript">
	<!--
		parent.HS_PullReport("<?php echo $report; ?>");
	//-->
	</script><?php
	
}//do_import_members

?>