#!%PERL% -w
# Copyright (c) vhffs project and its contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions 
# are met:
#
# 1. Redistributions of source code must retain the above copyright 
#   notice, this list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in 
#   the documentation and/or other materials provided with the 
#   distribution.
#3. Neither the name of vhffs nor the names of its contributors 
#   may be used to endorse or promote products derived from this 
#   software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
#FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
#COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.

# subscribe.pl
# Handle subscription for VHFFS
# If the subscribe form has been submitted
# we try to create the user, else display
# the form. If there is an error we inform the
# user and redisplay the form (already filled)
#

use strict;
use utf8;
use POSIX qw(locale_h);
use CGI;
use locale;
use Locale::gettext;
use HTML::Template;
use Encode;
use Authen::Captcha;

use lib '%VHFFS_LIB_DIR%';
use Vhffs::User;
use Vhffs::Main;
use Vhffs::Functions;
use Vhffs::Constants;
use Vhffs::Panel::Main;
use Vhffs::Services::Newsletter;

my $panel = new Vhffs::Panel::Main();
exit 0 unless $panel;

my $vhffs = $panel->{'vhffs'};
my $templatedir = $panel->{'templatedir'};
my $cgi = $panel->{'cgi'};

my $submitted = $cgi->param( 'CREATE_SUBMIT' );
my @errors = ();
my $template;
my $message;

my $usecaptcha = Vhffs::Functions::strtobool( $vhffs->get_config->get_panel->{'use_captcha'} );
my $captchakey = $vhffs->get_config->get_panel->{'captchakey'};

if( $vhffs->get_config->get_allow_subscribe == 0 )
{
	# Subscribe isn't allowed, inform user
        $template = new HTML::Template( filename => $templatedir.'/panel/misc/simplemsg.tmpl');
        $template->param( MESSAGE => gettext('You cannot subscribe to VHFFS') );
	$panel->light( $template );
	$panel->display;
	exit 0;
}


if( defined $submitted ) {
# don't check if form hasn't been submitted

	# get filled in parameters
	my $mail       = $cgi->param( "MAIL" );
	my $username   = $cgi->param( "USERNAME" );
	my $firstname  = Encode::decode_utf8( $cgi->param( "FIRSTNAME") );
	my $lastname   = Encode::decode_utf8( $cgi->param( "LASTNAME" ) );
	my $city       = Encode::decode_utf8( $cgi->param("CITY") );
	my $zipcode    = Encode::decode_utf8( $cgi->param("ZIPCODE") );
	my $country    = Encode::decode_utf8( $cgi->param("COUNTRY") );
	my $address    = Encode::decode_utf8( $cgi->param("ADDRESS") );
	my $newslettercheckbox = $cgi->param('NEWSLETTER');
	$newslettercheckbox = ( defined $newslettercheckbox && $newslettercheckbox eq 'on' );

	if( $usecaptcha ) {
	    	my $codeuser   = $cgi->param('CONFIRMATION');
		my $hexcode    = $cgi->param('CODE');
		my $code = pack('H12', $hexcode);
		$code ^= pack('H12', $captchakey) if defined $captchakey;

		if( ( ! defined $code ) || ( $codeuser ne $code ) )
		{
			push(@errors, {error => gettext("Codes do not match")});
		}
	}

	if( ! defined $username )
	{
		push(@errors, {error => gettext("You must declare your username")});
	}
	if( ! Vhffs::User::check_username($username) )
	{
		push(@errors, {error => gettext('Invalid username, it must contain between 3 and 12 alphanumeric characters, all in lowercase')});
	}
	if( ! defined $country )
	{
		push(@errors, {error => gettext("You must declare your country")});
	}
	if( ! defined $city )
	{
		push(@errors, {error => gettext("You must declare your city")});
	}
	if( ! defined $zipcode )
	{
		push(@errors, {error => gettext("You must declare your zipcode")});
	}
	if( ! defined $firstname )
	{
		push(@errors, {error => gettext("You must declare your firstname")});
	}
	if( ! defined $lastname )
	{
		push(@errors, {error => gettext("You must declare your lastname")});
	}
	if( ( ! defined $mail ) || ( length( $mail ) < 6 ) )
	{
		push(@errors, {error => gettext("You must declare your mail address")});
	}
	if( ! Vhffs::Functions::valid_mail( $mail ) )
	{
		push(@errors, {error => gettext("You must declare a valid mail address")});
	}
	if( $zipcode !~ /^[\w\d\s\-]+$/ )
	{
		push(@errors, {error => gettext("Your zipcode is not correct! Please enter a correct zipcode")});
	}
	if( $firstname !~ /^[^<>"]+$/ )
	{
         push(@errors, {error => gettext("Please enter a correct firstname")});
	}
	if( $lastname !~ /^[^<>"]+$/ )
	{
         push(@errors, {error => gettext("Please enter a correct lastname")});
	}
	if( $city !~ /^[^<>"]+$/ )
	{
         push(@errors, {error => gettext("Please enter a correct city")});
	}
	if( $country =~ /^[<>"]+$/ )
	{
         push(@errors, {error => gettext("Please enter a correct country")});
	}

	if( ( scalar @errors )  == 0)
	{
	    my $retour;
        my $user = Vhffs::User::create( $vhffs, $username, &Vhffs::Functions::generate_random_password(), 
            0, $mail, $firstname, $lastname, $city, $zipcode, $country, $address, "");
		
		if(! defined $user )
		{
		    push( @errors, {error => gettext("Cannot create user, the username you entered already exists")});
		}
		else
		{
		    #We set informations user fill in the form
		    $user->set_status( Vhffs::Constants::WAITING_FOR_CREATION );
		    
		    #Commit all the changes for the current user
		    if( ( $retour = $user->commit ) < 0 )
		    {
			push ( @errors, { error => gettext("Cannot apply changes to the user") } );
		    }
		    else
		    {
			my $good_news = gettext("User Successfully created");
			my $good_news2 = gettext("Please wait while we are creating the account, it will take some minutes");
			$template = new HTML::Template( filename => $templatedir."/panel/user/create_complete.tmpl" );
	    		$template->param( TEXT_BACK => gettext("Back to Login") );
			$template->param( GOOD_NEWS => $good_news );
			$template->param( GOOD_NEWS2 => $good_news2 );

			Vhffs::Acl::add_acl( $user , $user , Vhffs::Constants::ACL_DELETE , $vhffs );
			Vhffs::Acl::add_acl( $user->get_group , $user , Vhffs::Constants::ACL_DENIED , $vhffs );

			# Newsletter
			my $newsletter = init Vhffs::Services::Newsletter( $vhffs , $user );
			if( $newsletter ) {
				if(  ( $newsletter->get_collectmode == Vhffs::Services::Newsletter::ACTIVE_OPTIN && $newslettercheckbox )
				  || ( $newsletter->get_collectmode == Vhffs::Services::Newsletter::PASSIVE_OPTIN && $newslettercheckbox )
				  || ( $newsletter->get_collectmode == Vhffs::Services::Newsletter::ACTIVE_OPTOUT && !$newslettercheckbox )
				  || ( $newsletter->get_collectmode == Vhffs::Services::Newsletter::PASSIVE_OPTOUT )
				  || ( $newsletter->get_collectmode == Vhffs::Services::Newsletter::PERMANENT )
				  ) {
					$newsletter->add;
				}
			}
		    }
		}
	}
	if ( ( scalar @errors ) > 0 ) {
	    $template = new HTML::Template( filename => $templatedir."/panel/user/create.tmpl" );
	    # There was an error, fill the template parameter
	    $template->param( ERRORS => \@errors );
	    $template->param( USERNAME_VALUE         => $username );
	    $template->param( MAIL_VALUE             => $mail );
	    $template->param( FIRSTNAME_VALUE        => $firstname );
	    $template->param( LASTNAME_VALUE         => $lastname );
	    $template->param( ZIPCODE_VALUE          => $zipcode );
	    $template->param( CITY_VALUE             => $city );
	    $template->param( COUNTRY_VALUE          => $country );
	    $template->param( ADDRESS_VALUE          => $address );
	    $template->param( NEWSLETTER_CHECKED     =>	$newslettercheckbox );
	}
} else {
    $template = new HTML::Template( filename => $templatedir."/panel/user/create.tmpl" );
}

if( ( ! defined $submitted ) || (scalar @errors) != 0 )  {
# $template is defined in every cases

    $template->param( TEXT_SUBSCRIBE        => gettext("Subscription") );
    $template->param( TEXT_INFOS            => gettext("Please fill in all fields, a mail containing your password will be sent to you") );
    $template->param( USERNAME_TEXT         => gettext("Username") );
    $template->param( MAIL_TEXT             => gettext("mail") );
    $template->param( FIRSTNAME_TEXT        => gettext("Firstname") );
    $template->param( LASTNAME_TEXT         => gettext("Lastname") );
    $template->param( ZIPCODE_TEXT          => gettext("Zipcode") );
    $template->param( CITY_TEXT             => gettext("City") );
    $template->param( COUNTRY_TEXT          => gettext("Country") );
    $template->param( ADDRESS_TEXT          => gettext("Address") );
    $template->param( SEND                  => gettext("Subscribe") );
    $template->param( BACK                  => gettext("Back to Login") );

	$template->param( USECAPTCHA            => $usecaptcha );
	if( $usecaptcha ) {
		my $captcha = Authen::Captcha->new;
		my $code = $captcha->generate_random_string( 6 );
		$code ^= pack('H12', $captchakey) if defined $captchakey;
		my $hex = unpack('H12', $code);
		$template->param( CODE   => $hex );

		$template->param( CONFIRMATION_TEXT             => gettext('Code confirmation') );
		$template->param( REPEAT_CONFIRMATION_TEXT      => gettext('Recopy the code') );
		$template->param( CONFIRMATION_ALT              => gettext('Confirmation code, contact administrator team if you can\'t read it') );
		$template->param( CONFIRMATION_SOUND_TEXT    => gettext('Or listen to the code') );
	}

	if( $vhffs->get_config->get_service_availability('newsletter') ) {
		my $conf = $vhffs->get_config->get_service('newsletter');
		if( $conf->{'collectmode'} eq 'active_optin' ) {
			$template->param( NEWSLETTER_TEXT    => gettext('Subscribe to the newsletter') );
		} elsif ( $conf->{'collectmode'} eq 'passive_optin' ) {
			$template->param( NEWSLETTER_TEXT    => gettext('Subscribe to the newsletter') );
			$template->param( NEWSLETTER_CHECKED => 1 ) unless defined $submitted;
		} elsif ( $conf->{'collectmode'} eq 'active_optout' ) {
			$template->param( NEWSLETTER_TEXT    => gettext('Don\'t subscribe to the newsletter') );
		}
	}


    $template->param( USERNAME_TIP_TEXT => gettext('Your username. It must contains only alphanumeric characters in lowercase, its length must be between 3 and 12 chars') );
    $template->param( EMAIL_TIP_TEXT => gettext('Your email address. It will be used to contact you when needed and as a destination address if you use our email forwarding service') );
}

$panel->light( $template );
$panel->display;
