<?php

/**
 * Snippet to display and action the members login form.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\members
 * @copyright Copyright (c) 2012 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/* @var $tplEngine cfTemplateEngine */
$controller = $tplEngine->controller;

$uMgr = clearFusionCMS::getUserMgr();

if($controller->getRequest()->hasParam('id') && $controller->getRequest()->hasParam('activate') && preg_match('/^\d+$/', $controller->getRequest()->getParam('id')) && preg_match('/^[a-z0-9]{32}$/', $controller->getRequest()->getParam('activate'))) {
	if(($info = $uMgr->getInfo($controller->getRequest()->getParam('id'))) && $uMgr->verifyHash($info['email'], $controller->getRequest()->getParam('activate'))) {
		$uMgr->setState($controller->getRequest()->getParam('id'), 'active');

		// If site owner requires notification
		if(isset($notifyEmail)) {
			// Send activation email
			$info = $uMgr->getInfo($controller->getRequest()->getParam('id'));
			$data = array(
				'sitename' => clearFusionCMS::getSiteName(),
				'username' => $usernameRequired ? $info['username'] : '',
				'email' => $info['email']
			);

			// Process the HTML and text email bodies
			$cfg = clearFusionCMS::getSiteConfig('cfMembers');
			$tplEngine = new cfTemplateEngine($controller);
			$html = $tplEngine->parseString("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n</head>\n<body>\n" . $cfg->newUserEmailHTML . "\n</body>\n</html>\n", $data);
			$text = $tplEngine->parseString($cfg->newUserEmail, $data);

			$mailer = clearFusionCMS::getMailer();
			if($mailer->connect()) {
				$mailer
					->setTextBody($text)
					->setHTMLBody($html)
					->setSubject(str_replace('[[+sitename]]', clearFusionCMS::getSiteName(), $cfg->newUserSubject))
					->addRecipient($notifyEmail);

				$mailer->send();
				$mailer->close();
			}
		}

		// Auth the user
		$uMgr->authUser($controller->getResponse(), $controller->getRequest()->getParam('id'));

		if(isset($onActivated))
			clearFusionCMS::getResponse()->redirectTo($controller->content->getPageURI($onActivated, true));
		else
			echo __('<p>Your account has been activated.</p>', 'members');
	}
	else if(isset($onNotActivated))
		clearFusionCMS::getResponse()->redirectTo($controller->content->getPageURI($onNotActivated, true));
	else
		echo __('<p>Your account could not be activated.</p>', 'members');
}
else {

	$usernameRequired = isset($usernameRequired) ? $usernameRequired : 1;

	$form = new flForm(clearFusionCMS::getRequest(), 'userregistrationform', $controller->content->getPageURI($controller->pageData['id']), true);

	if($usernameRequired) {
		$username = new flFormElementText($form, 'username');
		$username->setLabel(__('Username', 'members'))
			->setAutocomplete('username')
			->setRequired()
			->addValidator(new flFormValidatorRequired())
			->addValidator(new flFormValidatorMinLength(3))
			->addValidator(new flFormValidatorMaxLength(100))
			->addValidator(new flFormValidatorRegex('/^[0-9a-zA-Z.-_]+$/', __('The username can only contain numbers, letters and the characters ., - and _.', 'members')))
			->addValidator(new cfValidatorUsername());
	}

	$email = new flFormElementEmail($form, 'email');
	$email->setLabel(__('Email', 'members'))
		->setAutocomplete('email')
		->setRequired()
		->addValidator(new flFormValidatorRequired())
		->addValidator(new flFormValidatorMaxLength(200))
		->addValidator(new cfValidatorUserEmail());

	if(isset($dispNameRequired) && $dispNameRequired) {
		$dispname = new flFormElementText($form, 'dispname');
		$dispname->setLabel(__('Display Name', 'members'))
			->setAutocomplete('name')
			->setRequired()
			->addValidator(new flFormValidatorRequired())
			->addValidator(new flFormValidatorMinLength(3))
			->addValidator(new flFormValidatorMaxLength(100));
	}

	$password = new flFormElementPassword($form, 'pwd1');
	$password->setLabel(__('Password', 'members'))
		->setAutocomplete('new-password')
		->setRequired()
		->setDescription(__('The password must be at least 8 characters long.', 'members'))
		->addValidator(new flFormValidatorRequired())
		->addValidator(new flFormValidatorMinLength(8));

	$pwd2 = new flFormElementPassword($form, 'pwd2');
	$pwd2->setLabel(__('Confirm Password', 'members'))
		->setAutocomplete('new-password')
		->setRequired()
		->addValidator(new flFormValidatorSameAs($password));

	$cfg = clearFusionCMS::getSiteConfig('cfSystemTZ');
	$tz = new flFormElementSelect($form, 'tz', $cfg->timezone, flDateTzMenu::get());
	$tz->setLabel(__('Timezone', 'members'));

	$userProfile = new cfUserProfile(clearFusionCMS::getDb(), null, cfUserProfile::REGISTRATION);
	$userProfile->addFields($form);

	// Enable recaptcha
	if(isset($siteKey) && isset($secretKey)) {
		$recaptcha = new flFormElementRecaptcha($form, 'recaptcha', $siteKey, $secretKey);
	}
	else if(isset($recaptcha) && $recaptcha) {
		$cfg = clearFusionCMS::getSiteConfig('cfSystemSocialAPI');
		$recaptcha = new flFormElementRecaptcha($form, 'recaptcha', $cfg->get('recaptcha_sitekey'), $cfg->get('recaptcha_secretkey'));
	}

	$submit = new flFormElementSubmit($form, 'register');
	$submit->setCaption(__('Register Account', 'members'))->setCSS('primary');

	$form->groupElements('regsubmit', array($submit), new flFormDecoratorList(new flFormDecoratorDl()));

	$form->focusElement($usernameRequired ? $username : $email);

	$show = true;
	if($form->isSubmitted() && $form->isValid() && !$form->isInvalidated()) {

		// Create the user
		if(!($uid = $uMgr->create($usernameRequired ? $username->getValue() : null, $email->getValue(), $password->getValue(), 'pending', $tz->getValue(), isset($dispname) ? $dispname->getValue() : '')))
			$username->forceError(__('Unable to create your user, please try again.', 'members'));
		else {
			// Set roles
			$cfg = clearFusionCMS::getSiteConfig('cfMembers');
			$uMgr->setUserRoles($uid, unserialize($cfg->defaultRoles));

			$userProfile->setUser($uid)->processFields($form);

			// Send activation email
			$data = array(
				'sitename' => clearFusionCMS::getSiteName(),
				'username' => $usernameRequired ? $username->getValue() : '',
				'activateuri' => $controller->content->getPageURI($controller->pageData['id'], true) . '?id=' . $uid . '&amp;activate=' . $uMgr->getVerificationHash($uid)
			);

			// Process the HTML and text email bodies
			$tplEngine = new cfTemplateEngine($controller);
			$html = $tplEngine->parseString("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n</head>\n<body>\n" . $cfg->activationEmailHTML . "\n</body>\n</html>\n", $data);
			$text = $tplEngine->parseString($cfg->activationEmail, $data);

			$mailer = clearFusionCMS::getMailer();
			if($mailer->connect()) {
				$mailer
					->setTextBody($text)
					->setHTMLBody($html)
					->setSubject(str_replace('[[+sitename]]', clearFusionCMS::getSiteName(), $cfg->activationSubject))
					->addRecipient($email->getValue());

				$mailer->send();
				$mailer->close();

				// Tell user all done
				$show = false;
				if(isset($onEmailSent))
					clearFusionCMS::getResponse()->redirectTo($controller->content->getPageURI($onEmailSent, true));
				else
					echo __('<p>An activation email has been sent to the email address that you provided, please follow the instructions in it to finish registration and activate your account.</p>', 'members');
			}
			else
				$username->forceError(__('Failed to send the activation email, please try again.', 'members'));
		}
	}

	if($show)
		echo $form->render($tplEngine->getCodeBuffer());
}
