<?php // $Id: user_add.php,v 1.17 2005/05/18 07:30:42 bmol Exp $
/*
==============================================================================
	Dokeos - elearning and course management software

	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 University of Ghent (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	Copyright (c) Olivier Brouckaert

	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
==============================================================================
*/
/**
============================================================================== 
*	@package dokeos.admin
============================================================================== 
*/
$langFile = array('admin','registration');
$cidReset = true;
include ('../inc/claro_init_global.inc.php');
api_protect_admin_script();
$tbl_admin = Database :: get_main_table(MAIN_ADMIN_TABLE);
$tbl_user = Database :: get_main_table(MAIN_USER_TABLE);

include (api_get_library_path().'/fileManage.lib.php');
include (api_get_library_path().'/usermanager.lib.php');

/*
 * default values
 */
$send_mail = 1;
$platform_admin = 0;

if (isset ($_POST['action']))
{
	$lastname = trim(stripslashes($_POST['lastname']));
	$form_firstname = trim(stripslashes($_POST['firstname']));
	$official_code = trim(stripslashes($_POST['official_code']));
	$email = trim(stripslashes($_POST['email']));
	$phone = trim(stripslashes($_POST['phone']));
	$username = eregi_replace('[^a-z0-9_.-]', '_', strtr(trim(stripslashes($_POST['username'])), 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ', 'AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn'));
	$status = (intval($_POST['status']) == 1) ? 1 : 5;
	$picture = $_FILES['picture'];
	$platform_admin = $_POST['platform_admin'] ? 1 : 0;
	$send_mail = $_POST['send_mail'] ? 1 : 0;
	$user_id = $_POST['user_id'];
	$action = $_POST['action'];
	$password = $_POST['password_auto'] == '1' ? api_generate_password() : $_POST['password'];
	if (empty ($lastname)) {
		$error_message .= get_lang('langEmptySurname').'<br/>';
	}
	if (empty ($form_firstname)) {
		$error_message .= get_lang('langEmptyName').'<br/>';
	}
	if (empty ($email) && !eregi("^[a-z0-9]+([._-][a-z0-9]+)*@[a-z0-9]+([.-][a-z0-9]+)*\.[a-z]{2,4}$", $email)) {
		$error_message .= get_lang('EmailWrong').'<br/>';
	}
	if (empty ($username)) {
		$error_message .= get_lang('PleaseEnterValidLogin').'<br/>';
	}
	if( empty($password)) {
		$error_message .= get_lang('EmptyPassword').'<br/>';	
	}
	$table_user = Database::get_main_table(MAIN_USER_TABLE);
	$result = api_sql_query("SELECT user_id FROM $table_user WHERE username='$username'");
	if (mysql_num_rows($result) > 0) {
		unset($password, $username);
		$error_message .=	"<p>".get_lang('langUserFree')."</p>";
	}
	if (empty($error_message)) {
		$picture_uri = '';
		if ($picture['size'])
		{
			$file_extension = explode('.', $picture['name']);
			$file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
			if (!strstr($picture['type'], 'jpeg') && !strstr($picture['type'], 'gif') && !strstr($picture['type'], 'png'))
			{
				$error_message .= get_lang('AcceptedPictureFormats');
			}
			else
			{
				if (!file_exists('../upload/users/'))
				{
					mkpath('../upload/users/');
				}
				$picture_uri = uniqid('').'.'.$file_extension;
				if (move_uploaded_file($picture['tmp_name'], '../upload/users/'.$picture_uri))
				{
					@chmod('../upload/users/'.$picture_uri, 0777);
				} else {
					$picture_uri = '';
				}
			}
		}
		if (empty ($error_message))
		{
				$db_password = $password;
				if ($userPasswordCrypted)
				{
					$db_password = md5($db_password);
				}
			$user_id = UserManager::create_user($form_firstname,$lastname,$status,$email,$username,$password,$official_code,$phone,$picture_uri);
			$table_user = Database::get_main_table(MAIN_USER_TABLE);
			$sql = "UPDATE $table_user SET password='".$db_password."' WHERE user_id = '".$user_id."'";
			api_sql_query($sql);
			if (!$user_id)
			{
				if (!empty ($picture_uri) && file_exists('../upload/users/'.$picture_uri))
				{
					unlink('../upload/users/'.$picture_uri);
				}
				$error_message .= get_lang('LoginAlreadyTaken');
			}
			else
			{
				if ($platform_admin)
				{
					api_sql_query("INSERT INTO $tbl_admin (user_id) VALUES('$user_id')", __FILE__, __LINE__);
				}
				if (!empty ($email) && $send_mail)
				{
					$emailto = '"'.$form_firstname.' '.$lastname.'" <'.$email.'>';
					$emailsubject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');
					$emailheaders = 'From: '.get_setting('administratorName').' '.get_setting('administratorSurname').' <'.get_setting('emailAdministrator').">\n";
					$emailheaders .= 'Reply-To: '.get_setting('emailAdministrator');
					$emailbody=get_lang('langDear')." ".stripslashes("$form_firstname $lastname").",\n\n".get_lang('langYouAreReg')." ". get_setting('siteName') ." ".get_lang('langSettings')." ". $username ."\n". get_lang('langPass')." : ".stripslashes($password)."\n\n" .get_lang('langAddress') ." ". get_setting('siteName') ." ". get_lang('langIs') ." : ". $serverAddress ."\n\n". get_lang('langProblem'). "\n\n". get_lang('langFormula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('langManager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('langEmail') ." : ".get_setting('emailAdministrator');
					@api_send_mail($emailto, $emailsubject, $emailbody, $emailheaders);
				}
				header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserAdded')));
				exit ();
			}
		}
	}
}
$interbredcrump[] = array ("url" => "index.php", "name" => get_lang('AdministrationTools'));
$tool_name = get_lang('AddUsers');
Display::display_header($tool_name);
api_display_tool_title($tool_name);
if (isset ($error_message))
{
	Display :: display_error_message($error_message);
}
echo '<h4>' . get_lang('UseOnlyEnglishChars') . '</h4>';
$textinput_size = ' style="width: 200px;"';
?>
<br>
<form name="mainForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" style="margin:0px;">
<input type="hidden" name="action" value="add_user">
<table>
<tr>
  <td align="right" width="30%"><?php echo get_lang('LastName'); ?> : </td>
  <td>&nbsp;</td>
  <td width="70%"><input type="text" name="lastname"<?php echo $textinput_size;?> value="<?php echo htmlspecialchars($lastname); ?>"></td>
</tr>
<tr>
  <td align="right"><?php echo get_lang('FirstName'); ?> :</td>
  <td></td>
  <td><input type="text" name="firstname"<?php echo $textinput_size;?> value="<?php echo htmlspecialchars($form_firstname); ?>"></td>
</tr>
<!--<tr>
  <td align="right"><?php echo get_lang('OfficialCode'); ?> :</td>
  <td></td>
  <td><input type="text" name="official_code" <?php echo $textinput_size;?> value="<?php echo htmlspecialchars($official_code); ?>"></td>
</tr>-->
<tr>
  <td align="right"><?php echo get_lang('Email'); ?> :</td>
  <td></td>
  <td><input type="text" name="email"<?php echo $textinput_size;?> value="<?php echo htmlspecialchars($email); ?>"></td>
</tr>
<!-- 
<tr>
  <td align="right"><?php echo get_lang('PhoneNumber'); ?> :</td>
  <td><input type="text" name="phone"<?php echo $textinput_size;?> value="<?php echo htmlspecialchars($phone); ?>"></td>
</tr>
-->
<tr>
  <td align="right"><?php echo get_lang('AddPicture'); ?> :</td>
  <td></td>
  <td><input type="file" name="picture" style="width: 283px;"></td>
<tr>
<tr>
  <td align="right"><?php echo get_lang('LoginName'); ?> :</td>
  <td></td>
  <td><input type="text" name="username"<?php echo $textinput_size;?> maxlength="20" value="<?php echo htmlspecialchars($username); ?>"></td>
</tr>
<tr>
  <td  align="right"valign="top"><?php echo get_lang('Password'); ?> :</td>
  <td></td>
  <td>
  	<input type="radio" name="password_auto" value="1" <?php if(empty($_POST['action']) || $_POST['password_auto']) echo 'checked="checked"'; ?> /><?php echo get_lang('AutoGeneratePassword'); ?><br/>
  	<input type="radio" name="password_auto" value="0" <?php if(!empty($_POST['action']) && !$_POST['password_auto']) echo 'checked="checked"'; ?> /><input type="password" name="password" style="width: 180px;" value="<?php if(!$_POST['password_auto']) echo htmlspecialchars($password); ?>" onfocus="javascript:document.mainForm.password_auto[1].checked=true;" onblur="javascript:if(this.value == '') document.mainForm.password_auto[0].checked=true;"></td>
</tr>
<tr>
  <td align="right"><?php echo get_lang('Status'); ?> :</td>
  <td></td>
  <td><select name="status">
	<option value="1"><?php echo get_lang('Teacher'); ?></option>
	<option value="5" <?php if( $status == 5) echo 'selected="selected"'; ?>><?php echo get_lang('User'); ?></option>
  </select></td>
</tr>
<tr>
  <td align="right"><?php echo get_lang('PlatformAdmin'); ?> :</td>
  <td></td>
  <td>
	<input class="checkbox" type="radio" name="platform_admin" value="1" <?php if( $platform_admin) echo 'checked="checked"'; ?>> <?php echo get_lang('Yes'); ?>&nbsp;
	<input class="checkbox" type="radio" name="platform_admin" value="0" <?php if( !$platform_admin) echo 'checked="checked"'; ?>> <?php echo get_lang('No'); ?>&nbsp;
  </td>
</tr>
<tr>
  <td align="right"><?php echo get_lang('SendMailToNewUser'); ?> :</td>
  <td></td>
  <td>
	<input class="checkbox" type="radio" name="send_mail" value="1" <?php if( $send_mail) echo 'checked="checked"'; ?>> <?php echo get_lang('Yes'); ?>&nbsp;
	<input class="checkbox" type="radio" name="send_mail" value="0" <?php if( !$send_mail) echo 'checked="checked"'; ?>> <?php echo get_lang('No'); ?>&nbsp;
  </td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td></td>
  <td><input type="submit" value="<?php echo get_lang('Ok'); ?>"></td>
</tr>

</table>

</form>


<?php
/*
==============================================================================
		FOOTER 
==============================================================================
*/ 
Display::display_footer();
?>