<?php
// ======================================================================== //
//                                                                          //
//   KooBI- Webportalsystem                                                 //
//   SCRiPTMAFiA 2005 - THE DiRTY HANDS ON YOUR SCRiPTS                     //
//                                                                          //
//   ====================================================================   //
//                                                                          //   
//   dream4 | webservices - Am Michelsgrund 7 - 69469 Weinheim - Germany    //    
//   tel. +49(0) 6201 - 980442 / fax. +49(0) 6201 - 64809                   //
//                                                                          //
// ======================================================================== //
if(!checkactive('register')) include(dirname(__FILE__)."/lib/notactive.php" );

$use_securecode = "";
if( (@extension_loaded("gd") == 1)  && ($securecode_by_register == 1) ) {
	$use_securecode = 1;
}

// ==========================================================
// <<-- pflichtfelder -->>
// ==========================================================
$required_fields = array();
$required_userfields = array();
$sqlfields = new dbc("SELECT * FROM " . PREFIX . "_userfields WHERE page='register' AND active='yes' AND required='yes' ORDER BY posi ASC");
while($row_uf = $sqlfields->fetchrow()){
	
	$required_fields[] = $row_uf->fieldname;
	$row_uf->fieldtext = $lang['userfields_' . $row_uf->fieldname];
	$row_uf->fieldval = $_REQUEST[$row_uf->fieldname];
	
	switch($row_uf->fieldname){
		case "pass":
		case "pass2":
		$row_uf->fieldtype = "password";
		break;
		
		default :
		$row_uf->fieldtype = "text";
		break;
	}
	
	
	array_push($required_userfields, $row_uf);
}
$tmpl->assign('ruf', $required_userfields);
// ==========================================================


// ==========================================================
// <<-- optonale felder -->>
// ==========================================================
$optional_fields = array();
$optional_userfields = array();
$sqlfields = new dbc("SELECT * FROM " . PREFIX . "_userfields WHERE page='register' AND active='yes' AND required='no' ORDER BY posi ASC");
while($row_of = $sqlfields->fetchrow()){
	
	$optional_fields[] = $row_of->fieldname;
	$row_of->fieldtext = $lang['userfields_' . $row_of->fieldname];
	$row_of->fieldval = $_REQUEST[$row_of->fieldname];
	
	switch($row_of->fieldname){
		case "pass":
		case "pass2":
		$row_of->fieldtype = "password";
		break;
		
		default :
		$row_of->fieldtype = "text";
		break;
	}
	
	
	array_push($optional_userfields, $row_of);
}
$tmpl->assign('ouf', $optional_userfields);

// ==========================================================

$mtime = time()-1800;
$sql = new dbc("DELETE FROM ".PREFIX."_securecode WHERE ctime<$mtime");
$sql->close();

$sql = new dbc("SELECT regtype,mailbyregister FROM " . PREFIX . "_settings");
$row = $sql->fetchrow();
$pref['regtype'] = $row->regtype;
$pref['mailbyregister'] = $row->mailbyregister;

$sname = $lang['register'];
if($islogged==1){
	$EOUT = msg("error_once", "registernew" , str_replace("__URL__", "index.php", $lang['redirect']), "index.php");
	$NOOUT = 1;
	$sname = $lang['register'];
}

// Wenn Benutzer EMail-Link folgt
if(isset($_REQUEST['action']) && $_REQUEST['action']=="activate"){
	$sname = $lang['registerfinalstep'];
	$ok = 1;
	
	// Wenn nur Freischaltung durch Admin...
	if($pref['regtype']=="admin"){
		$EOUT = msg("registerfinalstep", "errornoactivasion" , str_replace("__URL__", "index.php", $lang['redirect']), "index.php");
		$NOOUT = 1;
		$ok = -1;
		$nometa = 1;
	}
	
	// Stimmt Code?
	if($ok==1){
		$sql =& new dbc("SELECT uid FROM ".PREFIX."_user WHERE pass='".escs($_REQUEST['code'])."' AND status!='1'");
		$num = $sql->numrows();
		$row = $sql->fetchrow();
		$sql->close();
		$thecookieid = $row->uid;
		
		if(($num>0) && ($_REQUEST['code']!="")){
			$sql =& new dbc("UPDATE ".PREFIX."_user SET status='1' WHERE pass='".escs($_REQUEST['code'])."'");
			$sql->close();
			$ok = 1;
		} else {
			$EOUT = msg("registerfinalstep", "activated_notok" , str_replace("__URL__", "index.php", $lang['redirect']), "index.php");
			$NOOUT = 1;
			$nometa = 1;
			$ok = -1;
		}
	}
	
	
	
	if($ok==1){
		$EOUT = msg("registerfinalstep", "activatedok2" , str_replace("__URL__", "index.php", $lang['redirect']), "index.php");
		$NOOUT = 1;
		$nometa = 1;
		$sname = $lang['registerfinalstep'];
		setcookie("kuid", $thecookieid, time()+(365*24*3600));
		setcookie("kpass",escs($_REQUEST['code']),time()+(365*24*3600));
	}
	} else {
	
	
	// Wenn Neuregistrierung
	
	// Sicherheitscode generieren (nur, wenn nicht abgesendet)
	if($use_securecode == 1){
		if(!isset($_REQUEST['send']) && $_REQUEST['send']=="") {
			$code = securecode();
			$sql =& new dbc("INSERT INTO ".PREFIX."_securecode (id,code,ctime) VALUES ('','".$code."','".time()."')");
			$codeid = $sql->getid();
			$sql->close();
		} elseif (isset($_REQUEST['send']) && $_REQUEST['send']==1) {
			$codeid = $_REQUEST['pim'];
			$sql =& new dbc("SELECT code FROM ".PREFIX."_securecode WHERE id='".$codeid."'");
			$row = $sql->fetchrow();
			$sql->close();
			$securecode = $row->code;
		}
	}
	
	$errors = array();
	if(isset($_REQUEST['send']) && $_REQUEST['send']==1) { // Absenden //
		$ok = "1";
		
		// Formular wird nun überprüft...
		// Abgeschickten Namen nach Sonderzeichen durchsuchen
		$puname = str_replace(array("[","]",":","(",")","=",",","'"), "", $_POST['uname']);

		
		// Wurde ein Benutzername angegeben?
		if( (empty($_POST['uname'])) && (in_array("uname", $required_fields)) ){
			array_push($errors, $lang['nousername']);
			$ok = "0";
		}
		
		// Ist Benutzername in Bannliste eingetragen?
		if( (bannedname($_POST['uname'])) && (in_array("uname", $required_fields)) ){
			array_push($errors, $lang['banned']);
			$ok = "0";
		}
		
		// Wenn kein Fehler, prüfen, ob dieser Name schon existiert
		if($ok==1){
			$sql = new dbc("SELECT uid FROM " . PREFIX . "_user WHERE uname='".escs($_POST['uname'])."'");
			$c= $sql->numrows();
			
			if($c > 0){
				array_push($errors, $lang['nameexists2']);
				$ok = "0";
			}
			if($ok==1){
				$adminuname = "uname='".escs(iform($_POST['uname'],"65",""))."',";
			}
		}
		
		// Stimmen beide Email-Adressen überein?
		if((empty($_REQUEST['email2'])) && (in_array("email", $required_fields)) ){
			array_push($errors, $lang['emailempty2']);
			$ok = "0";
		}
		
		if(($_REQUEST['email2'] != $_REQUEST['email']) && (in_array("email", $required_fields)) ){
			array_push($errors, $lang['emailnotmatch']);
			$ok = "0";
		}
		
		// Sind beide Emai-Adressen korrekt?
		if((!@ereg("^[ -._A-Za-zÀ-ÖØ-öø-ÿ0-9-]+(\.[_A-Za-zÀ-ÖØ-öø-ÿ0-9-]+)*@([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,4})$", $_REQUEST['email'])) && (in_array("email", $required_fields)) ){
			array_push($errors, $lang['emailerror']);
			$ok = "0";
		}
		
		
		
		if((!@ereg("^[ -._A-Za-zÀ-ÖØ-öø-ÿ0-9-]+(\.[_A-Za-zÀ-ÖØ-öø-ÿ0-9-]+)*@([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,4})$", $_REQUEST['email2'])) && (in_array("email", $required_fields)) ){
			array_push($errors, $lang['emailerror']);
			$ok = "0";
		}
		
		// Wurden beide Kennwörter ausgefüllt, ist es mind. 5 Zeichen lang und stimmen sie überein?
		if(empty($_POST['pass'])){
			array_push($errors, $lang['error_nopw']);
			$ok = "0";
		}
		
		// Wenn Kennwort nicht wiederholt wird...
		if(empty($_POST['pass2'])){
			array_push($errors, $lang['error_nopw2']);
			$ok = "0";
		}
		
		// Werden Sonderzeichen verwendet?
		if(isset($_POST['pass']) && $_POST['pass']!=""){
			$pwcheck = str_replace(array("[","]",":","(",")","="), "", $_POST['pass']);
			if(@ereg("[^ ._A-Za-zÀ-ÖØ-öø-ÿ0-9-]", $pwcheck)){
				array_push($errors, $lang['error_pnospecial']);
				$ok = "0";
			}
		}
		
		$pw1 = iform($_POST['pass'],"35","");
		$pw2 = iform($_POST['pass2'],"35","");
		
		// Stimmen beide Kennwörter überein?
		if((isset($_POST['pass']) && isset($_POST['pass2'])) && ($pw1 != $pw2)){
			array_push($errors, $lang['error_reg_pw']);
			$ok = "0";
		}
		
		// Ist Kennwort kürzer als 5 Zeichen?
		if(isset($_POST['pass']) &&  ($_POST['pass']!="") && (strlen($pw1) <5) ){
			array_push($errors, $lang['error_ptoshort']);
			$ok = "0";
		}
		
		
		
		// existiert Email schon?
		if($ok == 1){
			$sql2 = new dbc("SELECT uid FROM " . PREFIX . "_user WHERE email='".escs($_REQUEST['email'])."'");
			$c2 = $sql2->numrows();
			
			if($c2 > 0){
				array_push($errors, $lang['emailexits']);
				$ok = "0";
			}
			
			// wurde eine email angegeben?
			if(empty($_REQUEST['email'])){
				array_push($errors, $lang['emailempty']);
				$ok = "0";
			}
		}
		
		// Wenn Geburtstag nicht angegeben...
		if((empty($_REQUEST['user_birthday'])) && (in_array("user_birthday", $required_fields)) ){
			array_push($errors, $lang['error_nobirthday']);
			$ok = "0";
		}
		
		if((!@ereg("^([0-9]{2})+(\.[0-9]+)+(\.[0-9]{4})$", $_REQUEST['user_birthday'])) && (in_array("user_birthday", $required_fields)) ){
			array_push($errors, $lang['error_bithday_wrong']);
			$ok = "0";
		}
		
		
		
		// sonstiges (icq, aim, eigene felder)
		$sqlfields = new dbc("SELECT * FROM " . PREFIX . "_userfields WHERE page='register' AND active='yes' AND type='other' AND required='yes' ORDER BY posi ASC");
		while($row_ufs = $sqlfields->fetchrow()){
			
			
			if((empty($_REQUEST[$row_ufs->fieldname])) && (in_array($row_ufs->fieldname, $required_fields)) ){
				if($lang["userfields_" . $row_ufs->fieldname . "_no"] == "" ){
					array_push($errors, $row_ufs->extra_error);
				} else {
					array_push($errors, $lang["userfields_" . $row_ufs->fieldname . "_no"]);
				}
				$ok = "0";
			}
		}
		
		// Wenn Sicherheitscode nicht übereinstimmt...
		if($use_securecode == 1){
			if($_REQUEST['scode'] != $securecode){
				array_push($errors, $lang['securecodeiswrong']);
				$ok = "0";
			}
		}
		
		
		// Wenn Regeln nicht akzeptiert...
		if(!isset($_REQUEST['rulez']) && $_REQUEST['rulez']!=1){
			array_push($errors, $lang['rulez_taccept_error']);
			$ok = "0";
		}
		
		// Wenn Fehler vorhanden sind, Fehlerroutine ausgeben...
		if(($ok==0) && (isset($_REQUEST['send']))){
			$tmpl->assign('title_error', $lang['error']);
			$tmpl->assign('iserror', 1);
			$tmpl->assign('errors', $errors);
		}
		
		// Wenn keine Fehler in die db eintragen und je nach Aktivierungsoption Meldung ausgeben
		if(($ok==1) && (isset($_REQUEST['send']))){
			switch ($pref['regtype']){
				case norm:
				$status = 0;
				$EOUT = msg("register", "regoknorm", str_replace("__URL__", "index.php", $lang['redirect']), "index.php");
				$NOOUT = 1;
				$message = $lang['regoknorm_emailbody'];
				$message = str_replace("__USERNAME__", escs($_POST['uname']), $message);
				$message = str_replace("__LINK__", "http://" . $_SERVER['HTTP_HOST'].str_replace("/index.php","",$_SERVER['PHP_SELF']), $message);
				$message = str_replace("__PASS__", $_POST['pass'], $message);
				$message = str_replace("__AKTLINK__", "http://" . $_SERVER['HTTP_HOST'].str_replace("/index.php","",$_SERVER['PHP_SELF'])."/index.php?p=register&action=activate&code=".md5($_POST['pass'])."",$message);
				$message = str_replace("__HOMEPAGENAME__", $pref['hpname'], $message);
				break;
				case now:
				$status = 1;
				$EOUT = msg("register", "regoknow", str_replace("__URL__", "index.php", $lang['redirect']), "index.php");
				$NOOUT = 1;
				$message = $lang['regoknow_emailbody'];
				$message = str_replace("__USERNAME__", escs($_POST['uname']), $message);
				$message = str_replace("__LINK__", "http://" . $_SERVER['HTTP_HOST'].str_replace("/index.php","",$_SERVER['PHP_SELF']), $message);
				$message = str_replace("__PASS__", $_POST['pass'], $message);
				$message = str_replace("__HOMEPAGENAME__", $pref['hpname'], $message);
				break;
				case admin:
				$status = 0;
				$EOUT = msg("register", "regokadmin", str_replace("__URL__", "index.php", $lang['redirect']), "index.php");
				$NOOUT = 1;
				$message = $lang['regokadmin_emailbody'];
				$message = str_replace("__USERNAME__", escs($_POST['uname']), $message);
				$message = str_replace("__LINK__", "http://" . $_SERVER['HTTP_HOST'].str_replace("/index.php","",$_SERVER['PHP_SELF']), $message);
				$message = str_replace("__PASS__", $_POST['pass'], $message);
				$message = str_replace("__HOMEPAGENAME__", $pref['hpname'], $message);
				break;
			}
			
			// =========================================================		
			// eintrag...		
			// =========================================================
			$insert = array();	
			$sql = new dbc("SELECT * FROM " . PREFIX . "_userfields 
			WHERE page='register' 
			AND fieldname != 'pass2' 
			AND fieldname != 'email2' 
			AND  active='yes' 
			ORDER BY posi ASC");
			
			while($row = $sql->fetchrow()){
				$fielddata = strip_tags(mysql_escape_string($_REQUEST[$row->fieldname]));
				switch($row->fieldname){
					case 'pass' :
					$data = md5($fielddata);
					break;
					
					case 'user_interests' :
					case 'user_sig' :
					$data = substr($fielddata, 0, 300);
					break;
					
					default :
					$data =  $fielddata;
					break;
				}
				
				if($data != ""){
					$insert[]     = "$row->fieldname";
					$insertdata[] = "'$data'";
				}
			}
			
			$pre = "INSERT INTO ".PREFIX."_user (uid, ugroup, status, user_regdate, ";
			$middle = " ) VALUES ('', 3, '$status', '".time()."', "; 
			$after  = " )";
			
			$q = $pre . implode(",", $insert) . $middle . implode(",", $insertdata) . $after;
			$sql = new dbc("$q");
			// =========================================================				
			
			// Temp-Code aus db löschen
			$sql = new dbc("DELETE FROM ".PREFIX."_securecode WHERE code='".$_REQUEST['scode']."'");
			$sql->close();
			
			// Bei sofortiger Freischaltung automtisch einloggen
			if($pref['regtype'] == "now"){
				setcookie("kuid", $sql->getid(), time()+(365*24*3600));
				setcookie("kpass",md5($_POST['pass']),time()+(365*24*3600));
			}
			
			
			$subject = str_replace("__HOMEPAGENAME__", $pref['hpname'], $lang['regok_emailsubject']);
			$body = str_replace("\n","\n\n", $message);
			
			// registrierungs- email senden
			@mail($_POST['email'], $subject, stripslashes($body),
				"From: $pref[sendemail]\r\n"
				."Reply-To: $pref[sendemail]\r\n"
				."X-Mailer: PHP/" . phpversion());
			
			// Ist die Option "Mail bei Neuregistrierung" aktiviert?
			if($pref['mailbyregister']==1){
				$subject = str_replace("__HOMEPAGENAME__", $pref['hpname'], $lang['emailbyregistersubject']);
				$message = $lang['emailbyregisterbody'];
				$message = str_replace("__NAME__", $_POST['uname'], $message);
				$message = str_replace("__EMAIL__", $_POST['email'], $message);
				
				$body = str_replace("\n","\n\n", $message);
				
				@mail($pref['sendemail'], $subject, stripslashes($body),
				"From: $pref[company_email_reply]\r\n"
				."Reply-To: $pref[company_email_reply]\r\n"
				."X-Mailer: PHP/" . phpversion());
			}
			
			$REDIR = 1;	
		} // Ende User in db eintragen
		
	} // Absenden //
	
	// Regeln aus Sprachdatei einlesen...
	$regrules = $lang['siterulesregister'];
	$regrules = str_replace("__SITENAME__", $pref['hpname'], $regrules);
	$regrules = str_replace("__ADMINMAIL__", $pref['sendemail'], $regrules);
	
	// Checkbox "Regeln akzeptieren"...
	if(isset($_REQUEST['rulez']) && $_REQUEST['rulez']==1){
		$rulezchecked = "checked";
	}
	
	
	
	$disp_securepng = ($use_securecode == 1) ? 1 : 0;
	$tmpl->assign('disp_securepng', $disp_securepng);
	$tmpl->assign('global', $global);
	$tmpl->assign('rulezcheckbox', '<input name="rulez" type="checkbox" id="rulez" value="1" '.$rulezchecked.'>');
	$tmpl->assign('msg', $lang['registerhead']);
	$tmpl->assign('pim', $codeid);
	$tmpl->assign('secuid', $codeid);
	$tmpl->assign('regrules',  $regrules);
	$tmpl->assign('postscode' , $_REQUEST['scode']);
	$tmpl->assign('register_notoksure' , $lang['register_notoksure']);
	$tmpl->assign('pref', $pref);
	
	if($REDIR == 1){
		$nometa = 1;
	} else {
		$tmpl->assign("content", parsetrue("container/".container("register"), $lang['register'], $tmpl->fetch("user/register.tpl")));
	}
}
?>