# 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: Admin.pm,v 1.1 2006/03/07 14:39:09 slash5234 Exp $

package Affelio::App::Standalone::Admin;
{
    use strict;
    use lib("../../../../extlib/");
    use CGI qw(-unique_headers);
    use CGI::Session; #qw(-ip_match);
    use HTML::Template;
    use Error qw(:try);
    use Fcntl;

    use lib("../../../../lib/");
    use Affelio;
    use Affelio::misc::CGIError;
    use Affelio::misc::Debug qw( debug_print);
    use Affelio::misc::Time;
    use Affelio::misc::NetMisc;
    use Affelio::misc::WebInput;
    use Affelio::Managing::NewsAggregator;
    use Affelio::exception::CommunicationException; 
    use Affelio::exception::SystemException;

    ######################################################################
    #Constructor
    ######################################################################
    sub new{
	my $class = shift;
	my %param = @_;

	debug_print("StandAlone::Admin::new: start.");

	my $cfg_dir = $param{ConfigDir};
	my $cgi = new CGI;
	my $wi = new Affelio::misc::WebInput();
	my $af;

	###########################
	#Load Affelio
	###########################
	$af = new Affelio(ConfigDir => $cfg_dir,
			  CGI => $cgi);
	debug_print("StandAlone::Admin::new: AF loaded.");

	my $self = {cfg_dir => $cfg_dir,
		    cgi => $cgi,
		    af => $af,
		    wi => $wi};
	bless $self, $class;

	$a = new Affelio::Managing::NewsAggregator($af);
	$a->get_one();

	debug_print("StandAlone::Admin::new: end.");
	return $self;
    }

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

	my $self = shift;
	my $af = $self->{af};
	my $cgi = $self->{cgi};
	my $cfg_path = $self->{cfg_path};
	my $wi = $self->{wi};

	my $HTTP_forward_flag = 0;
	my $forward_URL = "";

	my %handlers = ("config_affelio", "ConfigAffelio",
			"config_apps", "ConfigApps",
			"accesslog", "AccessLog",
			"makefriend", "MakeAffelioLink",
			"make_affeliolink", "MakeAffelioLink",
			"messages", "Messaging",
			"edit_skins", "EditSkins",
			"edit_templates", "EditTemplates",
			"friendsgraph", "FriendsGraph",
			"editprofile", "EditProfile",
			"group_member_table", "GroupMemberTable",
			"manage_friends", "ManageFriend",
			"manage_groups", "ManageGroup",
			"access_control", "AccessControl",
			"access_control_apps", "ManageApplication",
			"send_invitation", "SendInvitation",
			"top", "Top");

	###########################
	#Check session
	###########################
	check_session($self,$cgi);
	
	###########################
	#Going to the owner mode
	###########################
	$af->set_owner_mode();

	##############################################################
	#prep vars
	##############################################################
	my %output_data = ("tmpl_path", "$af->{site__tmpl_web_path}/owner_side/",
			   "style_path", $af->{site__web_root} . "/skins/" . $af->{userpref__skin},
			   "site__web_root", "$af->{site__user_afid}",
			   "site__locale", $af->{site__locale},
			   "my_nickname", $af->{user__nickname});

	use Affelio::App::Standalone::Admin::Messaging;
	$output_data{new_messages}
	=Affelio::App::Standalone::Admin::Messaging::get_new($af);


	##############################################################
	#Model invocation
	##############################################################
	my $admin_mode = $wi->PTN_mode($cgi->url_param("mode"));
	if ($admin_mode eq "") {$admin_mode="top";}
	debug_print("StandAlone::Admin::run: mode=$admin_mode");

	my $classname = "Affelio::App::Standalone::Admin::" . $handlers{$admin_mode};
	debug_print("StandAlone::Admin::run: handler= $classname");
	eval "use $classname";
	if($@){
	    throw Affelio::exception::SystemException("Could not load handler [$admin_mode]");
	}
	debug_print("StandAlone::Admin::run: handler function loaded.");

	my $ret="";
	try{
	    debug_print("StandAlone::Admin::run: handler function..... ");
	    handler($cgi, $af, \%output_data);
	    debug_print("StandAlone::Admin::run: handler function done.");
	}catch Error with{
	    my $e = shift;
	    $output_data{"err_msg"} .= $e->stacktrace;
	};

	##############################################################
	#Output View
	##############################################################
	if( $HTTP_forward_flag == 1 ){
	    print "Location: $forward_URL", "\n\n";
	    
	}else{
	    my $tmpl = new HTML::Template(filename => $output_data{tmpl_file},
					  die_on_bad_params => 0);
	    $tmpl->param(%output_data);
	    
	    print "Content-type: text/html; charset=UTF-8\n";
	    print "Pragma: no-cache", "\n\n";
	    print get_HTML_header($self);
	    print $af->translate_templateL10N($tmpl->output);
	    print get_HTML_footer($self);
	}
	
    }

    ######################################################################
    #Check session w/ cookie
    ######################################################################
    sub check_session{
	my $self = shift;
	my $cgi = shift;
	my $af = $self->{af};
	
	my $TMPL_FILE="";
	
	my $session = $af->getSM->get_session();

	if( (!$session) || ($session->param("type") ne "self")  ){
	    # Is the session alive?
	    # Is the user the admin of this site?
	    # if not....
	    debug_print("StandAlone::Admin::check_session: login is needed.");
	    
	    print "Content-type: text/html; charset=UTF-8\n";
	    print "Pragma: no-cache", "\n\n";
	    print get_HTML_header($self);
	    
	    $TMPL_FILE = "$af->{site__tmpl_dir}/owner_side/login.tmpl";
	    my $tmpl = new HTML::Template(filename => $TMPL_FILE,
					  die_on_bad_params => 0);
	    $tmpl->param(reason_msg => "You haven't been authenticated.");
	    $tmpl->param("tmpl_path" => "$af->{site__tmpl_web_path}/owner_side/");
	    $tmpl->param("style_path" => $af->{site__web_root} . "/skins/" . $af->{userpref__skin});
	    $tmpl->param("forward_URL" => $cgi->self_url);
	    
	    print $af->translate_templateL10N($tmpl->output);
	    print get_HTML_footer($self);
	    exit(1);
	}
	
	debug_print("StandAlone::Admin::check_session: Session as the admin is OK.");
    }

    ######################################################################
    #Get_HTML_header
    ######################################################################
    sub get_HTML_header{
        my $self = shift;
	my $af = $self->{af};
        my $app__page_title = shift;

        #Set template file name
        my $TMPL_FILE = "$af->{site__tmpldyn_dir}/_header.tmpl";
        #Set data for template
        my %output_data = ();
        $output_data{'app__css_path'} = "$af->{site__tmpl_web_path}/owner_side";
        $output_data{'app__page_title'} = "Affelio Owner's page";
        $output_data{"site__skin_dir"} = $af->{site__web_root} . "/skins/" . $af->{userpref__skin};
        $output_data{'site__web_root'} = $af->{site__web_root};
        $output_data{'site__locale'} = $af->{site__locale};

        $af->get_module_list(\%output_data, $af->{site__user_afid},"self");
        $af->get_guest_owner_list(\%output_data);

        #Initiate Template
        my $tmpl = new HTML::Template( filename => $TMPL_FILE,
                                       die_on_bad_params => 0);
        $tmpl->param(%output_data);

        my $final_out = $af->translate_templateL10N($tmpl->output)
            . '<div class="afMain">' . "\n";

        return($final_out);

    }
    
    ######################################################################
    #get_HTML_footer
    ######################################################################
    sub get_HTML_footer{
        my $self = shift;
	my $af = $self->{af};
        #Set template file name
        my $TMPL_FILE = "$af->{site__tmpldyn_dir}/_footer.tmpl";
        my $tmpl = new HTML::Template(filename => $TMPL_FILE,
				      die_on_bad_params => 0);
        my $final_out = "</div><!--afPubMain-->"
            . $af->translate_templateL10N($tmpl->output);

        return($final_out);
    }

}
1;

    
