<?php
/**
 * Default user/profile template
 * 
 * This file can be overriden. Discover logic and examples on :
 * @url http://dev.linea21.com/projects/linea21/wiki/Override
 * @url http://dev.linea21.com/projects/linea21/wiki/Personnalisation_de_l%27interface_publique
 * 
 * @package linea21\core\public
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */
?>
<?php
include_once(override('../user/display.php'));
include_once(override('../lib/input_helpers.php'));

//////////////////////////////////////////
///// déconnexion utilisateur authentifié
//////////////////////////////////////////

if(ActiveItemKey($GLOBALS['activeitem']) == 'logout') {
    if(! isset($_GET['token']) || $_GET['token'] != $GLOBALS['l21auth']->GetSessionElement('logout_token')) exit('no way !');
	$GLOBALS['l21auth']->logOut();
	header("Location: ".get_referer(true));
}


SetHTMLTitle(_t('user','section')); // set HTML title

//////////////////////////////////////////
/////affichage formulaire Password
//////////////////////////////////////////

if(ActiveItemKey($GLOBALS['activeitem']) == 'forgot-password') {
	
	include_once(override('../mail/mail_actions.php'));
	include_once(override('../mail/send.php'));
	$a = array();
	
	setBreadcrumb(array(ucfirst(_t('user', 'forgot_pass')) => HrefMaker(array('rub'=> $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue']))));
	SetHTMLTitle(ucfirst(_t('user', 'forgot_pass'))); // set HTML title
	echo '<h1>'.ucfirst(_t('user', 'forgot_pass')).'</h1>';

	if(isset($_REQUEST['token'])) {
		$r=$GLOBALS['sql_object']->DBSelect(SQL_get_UserInfoPK($_REQUEST['token']));

		if($r != 0) {
			$user_email=$r[0]['profile_email'];
			$user_login=$r[0]['user_login'];
			$user_id=$r[0]['user_id'];

			include_once('../class/class.user.php');
			$user = new user;
			$a['password'] = $user->GetNewPassword();
			$res = $user->UpdateUserPassword($user_id, $a['password'], $GLOBALS['sql_object']);
			if($res) {
				$user->resetPasskey($user_id, $GLOBALS['sql_object']);
				$a['action'] = 'change_pass';
				$a['recipient'] = $user_email;
				$a['login'] = $user_login;
				
				$emailContainer = prepare_email($a);
				$r = send_email($emailContainer);
				
				echo '<div class="confirmed">'._t('user', 'new_password_confirmation').'</div>';
			}
		} else {
			ReloadIndex('public');
		}
	} else {
		echo forgotPass();
	}
}

//////////////////////////////////////////
/////affichage profil utilisateur
//////////////////////////////////////////

if(ActiveItemKey($GLOBALS['activeitem']) == 'user-profile') {
	setBreadcrumb(array(ucfirst(_t('user', 'profile')) => HrefMaker(array('rub'=> $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue']))));
	/** préparation des variables
	 * 	$id -> default -1
	 **/
	if(isset($_REQUEST['id'])) $id=$_REQUEST['id']; else $id=-1;

	/** Détail d'un utilisateur
	 */
	if(isset($_REQUEST['id'])) {
		// set HTML Title
		$result=$GLOBALS['sql_object']->DBSelect(SQL_getUserLogin($id));
		SetHTMLTitle(formatText($result[0]['user_login'], '2HTML'));
		DisplayInfoUser($id);
	}
}

//////////////////////////////////////////
/////affichage formulaire inscription utilisateur
//////////////////////////////////////////

if(ActiveItemKey($GLOBALS['activeitem']) == 'user-registration') {

    include_once('../class/class.user.php');
    $user_object= new user;
    
	if(defined('FREE_REGISTRATION') && FREE_REGISTRATION == 0)  ReloadIndex('public');
	if(isset($_POST['valid']) || isset($_POST['valid_x'])) {
		$fired = true;

		include_once(override('../mail/mail_actions.php'));
		include_once(override('../mail/send.php'));
		$a = array();
		
		

		$data_table_user[0] = $_POST['login'];
		$data_table_user[1] = $_POST['email'];
		$data_table_user[2] = 'N'; // Affichage public de l'email (par défaut Non)
		$data_table_user[3] = $_POST['firstname'];
		$data_table_user[4] = $_POST['lastname'];
		
		if(isset($_POST['leisures'])) $data_table_user['leisures'] = $_POST['leisures'];
		if(isset($_POST['job'])) $data_table_user['job'] = $_POST['job'];
		
		if(!empty($_POST['password'])) $data_table_user[5] = $_POST['password'];
		else $data_table_user[5] = $user_object -> GetNewPassword();
		
		$result = $user_object->checkPasswordValidity($data_table_user[5]);
		if($result ===  true ) $result=$user_object->CheckDataIntegrity($data_table_user, $GLOBALS['sql_object']);
		
		$data_table_right=$user_object->InitUserRight('SIMPLE_USER');
		
		if(!isset($_POST['gdpr-ok'])) $result = _t('user', 'accept_gdpr');

		if($result===true) {
			
			/** include envoi de mail */
			$a['login'] = $data_table_user[0];
			$a['recipient'] = $data_table_user[1];
			$a['password'] = $data_table_user[5];
			$a['action'] = 'add_user';
			
			$emailContainer = prepare_email($a);
			$r = send_email($emailContainer);
			/** end mail */

			$result=$user_object->AddUser($data_table_user, $data_table_right, $GLOBALS['sql_object']);
			if(is_numeric($result)) $msg='<p class="confirmed">'._t('user','confirm_public').'</p>'.PHP_EOL;
		}

	}

	SetHTMLTitle(_t('divers','user_inscription'));
	echo '<h1>'._t('divers','user_inscription').'</h1>'.PHP_EOL;
	echo '<div class="sub-title">';
	echo _t('user','h1_public_comment_insc');
	echo '</div>';
	if(isset($result) && !is_numeric($result)) {
		echo '<p class="error">'.PHP_EOL;
		echo $result.PHP_EOL;
		echo '</p>'.PHP_EOL;
	} else {
		if(isset($msg)) echo $msg;
	}

	if(!isset($result) || (isset($result) && !is_numeric($result))) echo AuthForm('SUBSCRIBE', 1, $user_object);

}

//////////////////////////////////////////
/////affichage prefs utilisateurs
//////////////////////////////////////////

if(ActiveItemKey($GLOBALS['activeitem']) == 'user-prefs') {
	setBreadcrumb(array(ucfirst(_t('divers', 'myprofile')) => HrefMaker(array('rub'=> $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue']))));
	SetHTMLTitle(_t('divers','auth'). ' / '._t('user','p_mod'));

	$submitted = -1;

	if(isset($_REQUEST['login'])) {
		include_once('../class/class.auth.php');

		if(isset($_POST['rememberme'])) {
			$rememberme = true;
		} else {
			$rememberme = false;
		}

		$auth_value= $GLOBALS['l21auth']->logIn($_POST['login'], $_POST['password'],  'PUBLIC', $rememberme);
		// be sure the referer starts with the right URL before using it
		if(Stringy\Stringy::create($_POST['referer'], CHARSET)->startsWith(CURRENT_APP_URL)) {
			$redirect = $_POST['referer'];
		} else {
			// handle redirect when user is not authenticated
			if(isset($_GET['refer'])) $redirect = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
			else $redirect = CURRENT_APP_URL;
		}
		if($auth_value === true) header("Location: ".safe_redirect($redirect));
	}

	if(isset($_SESSION['authenticated'])) {

		if(isset($_REQUEST['current_email'])) {
			$update_msg = ModifyProfile();
			$submitted=1;
		}

		$content ='<h1>'._t('user','p_mod'). ' - ' .$_SESSION['userlogin']. '</h1>'.PHP_EOL;
		$content.='<div class="sub-title">';
		$content.=_t('user','h1_public_comment');
		$content.='</div>';
    
		echo GetLinkSeeUserInfo(base64_decode($_SESSION['userid']));
		
		echo $content;
		// confirmation messages on deleting avatar
		if(isset($_REQUEST['delavatar'])) {
			deleteUserAvatar();
		}
		// confirmation message on changes
		if(isset($_REQUEST['notifyUpdate'])) {
			ChangeNotifySettings(base64_decode($_SESSION['userid']));
		}
		if(isset($update_msg)) {
			echo $update_msg;
		}
		DisplayFormProfileUser(base64_decode($_SESSION['userid']), $submitted);
		echo '<h1>'._t('user','preferences').'</h1>'.PHP_EOL;
		DisplayWorkgroupsSettings(base64_decode($_SESSION['userid']));


	} else {
		echo '<h1>'._t('divers','auth').'</h1>'.PHP_EOL;
		echo '<div class="sub-title">';
		echo _t('user','h1_public_comment_auth');
		echo '</div>';

		if(isset($auth_value)) {
			echo '<p class="error">'.PHP_EOL;
			echo $auth_value.PHP_EOL;
			echo '</p>'.PHP_EOL;
		}
		echo '<div id="cookieEnabled"></div>';
		echo '<script type="text/javascript">cookieAlert("#cookieEnabled", "'._t('alert', 'cookie_disabled').'");</script>';
		echo AuthForm('LOGON');
		DisplayAuthTextInfo();
	}

}

?>