<?php

	//Récuperation d'une liste d'utilisateurs en attente de validation
	Action::register('subscribe_search',function(&$response){
	
			global $myUser,$_;
			User::check_access('subscribe','read');
		
	});

	//Ajout ou modification d'élément
	Action::register('subscribe_save',function(&$response){
	
			global $myUser,$_,$conf;

			Plugin::callHook('subscribe_validate',array());

			if(empty($_['firstname'])) throw new Exception('Le champ "Prénom" est obligatoire');
			if(empty($_['name'])) throw new Exception('Le champ "Nom" est obligatoire');

			$_['mail'] = mb_strtolower(trim($_['mail']));
			if(empty($_['mail'])) throw new Exception('Le champ "Email" est obligatoire');
			if(!check_mail($_['mail'])) throw new Exception('Le format du champ "Email" est invalide');
			if(empty($_['mail_confirm']) || $_['mail'] != $_['mail_confirm']) throw new Exception('Champs "Email" et "Confirmation email" non similaires');

			//Récupération du domaine
			preg_match("/.*@(.*)/i", $_['mail'], $matches);

			if(!empty($conf->get('subscribe_enable_blacklist'))) {
				$blacklist = array();
				foreach(Dictionary::bySlug('subscribe_domain_blacklist', true) as $domain)
					$blacklist[] = trim($domain->label);

				if(!isset($matches[1]) || in_array($matches[1], $blacklist)) throw new Exception("Le domaine utilisé pour l'adresse mail n'est pas autorisé");
			}

			if(!empty($conf->get('subscribe_enable_whitelist'))) {
				$whitelist = array();
				foreach(Dictionary::bySlug('subscribe_domain_whitelist', true) as $domain)
					$whitelist[] = trim($domain->label);

				if(!isset($matches[1]) || !in_array($matches[1], $whitelist)) throw new Exception("Le domaine utilisé pour l'adresse mail n'est pas autorisé");
			}

			if(empty($_['password_initialisation'])) throw new Exception("Mot de passe obligatoire");
			if(!empty($conf->get('password_forbidden_char')) && preg_match('|['.preg_quote(htmlspecialchars_decode($conf->get('password_forbidden_char'))).']|i', htmlspecialchars_decode($_['password_initialisation']), $match))
				throw new Exception("Caractère ".$match[0]." interdit dans le mot de passe");
			$_['password_initialisation'] = trim($_['password_initialisation']);
			$_['password_confirm'] = trim($_['password_confirm']);
			if(empty($_['password_confirm']) || $_['password_initialisation'] != $_['password_confirm']) throw new Exception("Mot de passe et confirmation non similaires");

			$passwordErrors = User::check_password_format(html_entity_decode($_['password_initialisation']));
			if(count($passwordErrors)!=0) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : <br>".implode("<br>",$passwordErrors));

			if($conf->get('subscribe_enable_captcha')){
				//Vérification du code captcha
				if(!isset($_['captcha']) || (empty($_['captcha']) && $_['captcha'] != 0)) throw new Exception('Veuillez remplir le champ anti-robots');
				subscribe_captcha($_['captcha']);
			}

			if(empty($conf->get('subscribe_firm'))) throw new Exception("Module non configuré (établissement), merci de contacter un administrateur");
			if(empty($conf->get('subscribe_rank')) && empty($conf->get('connected_default_rank'))) throw new Exception("Module non configuré (rang), merci de contacter un administrateur");

			$user = new User;
			$user->firstname = ucfirst(mb_strtolower($_['firstname']));
			$user->name = mb_strtoupper($_['name']);
			$user->login = $_['mail'];
			if($conf->get('subscribe_short_login')) $user->login = preg_replace('/^([^@]+)@.*\.[a-z]{2,6}/im', '$1', $user->login);
			$user->mail = $_['mail'];

			if($_['password_initialisation']==$user->mail) throw new Exception("Le mot de passe ne peut pas être identique à l'adresse mail");
			if($_['password_initialisation']==$user->login) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant");

			foreach(User::getAll(array('right'=>false, 'force'=>true)) as $existingUser){
				if($existingUser->mail == trim($user->mail)) throw new Exception("Un utilisateur existe déjà avec cette adresse email, ".(!empty($conf->get('password_allow_lost'))?"veuillez utiliser le système de mot de passe oublié":"veuillez contacter un administrateur"));
				if($existingUser->login == $user->login) throw new Exception("Un utilisateur existe déjà avec cet identifiant, ".(!empty($conf->get('password_allow_lost'))?"veuillez utiliser le système de mot de passe oublié":"veuillez contacter un administrateur"));
			}

			$user->state = $conf->get('subscribe_disable_mail') ? User::ACTIVE : 'registered';
			$user->password = User::password_encrypt($_['password_initialisation']);
			$user->preference('passwordTime',time());

			$token = base64_encode(sha1($user->login.mt_rand(0,1000).time()));
			$user->token = $token;
			$user->save();

			//clear du captcha utilisé
			subscribe_captcha('off');

			//validation par mail si non désactivé
			if(!$conf->get('subscribe_disable_mail')){
				$expDays = intval($conf->get('subscribe_mail_expire'));
				$parameters = array('token' => $user->token,'step' => 1,);
				$link = ROOT_URL.'/index.php?module=subscribe&page=validation&token='.base64_encode(json_encode($parameters));

				$mail = new Mail();
				$mail->title = "Inscription sur ".ROOT_URL;
				$mail->expeditor = !empty($conf->get('subscribe_reply_mail')) ? $conf->get('subscribe_reply_mail') : "no-reply@core.fr";
				$mail->reply = !empty($conf->get('subscribe_reply_mail')) ? $conf->get('subscribe_reply_mail') : "no-reply@core.fr";
				$mail->template(__DIR__.SLASH.'mail.subscription.html',array(
					'link' => $link,
					'url' => ROOT_URL,
					'name' => $user->name,
					'firstname' => $user->firstname,
					'accountExpiration' => !empty($conf->get('subscribe_registered_expire')) ? intval($conf->get('subscribe_registered_expire')) : '',
					'expDays' => $expDays,
					'expDate' => !empty($expDays) ? date("d/m/Y à H:i", strtotime($expDays." days")) : ''
				),true);
				$mail->recipients['to'][] = $user->mail;
				$mail->send();
			} else {
				$response['login'] = $user->login;
			}
			if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
			if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);

			Log::put("Inscription de l'utilisateur ".$user->toText(),'Utilisateur');
			Plugin::callHook('subscribe_save',array(&$fields));
		
	});

	//Édition d'utilisateur en attente de validation
	Action::register('subscribe_edit',function(&$response){
	
			global $myUser,$_;
			User::check_access('subscribe','delete');

		
	});

	//Suppression d'utilisateur en attente de validation
	Action::register('subscribe_delete',function(&$response){
	
			global $myUser,$_;
			User::check_access('subscribe','delete');

		
	});

	//Sauvegarde des configurations de subscribe
	Action::register('subscribe_setting_save',function(&$response){
	
			global $myUser,$_,$conf;
			User::check_access('subscribe','configure');

			foreach(Configuration::setting('subscribe') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value)
				if(in_array($key, $allowed)){
					if($key == 'subscribe_mail_expire' && (!is_numeric($value) || $value<0)) $value = 0;
					$conf->put($key,$value);
				}
		
	});

	//Récupération card des règles de mot de passe
	Action::register('subscribe_password_card',function(&$response){
	
			global $_,$conf;
			$selectedFormats = json_decode($conf->get('password_format'),true);
			$passwordInput = isset($_['password']) ? trim($_['password']) : '';

			$formats = array();
			foreach (User::password_formats() as $format)
				$formats[$format['pattern']] = $format;

			ob_start();
			require_once(__DIR__.SLASH.'card.subscribe.password.php');
			$stream = ob_get_clean();
			$response['content'] = $stream;
		
	});

