<?php // $Id: user_import.php,v 1.17.2.1 2006/02/14 13:42:34 pcool 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();
include(api_get_library_path().'/fileManage.lib.php');

$formSent=0;
$errorMsg='';

$tbl_user=$mysqlMainDb."`.`user";
//$tbl_cours_user=$mysqlMainDb."`.`cours_user";
//$tbl_cours=$mysqlMainDb."`.`cours";
//updated for 1.6 - YW
$tbl_course_user = Database::get_main_table(MAIN_COURSE_USER_TABLE);
$tbl_course      = Database::get_main_table(MAIN_COURSE_TABLE); 

$tool_name=get_lang('ImportUserListXMLCSV');

$interbredcrump[]=array("url" => "index.php","name" => get_lang('AdministrationTools'));

set_time_limit(0);

if($_POST['formSent'] )
{
	$formSent=$_POST['formSent'];
	$file_type=$_POST['file_type'];
	$sendMail=$_POST['sendMail']?1:0;

	if($_FILES['import_file']['size'])
	{
		$content=file($_FILES['import_file']['tmp_name']);
	}
	else
	{
		$content=array('');
	}

	$contacts=array();

	if($file_type == 'xml')
	{
		if(!stristr($content[0],'<?xml'))
		{
			$errorMsg=get_lang('NotXML');
		}
		else
		{
			$i=0;
			$pos='end';

			foreach($content as $enreg)
			{
				$enreg=trim($enreg);

				if($pos == 'end')
				{
					if(strtolower($enreg) == '<contact>')
					{
						$contacts[$i]=array();

						$pos='start';
					}
				}
				else
				{
					if(strtolower($enreg) == '</contact>')
					{
						$pos='end';

						if(!$i)
						{
							if(!isset($contacts[0]['LastName']) || !isset($contacts[0]['FirstName']) || !isset($contacts[0]['Email']))
							{
								$errorMsg=get_lang('NoNeededData');

								break;
							}
						}

						$i++;
					}
					else
					{
						list($tag_name)=explode('>',$enreg);
						$tag_name=str_replace('<','',$tag_name);

						$tag_value=strip_tags($enreg);

						$contacts[$i][$tag_name]=$tag_value;
					}
				}
			}
		}
	}
	else
	{
		if(!strstr($content[0],';'))
		{
			$errorMsg=get_lang('NotCSV');
		}
		else
		{
			$tag_names=array();

			foreach($content as $key=>$enreg)
			{
				$enreg=explode(';',trim($enreg));

				if($key)
				{
					foreach($tag_names as $tag_key=>$tag_name)
					{
						$contacts[$key-1][$tag_name]=$enreg[$tag_key];
					}
				}
				else
				{
					foreach($enreg as $tag_name)
					{
						$tag_names[]=eregi_replace('[^a-z0-9_-]','',$tag_name);
					}

					if(!in_array('LastName',$tag_names) || !in_array('FirstName',$tag_names) || !in_array('Email',$tag_names))
					{
						$errorMsg=get_lang('NoNeededData');

						break;
					}
				}
			}
		}
	}

	if(sizeof($contacts) > 500)
	{
		$errorMsg=get_lang('MaxImportUsers');
	}

	if(empty($errorMsg))
	{
		include('../lang/'.$platformLanguage.'/registration.inc.php');

		srand((double)microtime()*1000000);

		foreach($contacts as $enreg)
		{
			if(empty($enreg['LastName']))
			{
				$enreg['LastName']='LastName';
			}

			if(empty($enreg['FirstName']))
			{
				$enreg['FirstName']='FirstName';
			}

			$enreg['UserName']=eregi_replace('[^a-z0-9_.]','',$enreg['UserName']);

			if(empty($enreg['UserName']))
			{
				$enreg['UserName']='UserName';
			}

			$enreg['Password']=eregi_replace('[^a-z0-9_-]','',$enreg['Password']);

			if(empty($enreg['Password']))
			{
				$enreg['Password']=api_generate_password();
			}

			$enreg['Email']=eregi_replace('[^a-z0-9@._-]','',$enreg['Email']);

			if(!strstr($enreg['Email'],'@'))
			{
				$enreg['Email']='';
			}

			if(!empty($enreg['Courses']))
			{
				$enreg['Courses']=explode('|',$enreg['Courses']);
			}
			else
			{
				$enreg['Courses']=array();
			}

			if($enreg['Status'] == 'teacher')
			{
				$enreg['Status']=1;
			}
			else
			{
				$enreg['Status']=5;
			}

			$usernameAppend='';

			do
			{
				if($userPasswordCrypted)
				{
					$Password=md5($enreg['Password']);
				}
				else
				{
					$Password=$enreg['Password'];
				}

				$result=api_sql_query("INSERT INTO `$tbl_user`(lastname,firstname,username,password,email,status,official_code,phone,creator_id) VALUES('".addslashes($enreg['LastName'])."','".addslashes($enreg['FirstName'])."','$enreg[UserName]$usernameAppend','$Password','$enreg[Email]','$enreg[Status]','".addslashes($enreg['OfficialCode'])."','".addslashes($enreg['PhoneNumber'])."','$_uid')");

				if(!$result)
				{
					if($enreg['UserName'] == 'UserName')
					{
						$usernameAppend='_'.rand(1,100000);
					}
					else
					{
						$result=1;
					}
				}
				else
				{
					$user_id=mysql_insert_id();

					if(sizeof($enreg['Courses']))
					{
						$query="INSERT IGNORE INTO $tbl_course_user(course_code,user_id,status) VALUES";

						$cpt=0;

						foreach($enreg['Courses'] as $enreg_cours)
						{
							$result2=api_sql_query("SELECT code FROM $tbl_course WHERE visual_code='".addslashes($enreg_cours)."'",__FILE__,__LINE__);

							while(list($enreg_cours)=mysql_fetch_row($result2))
							{
								$query.="('$enreg_cours','$user_id','$enreg[Status]'),";

								$cpt++;
							}
						}

						if($cpt)
						{
							$query=substr($query,0,-1);

							api_sql_query($query,__FILE__,__LINE__);
						}
					}

					if($sendMail)
					{
						$emailto='"'.$enreg['FirstName'].' '.$enreg['LastName'].'" <'.$enreg['Email'].'>';
						$emailsubject='['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');
						$emailbody=get_lang('Dear')." $enreg[FirstName] $enreg[LastName],\n\n".get_lang('YouAreReg')." ".get_setting('siteName')." ".get_lang('Settings')." $enreg[UserName]$usernameAppend\n".get_lang('Pass')." : $enreg[Password]\n\n".get_lang('Address')." ".get_setting('siteName')." ".get_lang('Is')." : $serverAddress\n\n".get_lang('Problem')."\n\n".get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n".get_lang('Manager')." ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n".get_lang('Email')." : ".get_setting('emailAdministrator')."";
						$emailheaders='From: '.get_setting('administratorName').' '.get_setting('administratorSurname').' <'.$emailAdministrator.">\n";
						$emailheaders.='Reply-To: '.get_setting('emailAdministrator');

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

		header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
		exit();
	}
}

Display::display_header($tool_name);

api_display_tool_title($tool_name);


?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" style="margin:0px;">
<input type="hidden" name="formSent" value="1">
<table border="0" cellpadding="5" cellspacing="0">

<?php
if(!empty($errorMsg))
{
?>

<tr>
  <td colspan="2">

<?php
	Display::display_normal_message($errorMsg); //main API
?>

  </td>
</tr>

<?php
}
?>

<tr>
  <td nowrap="nowrap"><?php echo get_lang('ImportFileLocation'); ?> :</td>
  <td><input type="file" name="import_file" size="30"></td>
</tr>
<tr>
  <td nowrap="nowrap" valign="top"><?php echo get_lang('FileType'); ?> :</td>
  <td>
	<input class="checkbox" type="radio" name="file_type" id="file_type_xml" value="xml" <?php if($formSent && $file_type == 'xml') echo 'checked="checked"'; ?>> <label for="file_type_xml">XML</label> (<a href="exemple.xml" target="_blank"><?php echo get_lang('ExampleXMLFile'); ?></a>)<br>
	<input class="checkbox" type="radio" name="file_type" id="file_type_csv"  value="csv" <?php if(!$formSent || $file_type == 'csv') echo 'checked="checked"'; ?>> <label for="file_type_csv">CSV</label> (<a href="exemple.csv" target="_blank"><?php echo get_lang('ExampleCSVFile'); ?></a>)<br>
  </td>
</tr>
<tr>
  <td nowrap="nowrap" valign="top"><?php echo get_lang('SendMailToUsers'); ?> :</td>
  <td>
	<input class="checkbox" type="radio" name="sendMail" value="1" id="send_mail_yes" <?php if(!$formSent || !$sendMail) echo 'checked="checked"'; ?>> <label for="send_mail_yes"><?php echo get_lang('Yes'); ?></label><br>
	<input class="checkbox" type="radio" name="sendMail" value="0" id="send_mail_no"  <?php if($formSent && $sendMail) echo 'checked="checked"'; ?>> <label for="send_mail_no"><?php echo get_lang('No'); ?></label><br>
  </td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td><input type="submit" value="<?php echo get_lang('Ok'); ?>"></td>
</tr>
</table>
</form>

<font color="gray">
<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>

<blockquote>
<pre>
<b>LastName</b>;<b>FirstName</b>;UserName;Password;<b>Email</b>;OfficialCode;PhoneNumber;Status;Courses
<b>xxx</b>;<b>xxx</b>;xxx;xxx;<b>xxx</b>;xxx;xxx;user/teacher;xxx1|xxx2|xxx3
</pre>
</blockquote>

<p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>

<blockquote>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;Contacts&gt;
    &lt;Contact&gt;
        <b>&lt;LastName&gt;xxx&lt;/LastName&gt;</b>
        <b>&lt;FirstName&gt;xxx&lt;/FirstName&gt;</b>
        &lt;UserName&gt;xxx&lt;/UserName&gt;
        &lt;Password&gt;xxx&lt;/Password&gt;
        <b>&lt;Email&gt;xxx&lt;/Email&gt;</b>
        &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
        &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
        &lt;Status&gt;user/teacher&lt;/Status&gt;
        &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
    &lt;/Contact&gt;
&lt;/Contacts&gt;
</pre>
</blockquote>
</font>

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