# Copyright (C) 2005 FishGrove Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id: loginexec.pm,v 1.1 2006/03/07 14:39:10 slash5234 Exp $

package Affelio::App::Standalone::Public::Bin::loginexec;
{
    use strict;

    use lib("../../../../../../extlib/");
    use lib("../../../../../../lib/");
    use Affelio::misc::CGIError;
    use Affelio::misc::Debug qw(debug_print);

    use Exporter;
    @Affelio::App::Standalone::Public::Bin::loginexec::ISA = "Exporter";
    @Affelio::App::Standalone::Public::Bin::loginexec::EXPORT = qw (run);

    #######################################################################
    #run
    #######################################################################
    sub run{

use CGI qw(-unique_headers);
use CGI::Session;
use HTML::Template;
use Error qw(:try);
use Affelio;
use Affelio::App::Standalone::Env;
use Affelio::misc::Time;
use Affelio::misc::NetMisc;
use Affelio::misc::MyCrypt;
use Affelio::misc::WebInput;
use Affelio::SNS::Handshaker_c;

my $q = new CGI;

debug_print("StandAlone::loginexec.cgi: **start.");

############################################################################
#Load Affelio
############################################################################
my $cfg_dir = "../config/";
my $af;
try{
    $af = new Affelio(ConfigDir => $cfg_dir,
		      CGI => $q);
}catch Error with{
    my $e = shift;
    error($q, "Affelio load error.\n" . $e);
};
my $wi = new Affelio::misc::WebInput;
debug_print("StandAlone::loginexec.cgi: loaded Affelio.");

############################################################################
#Prep (1) input args
############################################################################
#mode
my $mode = $wi->PTN_mode($q->url_param("mode"));

#username or affelio_url
my $affelio_url = $wi->PTN_through($q->param("affelio_url"));
my $username = $wi->PTN_word($q->param("username"));

#password
my $password = $wi->PTN_through($q->param("password"));

#forward_URL
#  After authentication, browser must be forwarded to $forward_URL
#  Usually, $forward_URL is the user's AFLink person's page.
my $forward_URL = $wi->PTN_URL($q->url_param("forward_URL"));
#aftergo_URL
#  After browser is forwarded to $forward_URL (after auth.), 
#  $aftergo_URL is one more further URL that the browser needs 
#  to be fowarded to.
my $aftergo_URL = $wi->PTN_URL($q->url_param("aftergo_URL"));

#type from FORM
my $submit_type = $wi->PTN_mode($q->param("submittype"));
debug_print("StandAlone::loginexec.cgi: checked input args.");

############################################################################
#Prep (2) misc
############################################################################
#farm_users_root
#  This Affelio's 1-step parent URL.
#  e.g.  this Affelio    : http://my.affelio.jp/user/foo
#  e.g.  farm_users_root : http://my.affelio.jp/user/
my $farm_users_root = $af->{site__user_afid};
$farm_users_root =~ s|/$||;
$farm_users_root =~ s|/([A-Za-z0-9\-\_]+)$|/|;

#output data
my $issued_cookie="";
my $next_url;

debug_print("StandAlone::\t\tmode       = $mode");
debug_print("StandAlone::\t\taffelio_url= $affelio_url");
debug_print("StandAlone::\t\tusername   = $username");
debug_print("StandAlone::\t\tpassword   = $password");
debug_print("StandAlone::\t\tforward    = $forward_URL");
debug_print("StandAlone::\t\taftergo    = $aftergo_URL");
debug_print("StandAlone::\t\tfarm_users_root   = $farm_users_root");    

############################################################################
#Already logined?
############################################################################
if($af->getSM->get_userclass() eq "self"){
    #Yes, the user is already logged in as the owner.

}else{
    #No, this user has to be authenticated.

    if($mode eq ""){
	###################################################################
	#Protocol V1
	###################################################################
	if(  (verify_password($password, $af->{site__password}) > 0) 
	     && ($username eq $af->{site__username}) ){
	    debug_print("StandAlone::loginexec.cgi: AUTH OK.\n");
	    #login OK
	}else{
	    #login failed.
	    debug_print("StandAlone::loginexec.cgi: AUTH NG.\n");
	    
	    my $TMPL_FILE = "$af->{site__tmpl_dir}/owner_side/loginfailed.tmpl";
	    my $tmpl = new HTML::Template( filename => $TMPL_FILE);
	    $tmpl->param("forward_URL" => $af->{site__user_afid});
	    $tmpl->param("tmpl_path" => "$af->{site__tmpl_web_path}");
	    print "Content-type: text/html; charset=UTF-8\n\n";
	    print $af->translate_templateL10N($tmpl->output);
	    
	    debug_print("StandAlone::loginexec.cgi: exit(1).\n");    
	    exit(1);
	}    
    
    }elsif($mode eq "s0"){
	####################################################################
	#Phase V2: Phase S0
	####################################################################
	if($affelio_url eq $af->{site__username}){
	    ##################################
	    #input URL = site owner's nickname
	    ##################################
	    show_checkpassword_screen(af => $af,
				      forward_URL => $forward_URL,
				      aftergo_URL => $aftergo_URL,
				      mode => "login_as_owner");
	    exit(1);

	}else{
	    ##################################
	    #Else
	    ##################################
	    $affelio_url =~ /^([A-Za-z0-9\-\_]*)$/;
	    if ($1 eq $affelio_url){
		$affelio_url = $farm_users_root . $affelio_url;
	    }

	    if($affelio_url !~ /^(http:\/\/)/){
		$affelio_url = "http://" . $affelio_url;
	    }
	    if($affelio_url =~ /(.*)\/$/){
		$affelio_url = $1;
	    }
	    debug_print("StandAlone::loginexec.cgi($mode): formated Affelio URL= [$affelio_url]");

	    if($affelio_url eq $af->{site__user_afid}){

		show_checkpassword_screen(af => $af,
					  forward_URL => $forward_URL,
					  aftergo_URL => $aftergo_URL,
					  mode => "login_as_owner");

		exit(1);
	    }

	    ##################################
	    #Determine aftergo_URL
	    ##################################
	    #aftergo_URL is a URL to which the user will be forwarded after auth.
	    if($aftergo_URL eq ""){
		$aftergo_URL= $ENV{HTTP_REFERER};
	    }

	    ##################################
	    #Determine forward_URL
	    ##################################
	    if($forward_URL eq ""){
		$forward_URL= $af->{site__user_afid};
	    }
	    
	    ##################################
	    #Go to "s1" phase...
	    ##################################
	    my $next_URL
		= "$affelio_url/bin/loginexec.cgi?mode=s1&forward_URL=$forward_URL&aftergo_URL=$aftergo_URL";
	    debug_print("StandAlone::\t\tnext_URL= $next_URL");
	    debug_print("StandAlone::loginexec.cgi($mode): end.");
	    print $q->redirect( -url => $next_URL);
	    exit(1);
	}

    }elsif($mode eq "s1"){
	####################################################################
	#Phase V2: Phase S1
	# (password input phase)
	####################################################################
	show_checkpassword_screen(af => $af,
				  forward_URL => $forward_URL,
				  aftergo_URL => $aftergo_URL,
				  mode => "back_from_friend");
	debug_print("StandAlone::loginexec.cgi($mode): end.");
	exit(1);
	
    }elsif($mode eq "s2"){ 
	####################################################################
	#Phase V2: Phase S2
	# (auth check phase)
	####################################################################
	debug_print("StandAlone::loginexec.cgi($mode): submit_type= $submit_type");
	if($submit_type eq "Cancel"){
	    if($aftergo_URL eq ""){
		print $q->redirect( -url => $af->{site__user_afid});
		exit;
	    }else{
		print $q->redirect( -url => $aftergo_URL);
		exit;
	    } 

	}

	if(  (verify_password($password, $af->{site__password}) > 0) ){
	    debug_print("StandAlone::loginexec.cgi: AUTH Ok.\n");
	}else{
	    #login failed.
	    debug_print("StandAlone::loginexec.cgi: AUTH NG.\n");

	    my $loginfailed=
		$af->translate_templateL10N('<AF_M text="Login failed.">');

	    if($affelio_url eq $af->{site__username}){
		sleep(3);
		show_checkpassword_screen(af => $af,
					  forward_URL => $forward_URL,
					  aftergo_URL => $aftergo_URL,
					  mode => "login_as_owner",
					  error => $loginfailed);
	    }else{
		sleep(3);
		show_checkpassword_screen(af => $af,
					  forward_URL => $forward_URL,
					  aftergo_URL => $aftergo_URL,
					  mode => "back_from_friend",
					  error => $loginfailed);
	    }
	    
	    debug_print("StandAlone::loginexec.cgi: exit(1).\n");    
	    exit(1);
	}    
    }
    
    #######################################################################
    #Startup new session
    #######################################################################
    $af->getSM->startup_session(user_afid => $af->{site__user_afid},
				user_nickname => $af->{user__nickname},
				type => "self");
    $af->getSM->get_session->expire("+3d");
    $af->getSM->get_session->flush();

    debug_print("StandAlone::loginexec.cgi: startup_session finished.\n");    

    #Prepare a cookie with the session_id
    $issued_cookie = $af->getSM->issue_cookie();
}

############################################################################
#Check if forward_URL is my friend
############################################################################
if($forward_URL ne ""){
    if($forward_URL =~ /(.*)\/$/){
	$forward_URL = $1;
    }
    debug_print("StandAlone::loginexec.cgi: ForwardURL= $forward_URL");

    my $passAB="";
    try{
	$passAB = $af->getFM->get_attribute_by_afid($forward_URL, "password");
    }catch Error with{
	my $e = shift;
	error($q, "Error from FriendManager.\n" . $e);
    };

    if($passAB eq ""){
	show_askmakefriend_screen($af, $forward_URL);
	exit;
    }else{
	$next_url= "$af->{site__user_afid}/outgoing.cgi?dest_url=$forward_URL&dest_url2=$aftergo_URL"; 
    }
}else{
    $next_url= "$af->{site__user_afid}/admin.cgi";
}

if($issued_cookie){
    print $q->redirect( -url => $next_url, -cookie => $issued_cookie);
}else{
    print $q->redirect( -url => $next_url);
}

exit(1);

    }#method
    #######################################################################

############################################################################
# sub show_askmakefriend_screen
############################################################################
sub show_askmakefriend_screen{
    my $af =shift;
    my $forward_URL =shift;

    my $TMPL_FILE = "$af->{site__tmpl_dir}/owner_side/ask_makefriend.tmpl";
    my $tmpl = new HTML::Template( filename => $TMPL_FILE,
				   die_on_bad_params => 0);
    $tmpl->param("owner_nickname" => $af->{user__nickname});
    $tmpl->param("tmpl_path" => "$af->{site__tmpl_web_path}");
    $tmpl->param("admin_path" => "$af->{site__user_afid}/admin.cgi?mode=makefriend&dest_url=$forward_URL");
    $tmpl->param("dest_affelio_URL" => $forward_URL);

    print "Content-type: text/html; charset=UTF-8\n\n";
    print $af->translate_templateL10N($tmpl->output);
}

############################################################################
# sub show_checkpassword_screen
############################################################################
sub show_checkpassword_screen{
    my %args = @_;

    my $af = $args{af};
    my $forward_URL = $args{forward_URL};
    my $aftergo_URL = $args{aftergo_URL};

    my $TMPL_FILE = "$af->{site__tmpl_dir}/owner_side/login_s1.tmpl";
    my $tmpl = new HTML::Template( filename => $TMPL_FILE,
				   die_on_bad_params => 0);
    $tmpl->param("owner_nickname" => $af->{user__nickname});
    $tmpl->param("tmpl_path" => "$af->{site__tmpl_web_path}");
    $tmpl->param("cgi_path" => "$af->{site__user_afid}/bin/loginexec.cgi?mode=s2&forward_URL=$forward_URL&aftergo_URL=$aftergo_URL");
    $tmpl->param($args{mode} => "true");
    $tmpl->param(error => $args{error});

    print "Content-type: text/html; charset=UTF-8\n\n";
    print $af->translate_templateL10N($tmpl->output);
}
############################################################################


}
1;
