<?php
/**
 * User Management
 *
 * User administration functions
 *
 * @package MultiUser
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: users.php,v 1.00 2006/12/05 18:15:00
 */

require_once './core/functions.php';
require_once './core/template.php';
require_once './core/turing.php';
localnet_or_die();


/**
 * Create user
 *
 * @param string $user Username
 * @param string $pass Password
 * @param string $perm permission as integer
 * @return boolean     true on success
 */
if ($save)
{
	global $config;
	if (!$config['desactiveturing']) {
		if ($sid && $code) {
		$SELECT = 'SELECT code FROM '.TBL_CODES.' WHERE session=\''.$sid.'\';';
		$mycode = runSQL($SELECT);
			if ($mycode[0]['code'] != $code) {
			redirect('register.php');
			}
		}
		else {
			redirect('register.php');
		}
	}
	
    $pw = md5($password);
	$perm = $config['permdefault'];

    // acquire next free "real" user-id
    $SQL = "SELECT (MAX(id)+1) AS id FROM ".TBL_USERS." WHERE id != ".$config['guestid'].";";
    $nextid = runSQL($SQL);
    
    $SQL = "INSERT INTO ".TBL_USERS."
               SET id = ".$nextid[0]['id'].",
               	   name = '".addslashes($newuser)."',
                   passwd = '$pw',
                   permissions = $perm,
                   email = '".addslashes($email)."'";
    runSQL($SQL);
	
	$SQL = 'DELETE FROM '.TBL_CODES.' WHERE session = \''.$sid.'\';';
	runSQL($SQL);
	
	$oldtime = time() - 300;
	$SQL = 'DELETE FROM '.TBL_CODES.' WHERE now < \''.$oldtime.'\';';
	runSQL($SQL);
	
	$SQL = "INSERT INTO ".TBL_USERCONFIG." SET user_id = ".$nextid[0]['id'].", opt='points', value = '".$config['credits']."'";
	runSQL($SQL);
	
    redirect('login.php');	
}

$session = md5(time());
if (!$config['desactiveturing']) {
$numero = CreateSession($session);
$smarty->assign('numero', $numero);
}
// prepare templates
tpl_page('register');

$smarty->assign('userlist', $userlist);
$smarty->assign('message', $message);
$smarty->assign('sitename', $config['site_name']);
$smarty->assign('session', $session);
$smarty->assign('desactiveturing', $config['desactiveturing']);

// display templates
tpl_display('register.tpl');

?>
