<?php
class Users
{
	var $UserLimit = 15;
	
	
	function UserOverviewAjax()
	{
		if(perm('users_overview'))
		{
			$GLOBALS['tmpl']->assign('user', $this->listUser());
			$out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/user/user_overview_raw.tpl');
			echo $out;
		}
	}
	
	function DelUser($user,$details)
	{
		$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Geloescht='1', Geloescht_Email=Email, Email='', Aktiv='0' WHERE Id='$user'");
		Logger('User ' . $_SESSION['user_name'] . ' delete User: ' .  $details, '3', $_SESSION['benutzer_id']);
	}
	
	function UserOverview($new='')
	{
		if(perm('users_overview'))
		{
			// Multiaktionen
			if(isset($_POST['uaction']) && $_POST['uaction']!='')
			{
				if(perm('users_edit'))
				{
					switch($_POST['uaction'])
					{
						// Aktivieren
						case 'activate':
							$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Aktiv='1' " . $_SESSION['UserSearch'] . " AND Id!='1'");
						break;
						
						// Deaktivieren
						case 'deactivate':
							$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Aktiv='0' " . $_SESSION['UserSearch'] . " AND  Id!='1'");
						break;
						
						// Neue Gruppe
						case 'changegroup':
							$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Gruppe='" . $_POST['newgroup'] . "' " . $_SESSION['UserSearch'] . " AND  Id!='1'");
						break;
						
						// Loeschen
						case 'delete':
							$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Geloescht='1', Geloescht_Email=Email, Email='', Aktiv='0' " . $_SESSION['UserSearch'] . " AND  Id!='1'");
							$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_benutzer " . $_SESSION['UserSearch'] . " AND  Id!='1'");
						break;
						
						case 'sendmessage':
							if(isset($_POST['message_subject']) && $_POST['message_subject']!='' && isset($_POST['message_text']) && $_POST['message_text']!='')
							{
								$Koobi = new Koobi;
								$Subject = stripslashes($_POST['message_subject']);
								$Text    = $_POST['message_text'];
								
								$sql = $GLOBALS['db']->Query("SELECT  Email,Benutzername FROM " . PREFIX . "_benutzer " . $_SESSION['UserSearch']);
								while($res = $sql->fetchrow())
								{
									$Text    = $_POST['message_text'];
									$Text = str_replace('__USER__', $res->Benutzername, $Text);
									$Koobi->koobi_mail($res->Email, stripslashes($Text), $Subject, $GLOBALS['settings']['Mail_Absender'], stripslashes($GLOBALS['settings']['Mail_Name']), 'text', '');	
								}
							}
						break;
					}
					$GLOBALS['tmpl']->assign('action_done',1);
				}
			} else {
				unset($_SESSION['UserSearch']);
			}
			
			// Schnellspeichern aus der Uebersicht
			if(isset($_POST['quicksave']) && $_POST['quicksave']==1)
			{
				foreach($_POST['user'] as $uid => $u)
				{
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Gruppe = '" . $_POST['Gruppe'][$uid] . "' WHERE Id = '" . $_POST['user'][$uid] . "'");
					// Loeschen
					if(isset($_POST['del'][$uid])) $this->DelUser($_POST['user'][$uid], $_POST['deldetails'][$uid]);
				}
				
				
				
			}
			$GLOBALS['tmpl']->assign('user', $this->listUser($new));
			if($new=='new')
			{
				$out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/user/user_overview_small.tpl');
				return $out;	
			} else {
				$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Global_User']); 
				$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/user/user_overview.tpl'));
			}
		}
	}
	
	
	
	function getCountryShort($code)
	{
		$res = $GLOBALS['db']->RowQuery("SELECT Code FROM ".PREFIX."_laender WHERE Name='" . $code . "'");
		return $res->Code;
	}
	
	function getCountryName($code)
	{
		$res = $GLOBALS['db']->RowQuery("SELECT Name FROM ".PREFIX."_laender WHERE Code='" . strtoupper($code) . "'");
		return $res->Name;
	}
	
	function listUser($new='')
	{
		
		$def_order    = 'ORDER BY Id ASC';
		$def_order_n  = '';
		$def_search   = '';
		$def_search_n = '';
		$def_group    = '';
		$def_group_n  = '';
		$def_regtime  = '';
		$def_regtime_n = '';
		$def_lastonline = '';
		$def_lastonline_n = '';
		$def_aktive = '';
		$def_aktive_n = '';
		$db_shop_orders = '';
		$db_shop_orders_n = '';
		
		// Suche wurde gestartet...
		if(isset($_REQUEST['name']) && !empty($_REQUEST['name']) && strlen($_REQUEST['name'])>=1)
		{
			$name = trim(preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9.@ ]*)/', '', $_REQUEST['name']));
			$_REQUEST['name'] = $name;
			
			$def_search = " 
			AND (
				Benutzername LIKE '$name%' OR 
				Vorname LIKE '$name%' OR 
				Nachname LIKE '$name%' OR 
				Email LIKE '%$name' OR 
				Id = '$name'
			)";
			$def_search_n = "&name={$name}";
		}
		
		if(isset($_REQUEST['aktiv']) && $_REQUEST['aktiv']!='')
		{
			if($_REQUEST['aktiv']==0)
			{
				$def_aktive = " AND (Aktiv = '0') ";
				$def_aktive_n = "&amp;aktiv=0";
			} else {
				$def_aktive = " AND (Aktiv = '1') ";
				$def_aktive_n = "&amp;aktiv=1";
			}
		}
		
		// Suche mit Gruppe
		if(isset($_REQUEST['group']) && !empty($_REQUEST['group']))
		{
			$def_group = "AND (Gruppe='" . abs((int)$_REQUEST['group']) . "')";
			$def_group_n = "&group=" . abs((int)$_REQUEST['group']);
		}
		
		// Suche mit Reg-Datum
		if(!empty($_REQUEST['regfrom']) && !empty($_REQUEST['regtill']))
		{
			$rfrom = @explode('.',$_REQUEST['regfrom']);
			$rtill = @explode('.',$_REQUEST['regtill']);
			$rfrom = @mktime(0,0,1,$rfrom[1],$rfrom[0],$rfrom[2]);
			$rtill = @mktime(23,59,59,$rtill[1],$rtill[0],$rtill[2]);
			
			if($rfrom < $rtill)
			{
				$def_regtime = " AND (Regdatum BETWEEN '". abs((int)$rfrom) ."' AND '". abs((int)$rtill) ."') ";
				$def_regtime_n = "&regfrom=" . $_REQUEST['regfrom'] . "&regtill=" . $_REQUEST['regtill'];
			}
		}
		
		// Suche mit Datum der letzten Aktivitaet
		if(!empty($_REQUEST['lastonlinefrom']) && !empty($_REQUEST['lastonlinetill']))
		{
			$lafrom = @explode('.',$_REQUEST['lastonlinefrom']);
			$latill = @explode('.',$_REQUEST['lastonlinetill']);
			$lafrom = @mktime(0,0,1,$lafrom[1],$lafrom[0],$lafrom[2]);
			$latill = @mktime(23,59,59,$latill[1],$latill[0],$latill[2]);
			
			if($lafrom < $latill)
			{
				$def_lastonline = " AND (Zuletzt_Aktiv BETWEEN '". abs((int)$lafrom) ."' AND '". abs((int)$latill) ."') ";
				$def_lastonline_n = "&lastonlinefrom=" . $_REQUEST['lastonlinefrom'] . "&lastonlinetill=" . $_REQUEST['lastonlinetill'];
			}
		}
		
		// Sortierungen
		if(isset($_REQUEST['sort']))
		{
			$curr_page = ((isset($_REQUEST['page'])) ? '&page=' . abs((int)($_REQUEST['page'])) : '');
			
			switch($_REQUEST['sort'])
			{
				case 'name_asc' : 
					$def_order    = ' ORDER BY Nachname ASC';
					$def_order_n  = '&sort=name_asc' . $curr_page;
					$def_order_ns = '&sort=name_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('name_s',$def_order_ns);
				break;
				
				case 'name_desc': 
					$def_order    = ' ORDER BY Nachname DESC'; 
					$def_order_n  = '&sort=name_desc' . $curr_page;
					$def_order_ns = '&sort=name_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('name_s',$def_order_ns);
				break;
				
				case 'username_asc' : 
					$def_order    = ' ORDER BY Benutzername ASC';
					$def_order_n  = '&sort=username_asc' . $curr_page;
					$def_order_ns = '&sort=username_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('username_s',$def_order_ns);
				break;
				
				case 'username_desc' : 
					$def_order    = ' ORDER BY Benutzername DESC';
					$def_order_n  = '&sort=username_desc' . $curr_page;
					$def_order_ns = '&sort=username_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('username_s',$def_order_ns);
				break;
				
				case 'usergroup_asc' : 
					$def_order    = ' ORDER BY Gruppe ASC';
					$def_order_n  = '&sort=usergroup_asc' . $curr_page;
					$def_order_ns = '&sort=usergroup_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('usergroup_s',$def_order_ns);
				break;
				
				case 'usergroup_desc' : 
					$def_order    = ' ORDER BY Gruppe DESC';
					$def_order_n  = '&sort=usergroup_desc' . $curr_page;
					$def_order_ns = '&sort=usergroup_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('usergroup_s',$def_order_ns);
				break;

				case 'regdate_asc' : 
					$def_order    = ' ORDER BY Regdatum ASC';
					$def_order_n  = '&sort=regdate_asc' . $curr_page;
					$def_order_ns = '&sort=regdate_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('regdate_s',$def_order_ns);
				break;
				
				case 'regdate_desc' : 
					$def_order    = ' ORDER BY Regdatum DESC';
					$def_order_n  = '&sort=regdate_desc' . $curr_page;
					$def_order_ns = '&sort=regdate_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('regdate_s',$def_order_ns);
				break;
				
				
				case 'lastonline_asc' : 
					$def_order    = ' ORDER BY Zuletzt_Aktiv ASC';
					$def_order_n  = '&sort=lastonline_asc' . $curr_page;
					$def_order_ns = '&sort=lastonline_desc' . $curr_page;
					$GLOBALS['tmpl']->assign('regdate_s',$def_order_ns);
				break;
				
				case 'lastonline_desc' : 
					$def_order    = ' ORDER BY Zuletzt_Aktiv DESC';
					$def_order_n  = '&sort=lastonline_desc' . $curr_page;
					$def_order_ns = '&sort=lastonline_asc' . $curr_page;
					$GLOBALS['tmpl']->assign('lastonline_s',$def_order_ns);
				break;
			}
		}
		
		
		
		if(isset($_POST['startsearch']) && $_POST['startsearch']==1) 
		{
			$_SESSION['UserSearch'] = "WHERE Id!='0' AND Geloescht!='1' {$def_search} {$def_group} {$def_regtime} {$def_lastonline} {$def_aktive}";
		}
		if($new=='new') $def_order = ' ORDER BY Regdatum DESC';
		$sql = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_benutzer as a WHERE Id!='0' AND Geloescht!='1' {$def_search} {$def_group} {$def_regtime} {$def_lastonline} {$def_aktive} {$def_order}");
		$num = $sql->numrows();
	
		$limit = (isset($_REQUEST['limit']) && $_REQUEST['limit'] >= 1) ? $this->cleanNum($_REQUEST['limit']) : $this->UserLimit;
		if($new=='new') $limit = 5;
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
	
		$user = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Nachname,Benutzername,Email,Vorname,Gruppe,Aktiv,Zuletzt_Aktiv,Regdatum FROM " . PREFIX . "_benutzer as a WHERE 	Id!='0' AND  Geloescht!='1' {$def_search} {$def_group} {$def_regtime} {$def_lastonline} {$def_aktive} {$def_order} LIMIT $a,$limit");
		while($row = $sql->fetchrow())
		{
			$row->HasOrders = $this->HasOrders($row->Id);
			$row->hasESD = $this->hasUserDownloads($row->Id);
			array_push($user, $row);
		}
		
		// String fuer Navigation und Sortierung
		$ordstr = "index.php?do=user&sub=showusers{$def_search_n}{$def_group_n}{$def_regtime_n}{$def_lastonline_n}&amp;limit={$limit}{$def_aktive_n}{$db_shop_orders_n}";
		$nastr  = "{$def_search_n}{$def_group_n}{$def_regtime_n}{$def_lastonline_n}&amp;limit={$limit}{$def_aktive_n}{$db_shop_orders_n}{$def_order_n}";
		
		
		$GLOBALS['tmpl']->assign('limit',$limit);
		$GLOBALS['tmpl']->assign('ordstr',$ordstr);
		$GLOBALS['tmpl']->assign('groups',$this->UserGroups());
		if($num>$limit)$GLOBALS['tmpl']->assign('pages', pagenav($seiten, '', "<a class=\"page_navigation\" href=\"index.php?do=user&sub=showusers{$nastr}&limit={$limit}&page={s}\">{t}</a> "));
		
		
		return $user;
	}
	
	function HasOrders($user)
	{
		$res = $GLOBALS['db']->RowQuery("SELECT Id AS OrderCount FROM " . PREFIX . "_shop_bestellungen WHERE Benutzer = '$user' LIMIT 1");
		if(is_object($res))
		{
			return $res->OrderCount;
		}
	}
	
	/*
	function UserMultiaction($action)
	{
		switch($action)
		{
			case 'activate':
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Aktiv='1' " . $_SESSION['UserSearch'] . " AND Id!='1'");
			break;
			
			case 'deactivate':
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Aktiv='0' " . $_SESSION['UserSearch'] . " AND  Id!='1'");
			break;
		}
		echo '<script>parent.frames.location.reload();</script>';
		exit;
		header('Location:index.php?do=user&sub=showusers');
		
	}
	*/
	
	function AddUser()
	{
		if(perm('users_edit'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$error = '';
				$CName = $this->getCountryName($_POST['Land']);
				$PassRaw  = eregi_replace('[^@._A-Za-zÀ-ÖØ-öø-ÿ0-9]', '', $_POST['Kennwort']);
				$Pass  = md5(md5($PassRaw));
				
				$check = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_benutzer  WHERE Email='" . trim($_POST['Email']) . "' OR Benutzername='" . trim($_POST['Benutzername']) . "'");
				if(is_object($check) && $check->Email==trim($_POST['Email'])) $error[] = 'E-Mail schon vergeben.';
				if(is_object($check) && $check->Benutzername==trim($_POST['Benutzername'])) $error[] = 'Benutzername schon vergeben.';
				
				if($error)
				{	
					$GLOBALS['tmpl']->assign('error', $error);
				} else {
					$q = "INSERT INTO " . PREFIX . "_benutzer 
					(
						Id,
						Gruppe,
						GruppeMisc,
						Team,
						Regdatum,
						Email,
						Kennwort,
						Benutzername,
						Vorname,
						Nachname,
						Strasse_Nr,
						Postleitzahl,
						Ort,
						Firma,
						UStId,
						Telefon,
						Telefax,
						Land,
						LandCode,
						Aktiv,
						Profil_public,
						Profil_Alle,
						Emailempfang,
						Pnempfang,
						Gaestebuch,
						Zuletzt_Aktiv,
						Fsk18
					) VALUES (
						'',
						'" . $_POST['Gruppe'] . "',
						'" . @implode(';',$_POST['GruppeMisc']) . "',
						'" . @$_POST['Team'] . "',
						'" . stime() . "',
						'" . trim($_POST['Email']) . "',
						'" . $Pass . "',
						'" . $_POST['Benutzername'] . "',
						'" . $_POST['Vorname'] . "',
						'" . $_POST['Nachname'] . "',
						'" . $_POST['Strasse_Nr'] . "',
						'" . $_POST['Postleitzahl'] . "',
						'" . $_POST['Ort'] . "',
						'" . @$_POST['Firma'] . "',
						'" . @$_POST['UStId'] . "',
						'" . @$_POST['Telefon'] . "',
						'" . @$_POST['Telefax'] . "',
						'" . $CName . "',
						'" . $_POST['Land'] . "',
						'" . $_POST['Aktiv'] . "',
						'0',
						'0',
						'0',
						'0',
						'0',
						'" . stime() . "',
						'" . $_POST['Fsk18'] . "'
					)";
					$GLOBALS['db']->Query($q);
					$UserId = $GLOBALS['db']->InsertId();
					
					// Dem neuen Benutzer eine E-Mail mit Login-Daten senden
					if(isset($_POST['send_mail']) && $_POST['send_mail']==1)
					{
						$Subject = $GLOBALS['config_vars']['Shop_convertGuestMailSubject'];
						$Text    = $_POST['mail_text'];
						$Text    = str_replace('__WEBSITE__', WebLink(), $Text);
						$Text    = str_replace('__EMAIL__', trim($_POST['Email']), $Text);
						$Text    = str_replace('__PASS__', $PassRaw, $Text);
						
						$Koobi = new Koobi;
						$Koobi->koobi_mail(trim($_POST['Email']), stripslashes($Text), $Subject, $GLOBALS['settings']['Mail_Absender'], stripslashes($GLOBALS['settings']['Mail_Name']), 'text', '');	
					}
					$GLOBALS['tmpl']->assign('done', 1);
				}
				
			}
			
			$GLOBALS['tmpl']->assign('password', MakePass());
			$GLOBALS['tmpl']->assign('countries', Countries());
			$GLOBALS['tmpl']->assign('groups', UserGroups());
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['User_Add']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/user/userform_new.tpl'));
		}
	}
	
	
	
	function ConvertOrderToUser($order)
	{
		if(perm('shop_guestconvert'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$CName = $this->getCountryName($_POST['Land']);
				$PassRaw  = eregi_replace('[^@._A-Za-zÀ-ÖØ-öø-ÿ0-9]', '', $_POST['Kennwort']);
				$Pass  = md5(md5($PassRaw));
				
				$q = "INSERT INTO " . PREFIX . "_benutzer 
				(
					Id,
					Gruppe,
					GruppeMisc,
					Team,
					Regdatum,
					Email,
					Kennwort,
					Benutzername,
					Vorname,
					Nachname,
					Strasse_Nr,
					Postleitzahl,
					Ort,
					Firma,
					UStId,
					Telefon,
					Telefax,
					Land,
					LandCode,
					Aktiv,
					Profil_public,
					Profil_Alle,
					Emailempfang,
					Pnempfang,
					Gaestebuch,
					Zuletzt_Aktiv,
					Fsk18
				) VALUES (
					'',
					'" . $_POST['Gruppe'] . "',
					'" . @implode(';',$_POST['GruppeMisc']) . "',
					'" . @$_POST['Team'] . "',
					'" . stime() . "',
					'" . trim($_POST['Email']) . "',
					'" . $Pass . "',
					'" . $_POST['Benutzername'] . "',
					'" . $_POST['Vorname'] . "',
					'" . $_POST['Nachname'] . "',
					'" . $_POST['Strasse_Nr'] . "',
					'" . $_POST['Postleitzahl'] . "',
					'" . $_POST['Ort'] . "',
					'" . @$_POST['Firma'] . "',
					'" . @$_POST['UStId'] . "',
					'" . @$_POST['Telefon'] . "',
					'" . @$_POST['Telefax'] . "',
					'" . $CName . "',
					'" . $_POST['Land'] . "',
					'1',
					'0',
					'0',
					'0',
					'0',
					'0',
					'" . stime() . "',
					'" . @$_POST['Fsk18'] . "'
				)";
				$GLOBALS['db']->Query($q);
				
				// Gastbestellung aktualisieren
				if(isset($_REQUEST['order']) && !empty($_REQUEST['order']))
				{
					$UserId = $GLOBALS['db']->InsertId();
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_bestellungen SET Benutzer = '" . $UserId . "' WHERE Id = '" . $_REQUEST['order']. "'");
				}
				
				// Dem neuen Benutzer eine E-Mail mit Login-Daten senden
				if(isset($_POST['send_mail']) && $_POST['send_mail']==1)
				{
					$Subject = $GLOBALS['config_vars']['Shop_convertGuestMailSubject'];
					$Text    = $_POST['mail_text'];
					$Text    = str_replace('__WEBSITE__', WebLink(), $Text);
					$Text    = str_replace('__EMAIL__', trim($_POST['Email']), $Text);
					$Text    = str_replace('__PASS__', $PassRaw, $Text);
					
					$Koobi = new Koobi;
					$Koobi->koobi_mail(trim($_POST['Email']), stripslashes($Text), $Subject, $GLOBALS['settings']['Mail_Absender'], stripslashes($GLOBALS['settings']['Mail_Name']), 'text', '');	
				}
				echo '<script>window.opener.location.reload(); window.close();</script>';
			}
			$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_bestellungen WHERE Id='$order'");
			
			$GLOBALS['tmpl']->assign('password', MakePass());
			$GLOBALS['tmpl']->assign('countries', Countries());
			$GLOBALS['tmpl']->assign('country_short', $this->getCountryShort($res->Rng_Land));
			$GLOBALS['tmpl']->assign('groups', UserGroups());
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Global_User']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/user/guesttouser.tpl'));
		} else {
			no_perm();
		}
	}
	
	function EditUser($user)
	{
		if(perm('users_edit'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$CName = $this->getCountryName($_POST['Land']);
				$PassDb = '';
				
				if(isset($_POST['Kennwort']) && !empty($_POST['Kennwort']))
				{
					$PassRaw  = eregi_replace('[^@._A-Za-zÀ-ÖØ-öø-ÿ0-9]', '', $_POST['Kennwort']);
					$Pass  = md5(md5($PassRaw));
					$PassDb = "Kennwort = '" . $Pass . "',";
				}
				
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET 
					Gruppe = '" . (($user==1) ? 1 : $_POST['Gruppe']) . "',
					GruppeMisc = '" . @implode(';',$_POST['GruppeMisc']) . "',
					Team = '" . @$_POST['Team'] . "',
					Email = '" . trim($_POST['Email']) . "',
					{$PassDb}
					Benutzername = '" . $_POST['Benutzername'] . "',
					Vorname = '" . $_POST['Vorname'] . "',
					Nachname = '" . $_POST['Nachname'] . "',
					Strasse_Nr = '" . $_POST['Strasse_Nr'] . "',
					Postleitzahl = '" . $_POST['Postleitzahl'] . "',
					Ort = '" . $_POST['Ort'] . "',
					Firma = '" . @$_POST['Firma'] . "',
					UStId = '" . @$_POST['UStId'] . "',
					Telefon = '" . @$_POST['Telefon'] . "',
					Telefax = '" . @$_POST['Telefax'] . "',
					Land = '" . $CName . "',
					LandCode = '" . $_POST['Land'] . "',
					Aktiv = '" . (($user==1) ? 1 : $_POST['Aktiv']) . "',
					Geburtstag = '" . @$_POST['Geburtstag'] . "',
					Fsk18 = '" . $_POST['Fsk18'] . "' 
				WHERE 
					Id = '$user'
				");
				
					
					
				// Dem neuen Benutzer eine E-Mail  senden
				if(isset($_POST['send_mail']) && $_POST['send_mail']==1)
				{
					$Subject = $GLOBALS['config_vars']['User_profileChangeSubject'];
					$Text    = $_POST['mail_text'];
					$Text    = str_replace('__WEBSITE__', WebLink(), $Text);
					$Text    = str_replace('__EMAIL__', trim($_POST['Email']), $Text);
					$Text    = str_replace('__PASS__', ((isset($_POST['Kennwort']) && !empty($_POST['Kennwort'])) ? $PassRaw : $GLOBALS['config_vars']['User_profileChangePassUnd']), $Text);
					
					$Koobi = new Koobi;
					$Koobi->koobi_mail(trim($_POST['Email']), stripslashes($Text), $Subject, $GLOBALS['settings']['Mail_Absender'], stripslashes($GLOBALS['settings']['Mail_Name']), 'text', '');	
				}
				echo '<script>window.opener.location.reload(); window.close();</script>';
			}
			
			$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_benutzer WHERE Id='$user'");
			if(!is_object($res)) exit;
			
			$res->GroupsM = explode(';', $res->GruppeMisc);
			
			$GLOBALS['tmpl']->assign('mindate',date('Y')-50);
			$GLOBALS['tmpl']->assign('countries', Countries());
			$GLOBALS['tmpl']->assign('country_short', $this->getCountryShort($res->Land));
			$GLOBALS['tmpl']->assign('groups', UserGroups());
			$GLOBALS['tmpl']->assign('res', $res); 
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['User_edit']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/user/userform_newedit.tpl'));
		} else {
			no_perm();
		}
	}
	
	function hasUserDownloads($user)
	{
		$res = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS Numcount FROM " . PREFIX . "_shop_downloads_user WHERE Benutzer = '$user'");
		if($res->Numcount>=1)
			return true;
		else
			return false;
	}
	
	function OpenClose($w,$user)
	{
		if(perm('users_edit'))
		{
			switch($w)
			{
				case 'open': $GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Aktiv='1' WHERE Id='{$user}'"); break;
				case 'close': $GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Aktiv='0',RegCode='' WHERE Id='{$user}' AND Id!='1'"); break;
			}
			echo '<script>window.opener.location.reload(); window.close();</script>';
		}
	}
	
	function CheckUserData($oext='')
	{
		if(perm('shop_guestconvert'))
		{
			$uname = (isset($_REQUEST['Benutzername']) && !empty($_REQUEST['Benutzername'])) ? trim(strtolower(eregi_replace('[^@._A-Za-zÀ-ÖØ-öø-ÿ0-9 ]', '', $_REQUEST['Benutzername']))) : '';
			$mail  = (isset($_REQUEST['Email']) && !empty($_REQUEST['Email'])) ? trim(strtolower(eregi_replace('[^@._A-Za-zÀ-ÖØ-öø-ÿ0-9]', '', $_REQUEST['Email']))) : '';
			if($mail!='') 
			{
				$mailex = ($oext!='') ? " AND Email != '$oext'" : "";
				$res = $GLOBALS['db']->RowQuery("SELECT Email FROM " . PREFIX . "_benutzer WHERE Email = '$mail' {$mailex}");
				if(is_object($res)) $valid = 'false';
				else $valid = 'true'; 
			}
			
			if($uname!='') 
			{
				$userex = ($oext!='') ? " AND Benutzername != '$oext'" : "";
				$res = $GLOBALS['db']->RowQuery("SELECT Benutzername FROM " . PREFIX . "_benutzer WHERE Benutzername = '$uname' {$userex}");
				if(is_object($res)) $valid = 'false';
				else $valid = 'true'; 
			}
			echo $valid;
		}
	}
	

	
	//=================================================================
	// Benutzergruppen listen
	//=================================================================
	function UserGroups()
	{
		$groups = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Name_Intern,Name FROM ".PREFIX."_benutzer_gruppen ORDER BY Id ASC");
		while($row = $sql->fetchrow())
		{
			array_push($groups,$row);
		}
		return $groups;
	}
	
	
	function cleanNum($var)
	{
		return trim(eregi_replace('[^0-9]', '', $var));
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
		// TODO!!!
	function OrderImport($prefix,$delete=0)
	{
		if(perm('settings'))
		{
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_bestellungen WHERE Id!=1");
			
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . $prefix . "_modul_shop_bestellungen");
			while($r = $sql->fetchrow())
			{
				switch($r->ZahlungsId)
				{
					case '3':$r->ZahlungsId = '9';break;
					case '4':$r->ZahlungsId = '5';break;
					case '5':$r->ZahlungsId = '3';break;
					case '6':$r->ZahlungsId = '8';break;
					case '7':$r->ZahlungsId = '6';break;
					default:$r->ZahlungsId = $r->ZahlungsId;break;
				}
				
				switch($r->VersandId)
				{
					case '1':$r->VersandId = '1';break;
					case '2':$r->VersandId = '1';break;
					case '3':$r->VersandId = '3';break;
					case '4':$r->VersandId = '5';break;
					case '6':$r->VersandId = '5';break;
					default:$r->VersandId = $r->VersandId;break;
				}
				
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_bestellungen
				(
					Id, 
					Datum,
					Ip,
					Benutzer,
					Betrag,
					Status,
					Artikel,
					TransaktionsNummer,
					ZahlungsId,
					VersandId,
					Rng_Firma, 	    	
					Rng_Anrede, 	
					Rng_Vorname,
					Rng_Nachname,
					Rng_Strasse,
					Rng_Plz,
					Rng_Ort,
					Rng_Land,
					Rng_Fon,
					Rng_Email,
					Lief_Vorname,  	 	
					Lief_Nachname, 		
					Lief_Strasse, 		
					Lief_Plz, 		
					Lief_Ort, 			
					Lief_Land,
					Lief_Firma,
					Bestellung,
					KundenNachricht,
					Bemerkung
				) VALUES (
					'',
					'$r->Datum',
					'$r->Ip',
					'$r->Benutzer',
					'$r->Gesamt',
					'" . (($r->Status=='ok_send') ? 'oksend' : $r->Status)  . "',
					'$r->Artikel',
					'$r->TransId',
					'$r->ZahlungsId',
					'$r->VersandId',
					'" . mysql_escape_string($r->Rech_Firma) . "',
					'',
					'" . mysql_escape_string($r->Rech_Vorname) . "',
					'" . mysql_escape_string($r->Rech_Nachname) . "',
					'" . mysql_escape_string($r->Rech_Strasse) . "',
					'" . mysql_escape_string($r->Rech_PLZ) . "',
					'" . mysql_escape_string($r->Rech_Ort) . "',
					'" . strtolower($r->Rech_Land) . "',
					'',
					'$r->Bestell_Email',
					'" . mysql_escape_string($r->Liefer_Vorname) . "',
					'" . mysql_escape_string($r->Liefer_Nachname) . "',
					'" . mysql_escape_string($r->Liefer_Strasse . ' ' .$r->Liefer_Hnr) . "',
					'" . mysql_escape_string($r->Liefer_PLZ) . "',
					'" . mysql_escape_string($r->Liefer_Ort) . "',
					'" . strtolower($r->Liefer_Land) . "',
					'" . mysql_escape_string($r->Liefer_Firma) . "',
					'" . base64_encode($r->RechnungHtml) . "',
					'" . mysql_escape_string($r->NachrichtBenutzer) . "',
					'" . mysql_escape_string($r->NachrichtAdmin) . "'
				)");
			}
			
			
			
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . $prefix . "_modul_shop_artikel_downloads");
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX. "_shop_downloads");
			while($row = $sql->fetchrow())
			{
				$newid = '';
				switch($row->ArtId)
				{
					case '18': $newid = '4'; //LIGHT
					break;
					
					case '17': $newid = '2'; //STANDARD
					break;
					
					case '15': $newid = '1'; //PRO
					break;
				}
				
				if($newid!='')
				{
					$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_downloads 
					VALUES (
						'".$row->Id."',
						'".$newid."',
						'".$row->Datei."',
						'".$row->DateiTyp."',
						'".$row->TageNachKauf."',
						'".$row->Bild."',
						'".$row->Titel."',
						'".addslashes($row->Beschreibung)."',
						'".$row->Position."',
						'".$row->Datum."'
					)");
				}
			}
			
			
			include_once(BASE_DIR . '/admin/class/class.shop.php');
			$shop = new Shop;
			
			$GLOBALS['db']->Query("DELETE FROM " .PREFIX . "_shop_lizenzen");
			$GLOBALS['db']->Query("DELETE FROM " .PREFIX . "_shop_downloads_user");
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . $prefix . "_modul_shop_downloads");
			while($row = $sql->fetchrow())
			{
				$newid = '';
				switch($row->ArtikelId)
				{
					case '100020': $newid = '4'; //LIGHT
					break;
					
					case '100001': $newid = '2'; //STANDARD
					break;
					
					case '100010': $newid = '1'; //PRO
					break;
				}
				
				if($newid!='')
				{
					$lic = $shop->newKey();
					
					$insert = $GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_lizenzen VALUES 
					(
						'',
						'".$row->Benutzer."',
						'$lic',
						'".time()."',
						'".date('Y-m-d H:i:s')."',
						'".$row->PName."',
						'".$row->DownloadBis."',
						'".$newid."'
					)");
					
					$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_downloads_user 
					VALUES (
						'".$row->Id."',
						'".$row->Benutzer."',
						'".$row->PName."',
						'".$newid."',
						'".$row->DownloadBis."',
						'".$lic."',
						'".$row->Downloads."',
						'".addslashes($row->UrlLizenz)."',
						'".addslashes($row->KommentarBenutzer)."',
						'".addslashes($row->KommentarAdmin)."',
						'".addslashes($row->Gesperrt)."',
						'".addslashes($row->GesperrtGrund)."',
						'".addslashes($row->Position)."',
						'1'
					)");
				}
			}
			
			
			$this->UserImport('cp',1);
		}
	}
	
	function UserImport($prefix,$delete=0)
	{
		if(perm('settings'))
		{
			if($delete==1) $GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_benutzer WHERE Id != '1'");
			
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . $prefix . "_benutzer WHERE Id != 1");
			while($row = $sql->fetchrow())
			{
				switch($row->Benutzergruppe)
				{
					case '5':$row->Benutzergruppe = '6';break;
					case '6':$row->Benutzergruppe = '5';break;
					case '8':$row->Benutzergruppe = '7';break;
					case '12':$row->Benutzergruppe = '8';break;
					default:$row->Benutzergruppe = $row->Benutzergruppe;break;
				}
				
				$row->BenutzergruppeMisc = str_replace(array(5,6,8,12), array(6,5,7,8), $row->BenutzergruppeMisc);
				
				
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_benutzer
				(
					Id,
					Gruppe,
					GruppeMisc,
					Email,
					Kennwort,
					Benutzername,
					Vorname,
					Nachname,
					Regdatum,
					Zuletzt_Aktiv,
					Geburtstag,
					Aktiv,
					Strasse_Nr,
					Postleitzahl,
					Ort,
					Land,
					LandCode 
				) VALUES (
					'$row->Id',
					'$row->Benutzergruppe',
					'" . (str_replace(';',';',$row->BenutzergruppeMisc) . "',
					'$row->Email',
					'$row->Kennwort',
					'" . ((@$row->Username=='') ? $row->Vorname . ' ' . substr($row->Nachname,0,1) . '.' : $row->Username). "',
					'$row->Vorname',
					'$row->Nachname',
					'$row->Registriert',
					'" . (($row->ZuletztGesehen>1) ? $row->ZuletztGesehen : $row->Registriert) . "',
					'$row->GebTag',
					'$row->Status',
					'$row->Strasse $row->HausNr',
					'$row->Postleitzahl',
					'$row->Ort',
					'" . ($this->getCountryName(strtolower($row->Land)))) . "',
					'" . (strtolower($row->Land)) . "'
				)");
			}
			header('Location:index.php?do=user&sub=showusers');
			exit;
		}
	}
	
	
	
	
	
}
?>