<?php

/**
 * This file is part of LEPTON Core, released under the GNU GPL
 * Please see LICENSE and COPYING files in your package for details, specially for terms and warranties.
 * 
 * NOTICE:LEPTON CMS Package has several different licenses.
 * Please see the individual license in the header of each single file or info.php of modules and templates.
 *
 * @author          Website Baker Project, LEPTON Project
 * @copyright       2004-2010 Website Baker Project
 * @copyright       2010-2026 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         https://gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */

// include secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/secure.php' );}
if (defined('LEPTON_PATH')) {	
	include LEPTON_PATH.SEC_FILE;
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.SEC_FILE))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.SEC_FILE)) { 
		include $root.SEC_FILE;   
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include secure file


// [1] See if there exists a frontend template file or use the fallback
if (LEPTON_handle::require_alternative('login/signup2.php', 'frontend'))
{
    return 0;
}
else
{
	// Get details entered
	$MESSAGE = LEPTON_core::getGlobal("MESSAGE");
	$mail = LEPTON_mailer::getInstance();
	$oAC = account::getInstance();


	$signup_id = FRONTEND_SIGNUP;
	$active = 1;
	$username = LEPTON_core::getValue('username','username','post') ?? "";	
	$display_name = LEPTON_core::getValue('display_name','username','post') ?? "";
	$mail_to = LEPTON_core::getValue('email','email','post');

	// Check Captcha
	if (ENABLED_CAPTCHA)
	{		
		if (isset($_POST['captcha']))
		{
			// Check for a mismatch
			if ($_POST['captcha'] != $_SESSION['captcha'.$_SESSION['captcha_id']])
			{
				account::print_error($MESSAGE['MOD_FORM_INCORRECT_CAPTCHA']);
			}
		} 
		else 
		{
			account::print_error($MESSAGE['MOD_FORM_INCORRECT_CAPTCHA_MISSING']);
		}
	}
	if (isset($_SESSION['captcha'.$_SESSION['captcha_id']]))
	{
		unset($_SESSION['captcha'.$_SESSION['captcha_id']]); 
	}

	// Delete not confirmed entries. older than 1 hour
	$database->simple_query("DELETE from `".TABLE_PREFIX."users` where (`password` = 'unconfirmed signup') AND (`login_ip` < ( UNIX_TIMESTAMP() - 3600 ))");

	// Check if username already exists
	$results = $database->get_one("SELECT user_id FROM ".TABLE_PREFIX."users WHERE username = '".$username."'");
	if(!is_null($results)) 
	{
		account::print_error($MESSAGE['USERS_USERNAME_TAKEN']);
	}

	// Check if the email already exists
	$results = $database->get_one("SELECT user_id FROM ".TABLE_PREFIX."users WHERE email = '".$mail_to."'");
	if(!is_null($results)) 
	{
		account::print_error($MESSAGE['USERS_EMAIL_TAKEN']);
	}

	// insert new user and send confirmation link, create hash
	$confirm_hash = time();

	// create confirmation link
	$enter_pw_link = LEPTON_URL.'/account/new_password.php?hash='.$confirm_hash.'&signup=1';
	$language = DEFAULT_LANGUAGE;

	//save into database
	$fields = [
		'login_ip'	=>	$confirm_hash,
		'groups_id'	=>	$signup_id,
		'active'	=>	$active,
		'username'	=>	$username,
		'language'	=>	$language,
		'password'	=>	'unconfirmed signup',
		'display_name'	=>	$display_name,
		'email'		=>	$mail_to	
		];
	$database->build_and_execute( 
		'INSERT', 
		TABLE_PREFIX."users", 
		$fields
	);
												

	//send confirmation link to email
	$mail->addAddress($_POST['email']);
	$mail->Subject = $MESSAGE['SIGNUP2_SUBJECT_LOGIN_INFO'];

	// Replace placeholders from language variable with values
	$values = [
		"\n"	=> "<br />",
		'{LOGIN_DISPLAY_NAME}'	 =>  $display_name,
		'{LOGIN_WEBSITE_TITLE}'	 =>  WEBSITE_TITLE,
		'{ENTER_PW_LINK}'	 	=>  $enter_pw_link
	];

	$mail_message = str_replace( array_keys($values), array_values($values),$MESSAGE['SIGNUP2_BODY_LOGIN_INFO']);

	$data = [
		'LOGIN_DISPLAY_NAME'=>  $display_name,
		'LOGIN_TITLE'	 	=>  WEBSITE_TITLE,
		'HASH_PW_LINK'	 	=>  $enter_pw_link,
		'MAIL_MESSAGE'	 	=>	$mail_message,
		'oAC'	 			=>	$oAC
	];
	
	$sMailTemplate = $oAC->oTWIG->render('signup_mail_verify.lte',$data);
	$mail->Body = $sMailTemplate;	

	//send the message, check for errors
	if (!$mail->send()) 
	{
		$database->simple_query("DELETE FROM ".TABLE_PREFIX."users WHERE username = '".$username."' ");
		$aMessage = [
		    $MESSAGE['FORGOT_PASS_CANNOT_EMAIL'],
		    $TEXT['TFA_NOTICE_VI']
		];
		LEPTON_frontend::displayFEMessage(
		    "error",
		    $aMessage,
		    LEPTON_URL.'/account/signup.php',
		    2000
		);
		exit();
	}

	echo LEPTON_tools::display($MESSAGE['FORGOT_PASS_PASSWORD_RESET'],'div','ui signup2 message');
}