<?php // $Id: inscription_second.php,v 1.48 2005/05/18 11:37:06 bmol Exp $ 
/*
============================================================================== 
	Dokeos - elearning and course management software
	
	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 Ghent University (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	Copyright (c) various contributors
	
	For a full list of contributors, see "credits.txt".
	The full license can be read in "license.txt".
	
	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.
	
	See the GNU General Public License for more details.
	
	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
============================================================================== 
*/
/**
==============================================================================
*	This script reacts on the form data normally delivered by inscription.php
*	to register users into Dokeos.
*	(but malicious users can easily send POST data from their own scripts).
*
*	@package dokeos.auth
============================================================================== 
*/

/*==========================
             INIT
  ==========================*/

$langFile = 'registration';
require("../inc/claro_init_global.inc.php");

//$TABLEUSER      = $mysqlMainDb."`.`user";
$TABLEUSER      = Database::get_main_table(MAIN_USER_TABLE);

define ("CHECK_PASS_EASY_TO_FIND", false);

if (!isset($userMailCanBeEmpty))   $userMailCanBeEmpty   = true;
if (!isset($checkEmailByHashSent)) $checkEmailByHashSent = false;
if (!isset($userPasswordCrypted))  $userPasswordCrypted	 = false;

$regDataOk = false; // default value...

if(!empty($_POST['submitRegistration']))
{
	$regexp = "^[0-9a-z_\.-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z-]*[0-9a-z]\.)+[a-z]{2,4})$";
	$uname         = trim ($_POST["uname"]);
	$email         = trim ($_POST["email"]);
	$official_code = trim ($_POST["official_code"]);
	$lastname      = trim ($_POST["lastname"]);
	$firstname     = trim ($_POST["firstname"]);
	$password      = trim ($_POST["password"]);
	$password1     = trim ($_POST["password1"]);

	$status=($_POST['status'] == COURSEMANAGER)?COURSEMANAGER:STUDENT;

	$uname=eregi_replace('[^a-z0-9_.-]','_',strtr(stripslashes($uname),'ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ','AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn'));

	/*==========================
	   DATA SUBIMITED CHECKIN
	  ==========================*/

	// CHECK IF THERE IS NO EMPTY FIELD
	$errempty = 0;
	if (empty($lastname)) {
		$errempty = 1;
		$error_message .=	"<p>".get_lang('langEmptySurname')."</p>\n";
	}
	if (empty($firstname)) {
		$errempty = 1;
		$error_message .=	"<p>".get_lang('langEmptyName')."</p>\n";
	}
	if (empty($uname)) {
		$errempty = 1;
		$error_message .=	"<p>".get_lang('PleaseEnterValidLogin')."</p>\n";
	}
	if (empty($password1)) {
		$errempty = 1;
		$error_message .=	"<p>".get_lang('EmptyPassword')."</p>\n";
	} elseif (empty($password)) {
		$errempty = 1;
		$error_message .=	"<p>".get_lang('EmptyPassword')."</p>\n";
	}
	if (empty($email)) {
		$errempty = 1;
		$error_message .=	"<p>".get_lang('EmailWrong')."</p>\n";
	}
	if ($errempty) {
		$regDataOk = false;
		unset($password1, $password);
		$error_message .=   "<p>".get_lang('langBackandTry')."</p>\n";
	}
/*	if (
		   empty($lastname)
		OR empty($firstname)
		OR (empty($official_code) 
			AND (get_setting('registration','officialcode')=="true"))
		OR empty($password1)
		OR empty($password)
		OR empty($uname)
		OR (empty($email) && !$userMailCanBeEmpty)
			)
	{
		$regDataOk = false;

		unset($password1, $password);

		$error_message .=	"<p>".get_lang('langEmptyFields')."</p>\n" . get_lang('langRegistration');
	}*/
	

	// CHECK IF THE TWO PASSWORD TOKEN ARE IDENTICAL

	elseif($password1 != $password)
	{
		$regDataOk = false;
		unset($password1, $password);

		$error_message .= "<p>".get_lang('langPassTwice')."</p>\n";
	}
	elseif(CHECK_PASS_EASY_TO_FIND && !api_check_password($password))
	{
		$error_message .= "<p>".get_lang('langPassTooEasy')." : <code>".api_generate_password()."</code><br></p>";
	}
	// CHECK EMAIL ADDRESS VALIDITY

    elseif( !empty($email) && ! eregi( $regexp, $email ))
	{
		$regDataOk = false;
		unset($password1, $password, $email);

		$error_message .=	"<p>".get_lang('langEmailWrong').".</p>\n";
	}

	// CHECK IF THE LOGIN NAME IS ALREADY OWNED BY ANOTHER USER

	else
	{
		$result = api_sql_query("SELECT user_id FROM $TABLEUSER
							   WHERE username='$uname'");

		if (mysql_num_rows($result) > 0)
		{
			$regDataOk = false;
			unset($password1, $password, $uname);

			$error_message .=	"<p>".get_lang('langUserFree')."</p>";
		}
		else
		{
			$regDataOk = true;
		}
	}
}
$nameTools = get_lang('Registration');
if ( ! $regDataOk)
{
	Display::display_header($nameTools);
	api_display_tool_title($nameTools);
	echo 	$error_message;
	echo	"<p>",
			"<a href=\"inscription.php?lastname=",urlencode(stripslashes($lastname)),"&firstname=",urlencode(stripslashes($firstname)),"&official_code=",urlencode(stripslashes($official_code)),"&uname=",urlencode(stripslashes($uname)),"&email=",urlencode(stripslashes($email)),"&status=",$status,"\">",
			get_lang('langAgain'),
			"</a>",
			"</p>\n";
	Display::display_footer();
	exit;		
	
}


/*> > > > > > > > > > > > REGISTRATION ACCEPTED < < < < < < < < < < < <*/

if ($regDataOk)
{
	/*-----------------------------------------------------
	  STORE THE NEW USER DATA INSIDE THE CLAROLINE DATABASE
	  -----------------------------------------------------*/

	api_sql_query("INSERT INTO ".$TABLEUSER."
	             SET lastname     = '".$lastname."',
	                 firstname   	= '".$firstname."',
	                 username 	= '".$uname."',
	                 password 	= '".($userPasswordCrypted?md5($password):$password)."',
	                 email    	= '".$email."',
	                 status   	= '".$status."',
	                 official_code	= '".$official_code."'
					 ");

	$_uid = mysql_insert_id();

				/*
						@api_sql_query("INSERT INTO `$mysqlMainDb`.`user_hash`
									  (user_id, hash, state)
									  VALUES ('$last_id', '$hash', 'WAITCHECK')");
				*/

if ($_uid)
{
	/*--------------------------------------
	          SESSION REGISTERING
	  --------------------------------------*/

		$_user['firstName']     = stripslashes($firstname);
		$_user['lastName' ]     = stripslashes($lastname);
		$_user['mail'     ]     = $email;
		$is_allowedCreateCourse = ($status == 1) ? true : false ;

    	api_session_register('_uid');
		api_session_register('_user');
		api_session_register('is_allowedCreateCourse');

        //stats
        include(api_get_library_path()."/events.lib.inc.php");
        event_login();
        // last user login date is now
        $user_last_login_datetime = 0; // used as a unix timestamp it will correspond to : 1 1 1970

        api_session_register('user_last_login_datetime');

	/*--------------------------------------
	             EMAIL NOTIFICATION
	  --------------------------------------*/

	if(strstr($email,'@'))
	{
		// Lets predefine some variables. Be sure to change the from address!
		$emailto       = $email;
		$emailfromaddr = get_setting('emailAdministrator');
		$emailfromname = get_setting('siteName');
		$emailsubject = "Registration to Egnosis";
		$emailpasswd = stripslashes($password);
		// include the html mail body file
		include($includePath.'/../lang/'.$languageInterface.'/registration_email.inc.php');
		$emailbody = $langRegMailLongHTML;

		$emailheaders = "MIME-Version: 1.0\r\n";
		$emailheaders .= "Content-Type: text/html; charset=utf-8\r\n";
		$emailheaders .= "From: ".get_setting('administratorSurname')." ".get_setting('administratorName')." <".get_setting('emailAdministrator').">\r\n";
		$emailheaders .= "Reply-To: ".get_setting('emailAdministrator')."\r\n";
		$emailheaders .= "Return-Path: ".get_setting('emailAdministrator');

		@api_send_mail( $emailto, $emailsubject, $emailbody, $emailheaders);
	}
}


Display::display_header($nameTools);
api_display_tool_title($nameTools);

	echo "<p>".get_lang('langDear')." ".stripslashes("$firstname $lastname").",<br><br>".get_lang('langPersonalSettings').".</p>\n";

	if(!empty($email))
	{
		echo "<p>".get_lang('langMailHasBeenSent').".</p>";
	}

	if($is_allowedCreateCourse)
	{
		echo "<p>",get_lang('langNowGoCreateYourCourse'),".</p>\n";
		$actionUrl = "../create_course/add_course.php";
	}
	else
	{
		echo "<p>",get_lang('langNowGoChooseYourCourses'),".</p>\n";
		$actionUrl = "courses.php?action=subscribe";
	}
// ?uidReset=true&uidReq=$_uid
	echo	"<form action=\"",$actionUrl,"\"  method=\"post\">\n",
			"<input type=\"submit\" name=\"next\" value=\"",get_lang('langNext'),"\" validationmsg=\" ",get_lang('langNext')," \">\n",
			"</form>\n";

}	// else Registration accepted

$already_second=1;

Display::display_footer();
?>
