<?php
// $Id: inscription.php 11139 2007-02-17 15:43:14Z yannoo $
/*
==============================================================================
	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
	Copyright (c) Bart Mollet, Hogeschool Gent

	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: Zhong 	poopsoft@163.com
==============================================================================
*/
/**
==============================================================================
*	This script displays a form for registering new users.
*	@package	 dokeos.auth
==============================================================================
*/
// name of the language file that needs to be included
$language_file = "registration";

include ("../inc/global.inc.php");

require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
require_once (api_get_path(CONFIGURATION_PATH).'profile.conf.php');
$tool_name = get_lang('Registration');

Display :: display_header($tool_name);

// Forbidden to self-register
if (get_setting('allow_registration') == 'false')
{
	api_not_allowed();
}
//api_display_tool_title($tool_name);
if (get_setting('allow_registration')=='approval')
{
	Display::display_normal_message(get_lang('YourAccountHasToBeApproved'));
}


$form = new FormValidator('registration');

$form->addElement('header', 'header', get_lang('Registration'));

//	LAST NAME and FIRST NAME
// hgz 20070604
//$form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
//$form->addRule('lastname',  get_lang('ThisFieldIsRequired'), 'required');

$form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');

//	EMAIL
$form->addElement('text', 'email', get_lang('Email'), array('size' => 40));
if (api_get_setting('registration', 'email') == 'true')
	$form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('email', get_lang('EmailWrong'), 'email');
$form->addRule('email', get_lang('EmailTaken'), 'email_available');

//	OFFICIAL CODE
if (CONFVAL_ASK_FOR_OFFICIAL_CODE)
{
	$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
	if (api_get_setting('registration', 'officialcode') == 'true')
		$form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
}
//	USERNAME
$form->addElement('text', 'username', get_lang('UserName'), array('size' => 40));
$form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('username', get_lang('UsernameWrong'), 'username');
$form->addRule('username', get_lang('UserTaken'), 'username_available');

//	PASSWORD
$form->addElement('password', 'pass1', get_lang('Pass'), array('size' => 42));
$form->addElement('password', 'pass2', get_lang('Confirmation'), array('size' => 42));
$form->addRule('pass1', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule(array('pass1', 'pass2'), get_lang('PassTwo'), 'compare');
if (CHECK_PASS_EASY_TO_FIND)
	$form->addRule('password1', get_lang('PassTooEasy').': '.api_generate_password(), 'callback', 'api_check_password');
//	LANGUAGE
if (get_setting('registration', 'language') == 'true')
{
	$form->addElement('select_language', 'language', get_lang('Language'));
}
//	STUDENT/TEACHER
if (get_setting('allow_registration_as_teacher') <> 'false')
{
	$group = array();
	$group[] = $form->createElement('radio', 'status', null, get_lang('RegStudent'), STUDENT);
	$group[] = $form->createElement('radio', 'status', null, get_lang('RegAdmin'), COURSEMANAGER);
	$form->addGroup($group, 'status', get_lang('Status'), null, false);
}

$group = array ();
$group[] = $form->createElement('submit', 'submit', get_lang('Ok'), 'class="inputSubmit"');
$form->addGroup($group, 'submit', '&nbsp;', null, false);

if(isset($_SESSION["user_language_choice"]) && $_SESSION["user_language_choice"]!=""){
	$defaults['language'] = $_SESSION["user_language_choice"];
}
else{
	$defaults['language'] = api_get_setting('platformLanguage');
}
$defaults['status'] = STUDENT;
$form->setDefaults($defaults);

Display::setTemplateBorder($form, '60%');

if ($form->validate())
{

	/*-----------------------------------------------------
	  STORE THE NEW USER DATA INSIDE THE MAIN DOKEOS DATABASE
	  -----------------------------------------------------*/
	$values = $form->exportValues();

	if (get_setting('allow_registration_as_teacher') == 'false')
	{
		$values['status'] = STUDENT;
	}
	
	if (! isset($values['language'])) {
		$values['language'] = api_get_setting('platformLanguage');
	}

	// creating a new user
	//$user_id = UserManager::create_user($values['firstname'],$values['lastname'],$values['status'],$values['email'],$values['username'],$values['pass1'],$values['official_code'], $values['language']);
	$user_id = UserManager::create_user($values['firstname'],'',$values['status'],$values['email'],$values['username'],$values['pass1'],$values['official_code'], $values['language']);

	if ($user_id)
	{
		// TODO: add language to parameter list of UserManager::create_user(...)
		/* hgz 20070706 it is used never.
		$sql = "UPDATE ".Database::get_main_table(TABLE_MAIN_USER)."
		             SET language	= '".mysql_real_escape_string($values['language'])."'
					WHERE user_id = '".$user_id."'	 ";
		*/
		//api_sql_query($sql,__FILE__,__LINE__);

		// if there is a default duration of a valid account then we have to change the expiration_date accordingly
		if (get_setting('account_valid_duration')<>'')
		{
			$sql = "UPDATE ".Database::get_main_table(TABLE_MAIN_USER)."
						SET expiration_date='registration_date+1' WHERE user_id='".$user_id."'";
			api_sql_query($sql,__FILE__,__LINE__);
		}

		// if the account has to be approved then we set the account to inactive, sent a mail to the platform admin and exit the page.
		if (get_setting('allow_registration')=='approval')
		{
			// 1. set account inactive
			$sql = "UPDATE ".Database::get_main_table(TABLE_MAIN_USER)."
						SET active='0' WHERE user_id='".$user_id."'";
			api_sql_query($sql,__FILE__,__LINE__);

			// 2. send mail to the platform admin
			$emailTo = api_get_setting('emailAdministrator');
			$emailToName = addslashes(get_setting('administratorSurname') . ' ' . get_setting('administratorName'));
			$emailFrom = api_get_setting('emailAdministrator');
			$emailFromName = addslashes(get_setting('administratorSurname') . ' ' . get_setting('administratorName'));
			$emailSubject = get_lang('ApprovalForNewAccount') . ' : ' . $values['username'];
			$emailBody = get_lang('ApprovalForNewAccount') . "\n" .
						 get_lang('UserName') . ' : ' . $values['username'] . "\n" .
						 //get_lang('LastName') . ' : ' . $values['lastname'] . "\n" .
						 get_lang('FirstName') . ' : ' . $values['firstname'] . "\n" .
						 get_lang('Email') . ' : ' . $values['email'] . "\n" .
						 get_lang('Status') . ' : ' . $values['status'] . "\n\n" .
						 get_lang('ManageUser') . ' : ' . api_get_path(WEB_CODE_PATH) . 'admin/user_edit.php?user_id=' . $user_id;			
			$emailHeader = "Content-Type: text/plain;\n\tcharset=\"".SYSTEM_CHARSET."\"\n";
			$emailHeader .= "Mime-Version: 1.0";
			
			api_mail($emailToName,$emailTo,$emailSubject,$emailBody,$emailFromName,$emailFrom,$emailHeader);
			
			// 3. exit the page
			unset($user_id);
			Display :: display_footer();
			exit;
		}


		/*--------------------------------------
		          SESSION REGISTERING
		  --------------------------------------*/
		$_user['firstName'] = stripslashes($values['firstname']);
		//$_user['lastName'] 	= stripslashes($values['lastname']);
		$_user['mail'] 		= $values['email'];
		$_user['language'] 	= $values['language'];
		$_user['user_id']	= $user_id;
		$is_allowedCreateCourse = ($values['status'] == 1) ? true : false;
		api_session_register('_user');
		api_session_register('is_allowedCreateCourse');

		//stats
		include (api_get_path(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($values['email'], '@'))
		{			
			$emailTo = $values['email'];
			//$emailToName = $values['firstname'] . ' ' . $values['lastname'];
			$emailToName = $values['firstname'];
			$emailFrom = api_get_setting('emailAdministrator');
			$emailFromName = addslashes(get_setting('administratorSurname') . ' ' . get_setting('administratorName'));
			$emailSubject = '[' . get_setting('siteName') . '] ' . get_lang('YourReg');
			$emailBody = 
						 //get_lang('Dear') . ' ' . stripslashes($values['firstname'] . ' ' . $values['lastname']) . ",\n\n" . 
						 get_lang('Dear') . ' ' . stripslashes($values['firstname']) . ",\n\n" . 
						 get_lang('YouAreReg') . ' ' . get_setting('siteName') . ' ' . get_lang('Settings') . "\n\n" . 
						 get_lang('TheU') . ' : ' . $values['username'] . "\n" . 
						 get_lang('Pass') . ' : ' . stripslashes($values['pass1']) . "\n" . 
						 get_setting('siteName') . ' : ' . $_configuration['root_web'] . "\n\n" . 
						 get_lang('Problem') . "\n\n" . 
						 get_lang('Manager') . ' : ' . get_setting('administratorName') . ' ' . get_setting('administratorSurname') . "\n" . 
						 get_lang('phone') . ' : ' . get_setting('administratorTelephone') . "\n" . 
						 get_lang('Email') . ' : ' . get_setting('emailAdministrator');
			
			$emailHeader = "Content-Type: text/plain;\n\tcharset=\"".SYSTEM_CHARSET."\"\n";
			$emailHeader .= "Mime-Version: 1.0";

			api_mail($emailToName,$emailTo,$emailSubject,$emailBody,$emailFromName,$emailFrom,$emailHeader);
		}
	}

	echo "<p>".get_lang('Dear')." ".stripslashes($values['firstname']).",<br><br>".get_lang('PersonalSettings')."</p>\n";

	if (!empty ($values['email']))
	{
		echo "<p>".get_lang('MailHasBeenSent')."</p>";
	}

	if ($is_allowedCreateCourse)
	{
		echo "<p>", get_lang('NowGoCreateYourCourse'), "</p>\n";
		$actionUrl = "../create_course/add_course.php";
	}
	else
	{
		echo "<p>", get_lang('NowGoChooseYourCourses'), "</p>\n";
		$actionUrl = "../course/course_manage.php?action=subscribe";
	}

	echo "<form action=\"", $actionUrl, "\"  method=\"post\">\n", "<input type=\"submit\" class=\"inputSubmit\" name=\"next\" value=\"", get_lang('Next'), "\" validationmsg=\" ", get_lang('Next'), " \">\n", "</form><br>\n";

}
else
{
	$form->display();
	echo '<table align=center width=60%><tr><td align=left>';
	echo '<a href="' . api_get_path(WEB_PATH) . '">&lt;&lt;' . get_lang('Back') . '</a>';
	echo '</td></tr></table><br>';
}
?>

<?php
/*
==============================================================================
		FOOTER
==============================================================================
*/

Display :: display_footer();
?>