<?php // $Id: user_export.php,v 1.11 2005/05/23 14:17:19 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='admin';

$cidReset=true;

include('../inc/claro_init_global.inc.php');
api_protect_admin_script();
include(api_get_library_path().'/fileManage.lib.php');

$course_code=$_GET['course_code'];
$formSent=0;
$errorMsg='';

$tbl_user=$mysqlMainDb."`.`user";
$tbl_course      = Database::get_main_table(MAIN_COURSE_TABLE); 
$tbl_course_user = Database::get_main_table(MAIN_COURSE_USER_TABLE);

$archivePath=api_get_path(SYS_PATH).$archiveDirName.'/';
$archiveURL=api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';

$tool_name=get_lang('ExportUserListXMLCSV');

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

set_time_limit(0);

if($_POST['formSent'] )
{
	$formSent=$_POST['formSent'];
	$file_type=($_POST['file_type'] == 'csv')?'csv':'xml';
	$course_code=$_POST['course_code'];

	if(empty($course_code))
	{
		$result=api_sql_query("SELECT user_id,lastname,firstname,email,username,password,auth_source,status,official_code,phone FROM `$tbl_user` ORDER BY user_id",__FILE__,__LINE__);
	}
	else
	{
		$result=api_sql_query("SELECT t1.user_id,lastname,firstname,email,username,password,auth_source,t2.status,official_code,phone FROM `$tbl_user` t1,$tbl_course_user t2 WHERE t1.user_id=t2.user_id AND course_code='$course_code' ORDER BY user_id",__FILE__,__LINE__);
	}

	if(mysql_num_rows($result))
	{
		if(!file_exists($archivePath))
		{
			mkpath($archivePath);
		}

		if(!file_exists($archivePath.'index.html'))
		{
			$fp=fopen($archivePath.'index.html','w');

			fputs($fp,'<html><head></head><body></body></html>');

			fclose($fp);
		}

		$archiveFile='export_users_'.$course_code.'_'.date('Y-m-d_H-i-s').'.'.$file_type;
		while( file_exists($archivePath.$archiveFile))
		{
			$archiveFile='export_users_'.$course_code.'_'.date('Y-m-d_H-i-s').'_'.uniqid('').'.'.$file_type;		
		}
		$fp=fopen($archivePath.$archiveFile,'w');

		if($file_type == 'csv')
		{
			fputs($fp,"UserId;LastName;FirstName;UserName;Password;AuthSource;Email;Statut;OfficialCode;PhoneNumber\n");
		}
		else
		{
			fputs($fp,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Contacts>\n");
		}

		while($row=mysql_fetch_array($result))
		{
			if($userPasswordCrypted)
			{
				$row['password']='';
			}

			if($file_type == 'csv')
			{
				$row['user_id']=str_replace(';',',',$row['user_id']);
				$row['lastname']=str_replace(';',',',$row['lastname']);
				$row['firstname']=str_replace(';',',',$row['firstname']);
				$row['username']=str_replace(';',',',$row['username']);
				$row['password']=str_replace(';',',',$row['password']);
				$row['auth_source']=str_replace(';',',',$row['auth_source']);
				$row['email']=str_replace(';',',',$row['email']);
				$row['status']=str_replace(';',',',$row['status']);
				$row['official_code']=str_replace(';',',',$row['official_code']);
				$row['phone']=str_replace(';',',',$row['phone']);

				fputs($fp,"$row[user_id];$row[lastname];$row[firstname];$row[username];$row[password];$row[auth_source];$row[email];$row[status];$row[official_code];$row[phone]\n");
			}
			else
			{
				fputs($fp,"\t<Contact>\n"
						 ."\t\t<UserId>$row[user_id]</UserId>\n"
						 ."\t\t<LastName>$row[lastname]</LastName>\n"
						 ."\t\t<FirstName>$row[firstname]</FirstName>\n"
						 ."\t\t<UserName>$row[username]</UserName>\n"
						 ."\t\t<Password>$row[password]</Password>\n"
						 ."\t\t<AuthSource>$row[auth_source]</AuthSource>\n"
						 ."\t\t<Email>$row[email]</Email>\n"
						 ."\t\t<Statut>$row[status]</Statut>\n"
						 ."\t\t<OfficialCode>$row[official_code]</OfficialCode>\n"
						 ."\t\t<PhoneNumber>$row[phone]</PhoneNumber>\n"
						 ."\t</Contact>\n");
			}
		}

		if($file_type == 'xml')
		{
			fputs($fp,"</Contacts>");
		}

		fclose($fp);

		$errorMsg=get_lang('UserListHasBeenExported').'<br/><a href="'.$archiveURL.$archiveFile.'">'.get_lang('ClickHereToDownloadTheFile').'</a>';
	}
}

Display::display_header($tool_name);

api_display_tool_title($tool_name);



$result=api_sql_query("SELECT code,visual_code,title FROM $tbl_course ORDER BY visual_code LIMIT 0,2000",__FILE__,__LINE__);

$Courses=api_store_result($result);
?>

<?php
if(!empty($errorMsg))
{
	Display::display_normal_message($errorMsg); //main API
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="margin:0px;">
<input type="hidden" name="formSent" value="1">
<table border="0" cellpadding="5" cellspacing="0">
<tr>
  <td nowrap="nowrap" valign="top"><?php echo get_lang('OutputFileType'); ?> :</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><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><br>
  </td>
</tr>
<tr>
  <td><?php echo get_lang('OnlyUsersFromCourse'); ?> :</td>
  <td><select name="course_code">
	<option value="">-----</option>

<?php
foreach($Courses as $enreg)
{
?>

	<option value="<?php echo $enreg['code']; ?>" <?php if($course_code == $enreg['code']) echo 'selected="selected"'; ?>><?php echo '('.$enreg['visual_code'].') '.$enreg['title']; ?></option>

<?php
}

unset($Courses);
?>

  </select></td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td><input type="submit" value="<?php echo get_lang('Ok'); ?>"></td>
</tr>
</table>
</form>

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