# 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: Affelio.pm,v 1.40 2006/03/07 14:39:08 slash5234 Exp $

package Affelio;
{
    use strict;
    use lib("../extlib");
    use DBI;
    use Error qw(:try);

    use lib("../lib");
    use Affelio::SNS::FriendManager;
    use Affelio::misc::Debug;
    use Affelio::misc::L10N;
    use Affelio::misc::WebInput;
    use Affelio::misc::Util;
    use Affelio::exception::TaintedInputException;
    use Affelio::exception::DBException;
    use Affelio::exception::SystemException;

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

	debug_print("Affelio::new: start.");

	###################################
	#Config dir
	###################################
	my $cfg_dir = $param{ConfigDir};
	my $cfg_path = $param{ConfigDir} . "/affelio.cfg";
	debug_print("Affelio::new: cfg_path= [$cfg_path]");
	#cfg_path               Configuration file's path
	#cfg_dir                Configuration file's directory

	my $top_dir = $param{ConfigDir} . "/../";

	###################################
	#Mode
	###################################
	my $mode = $param{Mode};
	if(!defined($mode)){
	    $mode ="";
	}
	#mode= "init"                Setup mode
	#mode= ""                    Normal execution 

	###################################
	#Guest/Owner current status
	###################################
	# How can we know if we are in owner mode? or guest mode?
	my $guest_owner_switch = $param{GuestOwnerSwitch};
	#guest_owner_switch = ""          guest
	#guest_owner_switch = "owner"     owner

	###################################
	#CGI
	###################################
	my $cgi = $param{CGI};

	###################################
	#Caller
	###################################
	#caller= ""            ... if AffelioCore called me.
	#caller= "install_name"... if application "install_name" called me.
	my $caller = "";
	$caller = $param{Caller};
	if($caller){
	    if($caller =~ /([\w]+)/){
		$caller =$1;
	    }else{
		throw Affelio::exception::TaintedInputException("Affelio caller");
	    }
	}else{
	    $caller="";
	}
	debug_print("Affelio::new: caller= [$caller] ");

	###################################
	#Managers
	###################################
	my $lh = "";
	my $db = "";
	my $pm = "";
	my $fm = "";
	my $gm = "";
	my $perm = "";
	my $am = "";
	my $alm = "";
	my $sm = "";
	my $nghr_news = "";
	my $my_news="";
	my $farm_con = "";

	###################################
	#Blessing
	###################################
	my $self = {cfg_path => $cfg_path,
		    cfg_dir => $cfg_dir,
		    top_dir => $top_dir,
		    lh => $lh,
		    cgi => $cgi,
		    db => $db,
		    pm => $pm,
		    fm => $fm,
		    gm => $gm,
		    perm => $perm,
		    am => $am,
		    alm => $alm,
		    sm => $sm,
		    nghr_news => $nghr_news,
		    my_news => $my_news, 
		    mode => $mode,
		    guest_owner_switch => $guest_owner_switch,
		    caller => $caller,
		    farm_con => $farm_con
		    };

	bless $self, $class;

	###################################
	#Initialization
	#   Read site config. and user preferences.
	$self->read_site_config();
	$self->read_user_prefs();

	###################################
	#Load locale 
	$self->load_Locale();

	my $dummy=$self->getPM();

	###########################
	#Configure "Top page"
	###########################
	if($self->{mode} ne "init"){
	    if(($self->{userpref__toppage_app_installname} ne "")
	       && ($self->{userpref__toppage_app_installname} ne "Affelio")){

		#Here, top page is not Affelio module but one of apps. 
                #We now need to load Application Manager
		$self->load_ApplicationManager();
		$self->{userpref__toppage_app_path}= "/apps/" . $self->{userpref__toppage_app_installname} . "/" . $self->{am}->{apps}->{"$self->{userpref__toppage_app_installname}"}->{guest_index};
		
	    }else{

		#Here, top page is Affelio module.
		$self->{userpref__toppage_app_installname} = "Affelio";
		$self->{userpref__toppage_app_path}="index.cgi?mode=index";
	    }
	}

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



    ######################################################################
    #Destructor
    ######################################################################
    sub DESTROY{
	my $self = shift;
	if(defined($self->{db})){
	    try{
		$self->{db}->disconnect;
	    }catch Error with{
	    };
	}
    }

    ######################################################################
    #set_owner_mode:   Flag this Affelio as "owner" mode.
    ######################################################################
    sub set_owner_mode{
	my $self = shift;
	debug_print("Affelio::set_owner_mode  OK");
	$self->{guest_owner_switch} = "owner";
    }


    ######################################################################
    #getDB
    ######################################################################
    sub getDB{
	my $self=shift;

	if(! ($self->{db}) ){
	    debug_print("Affelio::getDB: db is empty... let's open.");
	    $self->openDB();
	    debug_print("Affelio::getDB: db is empty... opened.");
	}
	debug_print("Affelio::getDB: db=[$self->{db}]");
	return($self->{db});
    }

    ######################################################################
    #openDB
    ######################################################################
    sub openDB{
	my $self = shift;

	undef($self->{db});

	#Load username and password
	require Config::Tiny;
	my $DBConfig = Config::Tiny->new();
	$DBConfig = Config::Tiny->read("$self->{site__user_dir}/db.cfg");
	my $db_type = $DBConfig->{db}->{type};
	$self->{site__db_type} = $db_type;
	my $db_dbname   = $DBConfig->{db}->{dbname};
	my $db_username = $DBConfig->{db}->{username};
	my $db_password = $DBConfig->{db}->{password};
	my $db_hostname = $DBConfig->{db}->{hostname};
	my $db_port = $DBConfig->{db}->{port};

	debug_print("Affelio::openDB: start.");
	debug_print("Affelio::openDB: db_type = $db_type");
	debug_print("Affelio::openDB: db_dbname = $db_dbname");
	debug_print("Affelio::openDB: db_username = $db_username");
	debug_print("Affelio::openDB: db_password = $db_password");
	debug_print("Affelio::openDB: db_hostname = $db_hostname");
	debug_print("Affelio::openDB: db_port = $db_port");

	#################################################
	#MySQL
	if($db_type eq "mysql"){
	    
	    my $dsn = "DBI:mysql:$db_dbname:$db_hostname:$db_port";
	    eval{
		$self->{db} = DBI->connect($dsn, $db_username, $db_password) or die("Cannot connect to MySQL: " . $DBI::errstr);
	    };
	    if($@){
		throw Affelio::exception::DBException("MySQL open error");
	    }

	#################################################
	#SQLite
	}elsif ($db_type eq "sqlite"){
	    my $dbfile = "$self->{site__user_dir}/DB.sqlite";
	    $dbfile =~ s|//|/|g;

	    eval{
		$self->{db} = DBI->connect("dbi:SQLite:dbname=$dbfile", "", "") or die("Cannot connect to SQLite: " . $DBI::errstr);
	    };
	    if($@){
		throw Affelio::exception::DBException("SQLite open error");
	    }
	}else{
	    throw Affelio::exception::SystemException("DB type not specified");
	}

	#################################################
	#Error?
	if(!defined($self->{db})){
	    throw Affelio::exception::DBException("DB Handle not defined after open. very weird.");
	}
	eval{
	    $self->{db}->{RaiseError} = 1;
	};
	if($@){
	    throw Affelio::exception::DBException("DB Error Setting");
	}

	debug_print("Affelio::openDB: end.");
    }

    ######################################################################
    #openAppDB
    ######################################################################
    sub openAppDB{
	my $self = shift;
	my $app_install_name = shift;

	#Load username and password
	require Config::Tiny;
	my $DBConfig = Config::Tiny->new();
	$DBConfig = Config::Tiny->read("$self->{site__user_dir}/db.cfg");
	my $rootproperty = $DBConfig->{_}->{rootproperty};
	my $db_type = $DBConfig->{appdb}->{type};
	my $db_dbname   = $DBConfig->{appdb}->{dbname};
	my $db_username = $DBConfig->{appdb}->{username};
	my $db_password = $DBConfig->{appdb}->{password};
	my $db_hostname = $DBConfig->{appdb}->{hostname};
	my $db_port = $DBConfig->{appdb}->{port};

	my $ret="";

	###MySQL
	if($db_type eq "mysql"){
	    my $dsn = "DBI:mysql:$db_dbname:$db_hostname:$db_port";

	    eval{
		$ret = DBI->connect($dsn, $db_username, $db_password);
	    };
	    if($@){
		throw Affelio::exception::DBException("MySQL open error");
	    }
	}
	###SQLite
	if($db_type eq "sqlite"){
	    eval{
		$ret = DBI->connect("dbi:SQLite:dbname=$self->{site__user_dir}/appdata/$app_install_name/DB.sqlite", "", "");
	    };
	    if($@){
		throw Affelio::exception::DBException("SQLite open error");
	    }
	}

	eval{
	    $ret->{RaiseError} = 1;
	};
	if($@){
	    throw Affelio::exception::DBException("DB Error Setting");
	}

	$ret->{RaiseError} = 1;

	return($ret);
    }

    ######################################################################
    #load_Locale
    ######################################################################
    sub load_Locale{
	my $self = shift;
	$self->{lh} = Affelio::misc::L10N->get_handle(($self->{site__locale},"en_us"));
    }

    ######################################################################
    #getPM
    ######################################################################
    sub getPM{
	my $self=shift;

	if(!($self->{pm}) ){
	    $self->load_ProfileManager();
	}
	return($self->{pm});
    }

    ######################################################################
    #load_ProfileManager
    ######################################################################
    sub load_ProfileManager{
	require Affelio::Managing::ProfileManager;

	my $self = shift;
	try{
	    $self->{pm} = new Affelio::Managing::ProfileManager($self,
								$self->{mode});
	}
	catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load profilemanager: $ex");
	    }
	};
    }

    ######################################################################
    #getSM
    ######################################################################
    sub getSM{
	my $self=shift;

	if(!($self->{sm}) ){
	    $self->load_SessionManager();
	}
	return($self->{sm});
    }

    ######################################################################
    #load_SessionManager
    ######################################################################
    sub load_SessionManager{
	my $self=shift;

	debug_print("Affelio::loadSM: start.");

	if($self->{site__farm_mode} eq "AFE2"){
	    debug_print("Affelio::loadSM: getting SM from AFE2...");

	    $self->{sm} = $self->{farm_con}->getSM();
	    if(!$self->{sm}){
		throw Affelio::exception::SystemException("affelio.cfg: cannot obtain SessionManager from FarmConnector.");
	    }

	}else{
	    debug_print("Affelio::loadSM: loading normal SM....");
	    require Affelio::Managing::SessionManager;
	    $self->{sm} = new Affelio::Managing::SessionManager;
	    $self->{sm}->init($self);
	}
	debug_print("Affelio::loadSM: end.");
    }

    ######################################################################
    #getNghrNews
    ######################################################################
    sub getNghrNews{
	my $self=shift;

	if(! ($self->{nghr_news}) ){
	    $self->load_NewsAggregator();
	}
	return($self->{nghr_news});
    }

    ######################################################################
    #load_NewsAggregator
    ######################################################################
    sub load_NewsAggregator{
	require Affelio::Managing::NewsAggregator;

	my $self = shift;
	try{
	    $self->{nghr_news} = new Affelio::Managing::NewsAggregator($self);
	}catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load NewsAggregator: $ex");
	    }
	};
    }

    ######################################################################
    #getMyNews
    ######################################################################
    sub getMyNews{
	my $self=shift;

	if(! ($self->{my_news}) ){
	    $self->load_MyNewsManager();
	}
	return($self->{my_news});
    }

    ######################################################################
    #load_MyNewsManager
    ######################################################################
    sub load_MyNewsManager{
	require Affelio::Managing::MyNewsManager;

	my $self = shift;
	try{
	    $self->{my_news} = new Affelio::Managing::MyNewsManager($self);
	}catch Error with {
	    my $ex = shift;
	    throw Affelio::exception::SystemException("Cannot load MyNewsManager: $ex");
	};
    }

    ######################################################################
    #getFM
    ######################################################################
    sub getFM{
	my $self=shift;

	if(! ($self->{fm}) ){
	    $self->load_FriendManager();
	}
	return($self->{fm});
    }

    ######################################################################
    #load_FriendManager
    ######################################################################
    sub load_FriendManager{
	require Affelio::SNS::FriendManager;

	my $self = shift;
	try{
	    $self->{fm} = new Affelio::SNS::FriendManager($self);
	}catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load FriendManager: $ex");
	    }
	};
    }

    ######################################################################
    #getGM
    ######################################################################
    sub getGM{
	my $self=shift;

	if(! ($self->{gm}) ){
	    $self->load_GroupManager();
	}
	return($self->{gm});
    }

    ######################################################################
    #load_GroupManager
    ######################################################################
    sub load_GroupManager{
	require Affelio::Managing::GroupManager;

	my $self = shift;
	try{
	    $self->{gm} = new Affelio::Managing::GroupManager($self);
	}
	catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load GroupManager: $ex");
	    }
	};

    }

    ######################################################################
    #getPERM
    ######################################################################
    sub getPERM{
	my $self=shift;

	if(! ($self->{perm}) ){
	    $self->load_PermissionManager();
	}
	return($self->{perm});
    }

    ######################################################################
    #load_PermissionManager
    ######################################################################
    sub load_PermissionManager{
	require Affelio::Managing::PermissionManager;

	my $self = shift;
	try{
	    $self->{perm} = new Affelio::Managing::PermissionManager($self);
	}
	catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load PermissionManager: $ex");
	    }
	};
    }

    ######################################################################
    #getMESGM
    ######################################################################
    sub getMESGM{
	my $self=shift;

	if(! ($self->{mesgm}) ){
	    $self->load_MessageManager();
	}
	return($self->{mesgm});
    }

    ######################################################################
    #load_MessageManager
    ######################################################################
    sub load_MessageManager{
	require Affelio::Managing::MessageManager;

	my $self = shift;
	try{
	    $self->{mesgm} = new Affelio::Managing::MessageManager($self);
	}
	catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load MessageManager: $ex");
	    }
	};

    }

    ######################################################################
    #getALM
    ######################################################################
    sub getALM{
	my $self=shift;

	if(! ($self->{alm}) ){
	    $self->load_AccessLogManager();
	}
	return($self->{alm});
    }

    ######################################################################
    #load_AccessLogManager
    ######################################################################
    sub load_AccessLogManager{
	require Affelio::Managing::AccessLogManager;

	my $self = shift;
	try{
	    $self->{alm} = new Affelio::Managing::AccessLogManager($self);
	}
	catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load AccessLogManager: $ex");
	    }
	};

    }

    ######################################################################
    #getAM
    ######################################################################
    sub getAM{
	my $self=shift;

	if(! ($self->{am}) ){
	    $self->load_ApplicationManager();
	}
	return($self->{am});
    }

    ######################################################################
    #load_ApplicationManager
    ######################################################################
    sub load_ApplicationManager{
	require Affelio::Managing::ApplicationManager;

	my $self = shift;
	try{
	    ###########################
	    #Start ApplicationManager 
	    ###########################
	    $self->{am} = new Affelio::Managing::ApplicationManager($self);

	}catch Error with {
	    my $ex = shift;
	    if($self->{mode} ne "init"){
		throw Affelio::exception::SystemException("Cannot load ApplicationManager: $ex");
	    }
	};

    }


    ######################################################################
    #get_farm_connecter{
    ######################################################################
    sub get_farm_connecter{
	my $self = shift;
	if( !($self->{farm_con}) ){
	    require Config::Tiny;
	    my $Config = Config::Tiny->new();

	    $Config = Config::Tiny->read($self->{cfg_path});
	    if($@ || !$Config){
		throw Affelio::exception::SystemException("affelio.cfg not found");
	    }

	    $self->{farm__connecter_path} = $Config->{affelio_farm}->{farm_connecter};
	    if(($self->{farm__connecter_path} eq "" )
	       || !($self->{farm__connecter_path}) ){
		return("");
	    }
	    debug_print("Affelio::get_farm_con: [$self->{farm__connecter_path}]");

	    my ($con_type, $con_arg) = split(':', $self->{farm__connecter_path});
	    my $con_class = "Affelio::Backplane::FarmConnecter::" . $con_type;
	    debug_print("Affelio::get_farm_con: [$con_class]");
	    debug_print("Affelio::get_farm_con: [$con_arg]");

	    eval "use $con_class";
	    if($@){
		debug_print("Affelio::get_farm_con: con=[$self->{farm_con}]1");
	    }
	    
	    $self->{farm_con} = $con_class->new(path => $con_arg);
	    if($@){
		debug_print("$@");
		throw Affelio::exception::SystemException("Could not instantiate [$con_class].");
	    }
	    debug_print("Affelio::get_farm_con: con=[$self->{farm_con}]");

	}
	   
	return($self->{farm_con});
    }

    ######################################################################
    #read_site_config
    #    read Affelio.cfg / login.cfg file
    ######################################################################
    sub read_site_config{
	my $self = shift;
	debug_print("Affelio::read_site_config: start.");

	my $wi = new Affelio::misc::WebInput();
	require Config::Tiny;
	my $Config = Config::Tiny->new();

	#################################################################
	#affelio.cfg
	#################################################################
	$Config = Config::Tiny->read($self->{cfg_path});
	if($@ || !$Config){
	    throw Affelio::exception::SystemException("affelio.cfg not found");
	}

	##############################################
	#[site] / Farm mode
	##############################################
	#farm_mode
	if($ENV{FARM_MODE}){
	    $self->{site__farm_mode} = $ENV{FARM_MODE};
	    $self->{farm__connecter_path} = $ENV{FARM_CONNECTOR};
	}else{
	    $self->{site__farm_mode} = $Config->{site_config}->{farm_mode};
	    $self->{farm__connecter_path} = 
		$Config->{affelio_farm}->{farm_connecter};
	}
	debug_print("Affelio::read_site_config: farm_mode=[$self->{site__farm_mode}]");
	debug_print("Affelio::read_site_config: farm_con=[$self->{site__farm_connector}]");

	#Detect AFE (not 2)
	if(($self->{site__farm_mode} eq "")
	   && ($self->{farm__connecter_path} ne "")){
	    $self->{site__farm_mode} = "AFE";
	}

	#platform
	$self->{site__platform} = $Config->{site_config}->{platform};
	debug_print("Affelio::read_site_config: platform=[$self->{site__platform}]");

	##############################################
	#[site]
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){
	    #site_fs_root
	    $self->{site__fs_root} = "$ENV{FARM_FS_TOP}/affelio";
	    #site_web_root
	    $self->{site__web_root} =  "$ENV{FARM_WEB_TOP}/affelio";
	}else{
	    #site_fs_root
	    $self->{site__fs_root} = $Config->{site_config}->{fs_root};
	    #site_web_root
	    $self->{site__web_root} = $Config->{site_config}->{web_root};
	}
	if($self->{site__fs_root} =~ /(.*)\/$/){
	    $self->{site__fs_root} = $1;
	}
	if($self->{site__web_root} =~ /(.*)\/$/){
	    $self->{site__web_root} = $1;
	}

	#locale
	#Oh well, this config parameter has been "char_set" for a while..
	#For now, locale = char_set 
	$self->{site__locale} = $Config->{site_config}->{char_set};
	if($self->{site__locale} eq ""){
	    $self->{site__locale} = "ja";
	}

	#template
	$self->{site__template} = $Config->{site_config}->{template};
	if($self->{site__template} eq ""){
	    $self->{site__template} = "default";
	}


	##############################################
	#AFE
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){

	    ####################
	    #Load farm connecter
	    ####################
	    my $clsname = "";
	    $clsname = $self->{farm__connecter_path};
	    debug_print("Affelio::read_site_config: AFE_con=[$clsname]");

	    eval "require $clsname; import $clsname;";
	    if($@){	    throw Affelio::exception::SystemException("Could not load [$clsname]");	}
	    debug_print("Affelio::read_site_config: AFE_con [$clsname] loaded.");
	    $self->{farm_con} = eval "new $clsname;";
	    $self->{farm_con}->init($self);

	    ####################
	    #farm__fs_data_root
	    ####################
	    $self->{farm__fs_datadir} = $self->{farm_con}->get_fs_datadir();
	    if(!$self->{farm__fs_datadir}){
		throw Affelio::exception::SystemException("affelio.cfg: cannot obtain fs_data_root from FarmConnector.");
	    }

	    ####################
	    #farm__user_afid
	    ####################
	    $self->{farm__user_afid} = $self->{farm_con}->get_user_afid();
	    if(!$self->{farm__user_afid}){
		throw Affelio::exception::SystemException("affelio.cfg: cannot obtain fs_data_root from FarmConnector.");
	    }

	    ####################
	    #farm__cur_user
	    ####################
	    $self->{farm__cur_user} = $ENV{'REDIRECT_AF_USERNAME'};
	    if(!$self->{farm__cur_user}){
		throw Affelio::exception::SystemException("AFE2/farm_cur_user not set.");
	    }

	    ####################
	    #farm__fs_farmroot
	    ####################
	    $self->{farm__fs_farmroot} = $ENV{'FARM_FS_TOP'} . "/" .  $ENV{'REDIRECT_AF_EXEC_TYPE'} . "Farm";

	    ####################
	    #farm__web_farmroot
	    ####################
	    $self->{farm__web_farmroot} = $ENV{'FARM_WEB_TOP'} . "/" .  $ENV{'REDIRECT_AF_EXEC_TYPE'} . "Farm";


	}
	#if(AFE2) 

	##############################################
	#exec_type
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){
	    $self->{site__exec_type} = $ENV{'REDIRECT_AF_EXEC_TYPE'};
	}else{
	    $self->{site__exec_type} = "";
	}
	debug_print("Affelio::read_site_config: site__exec_type = [$self->{site__exec_type}]");


	##############################################
	#site__user_afid
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){
	    $self->{site__user_afid} = $self->{farm__user_afid};
	}else{
	    $self->{site__user_afid} = $self->{site__web_root};
	}
	debug_print("Affelio::read_site_config: site__user_afid = [$self->{site__user_afid}]");

	##############################################
	#Determine the user's userdata directory
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){
	    $self->{site__user_dir} = 
		$self->{farm__fs_datadir} . "/userdata/";
	}else{
	    try{
		$self->{site__user_dir} = 
		    get_userdir("$self->{site__fs_root}/userdata");	    
	    }catch Error with{
		my $e = shift;
		throw $e;
	    };
	}
	debug_print("Affelio::read_site_config: site__user_dir = [$self->{site__user_dir}]");

	##############################################
	#Determine templates_dyn dir
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){
	    $self->{site__tmpldyn_dir} = 
		$self->{farm__fs_datadir} . "/templates_dyn/";
	}else{
	    $self->{site__tmpldyn_dir} =  "$self->{site__fs_root}/templates_dyn/";
	}
	debug_print("Affelio::read_site_config: site_tmpldyn_dir = [$self->{site__tmpldyn_dir}]");

	##############################################
	#Determine templates dir
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){
	    $self->{site__tmpl_dir} 
	    = $self->{farm__fs_farmroot} . "/templates/"
		. $self->{site__template};
	}else{
	    $self->{site__tmpl_dir} 
	    = $self->{site__fs_root} . "/templates/"
		. $self->{site__template};
	}
	debug_print("Affelio::read_site_config: site_tmpl_dir = [$self->{site__tmpl_dir}]");

	##############################################
	#Determine templates web path
	##############################################
	if($self->{site__farm_mode} eq "AFE2"){
	    $self->{site__tmpl_web_path} 
	    = $self->{farm__web_farmroot} . "/templates/"
		. $self->{site__template};
	}else{
	    $self->{site__tmpl_web_path} 
	    = $self->{site__web_root} . "/templates/"
		. $self->{site__template};
	}
	debug_print("Affelio::read_site_config: site_tmpl_web_path = [$self->{site__tmpl_web_path}]");


	##############################################
	#[command]
	##############################################
	$self->{cmd__sendmail} = $Config->{command}->{sendmail};
	
	#################################################################
	#login.cfg
	#################################################################

	##############################################
	#Load user's login username / password
	##############################################
	my $Config2 = Config::Tiny->new();
	$Config2 = Config::Tiny->read("$self->{site__user_dir}/login.cfg");
	if($@ || !$Config2){
	    throw Affelio::exception::SystemException("login.cfg not found");
	}

	$self->{site__username} = $wi->PTN_nickname($Config2->{auth}->{username});
	$self->{site__password} = $Config2->{auth}->{password};

	#Table name prefix
	if($self->{site__farm_mode} eq "AFE2"){
	    $self->{site__dbtbl_prefix} 
	    = "AF_" . $self->{site__exec_type} . "_" . $self->{site__username};
	}else{
	    $self->{site__dbtbl_prefix} = "AF" . "user";
	}
	
    }

    ######################################################################
    #write_user_prefs
    ######################################################################
    sub write_user_prefs{
	my $self = shift;
	debug_print("Affelio::write_user_prefs: start.");

	require Config::Tiny;
	my $Config = Config::Tiny->new();
	$Config = Config::Tiny->read("$self->{site__user_dir}/preference.cfg");
	if($@ || !$Config){
	    throw Affelio::exception::SystemException("preference.cfg not found");
	}

	my $rootproperty = $Config->{_}->{rootproperty};

	#Write preferences

	$Config->{messaging}->{emailflg} = 
	    $self->{userpref__mesging__emailflg};
	$Config->{preference}->{toppage_app_installname} = 
	    $self->{userpref__toppage_app_installname};
	$Config->{preference}->{emailack_friendship_recv} = 
	    $self->{userpref__emailack_fr_recv};
	$Config->{preference}->{preferred_hosting_service} =
	    $self->{userpref__preferred_hosting_service};
	$Config->{preference}->{skin}= $self->{userpref__skin};

	$Config->{preference}->{password_remoteop}= 
	    $self->{userpref__password_remoteop};

	$Config->write("$self->{site__user_dir}/preference.cfg");
	if($@ || !$Config){
	    throw Affelio::exception::SystemException("preference.cfg is not writable.");
	}

	debug_print("Affelio::write_user_prefs: end.");
    }

    ######################################################################
    #read_user_prefs
    ######################################################################
    sub read_user_prefs{
	my $self = shift;
	debug_print("Affelio::read_user_prefs: start.");
	
	my $wi = new Affelio::misc::WebInput;

	require Config::Tiny;
	my $Config = Config::Tiny->new();
	$Config = Config::Tiny->read("$self->{site__user_dir}/preference.cfg");
	if($@ || !$Config){
	    throw Affelio::exception::SystemException("Cannot open preference.cfg");
	}

	my $rootproperty = $Config->{_}->{rootproperty};
	
	#Read preferences
	$self->{userpref__toppage_app_installname} 
	= $wi->PTN_word($Config->{preference}->{toppage_app_installname});
	$self->{userpref__emailack_fr_recv} 
	= $wi->PTN_word($Config->{preference}->{emailack_friendship_recv});
	$self->{userpref__preferred_hosting_service}
	= $wi->PTN_URL($Config->{preference}->{preferred_hosting_service});
	$self->{userpref__skin}
	= $wi->PTN_word($Config->{preference}->{skin});

	$self->{userpref__password_remoteop} 
	= $Config->{preference}->{password_remoteop};

	$self->{userpref__mesging__emailflg}
	= $wi->PTN_word($Config->{messaging}->{emailflg});
	if($self->{userpref__mesging__emailflg} eq ""){
	    $self->{userpref__mesging__emailflg} = "yes";
	}

	debug_print("Affelio::read_user_prefs: end.");
    }
    
    ######################################################################
    #get_guest_owner_list
    ######################################################################
    sub get_guest_owner_list{
	my $self = shift;
	my $output_ref = shift;

	my @guest_owner_switch=();
	$output_ref->{'guest_owner_switch'} = \@guest_owner_switch;



	my $owner_mode_selected="";
	if($self->{guest_owner_switch} eq "owner"){
	    $owner_mode_selected="true";
	}else{
	    $owner_mode_selected="";
	}

	my $guest_mode_url="";
	my $owner_mode_url="";
	if($self->{caller}){ 
	    $guest_mode_url
		= $self->getAM->{apps}->{$self->{caller}}->{guest_index};
	    $owner_mode_url
		= $self->getAM->{apps}->{$self->{caller}}->{owner_index};
	}else{
	    $guest_mode_url= $self->{site__user_afid} . "/index.cgi?mode=index";
	    $owner_mode_url= $self->{site__user_afid} . "/admin.cgi";
	}

	if($owner_mode_selected){
	    push(@guest_owner_switch,
		 {'selected' => $owner_mode_selected,
		  'name' => "Owner",
		  'url' => $guest_mode_url,
		  'image_over' => "$self->{site__web_root}/icons/owner_over.jpg"
		  }
		 );

	}else{
	    push(@guest_owner_switch,
		 {'selected' => $owner_mode_selected,
		  'name' => "Owner",
		  'url' => $owner_mode_url,
		  'image_normal' => "$self->{site__web_root}/icons/owner_normal.jpg",
		  }
		 );
	}#else

    }#method


    ######################################################################
    #get_module_list
    ######################################################################
    sub get_module_list{
	my $self = shift;
	my $output_ref = shift;
	my $visitor_afid =shift;
	my $visitor_type =shift;

	my $selected ="";
	my @modules=();
	$output_ref->{'modules'} = \@modules;

	#########################
	#Affelio core 
	#########################
	if($self->{caller}){
	    #Affelio.pm is called by an application
	    $selected ="";
	}else{
	    $selected ="true";
	}

	my $dest_url;
	if($self->{guest_owner_switch} eq "owner"){
	    ####Owner
	    if($selected eq "true" ){
		$dest_url = $self->{site__user_afid} . "/index.cgi?mode=index";
	    }else{
		if($visitor_type eq "self"){
		    $dest_url = $self->{site__user_afid} . "/admin.cgi";
		}
	    }
	}else{
	    ####Guest
	    if($selected eq "true" ){
		if($visitor_type eq "self"){
		    $dest_url = $self->{site__user_afid} . "/admin.cgi";
		}
	    }else{
		$dest_url = $self->{site__user_afid} . "/index.cgi?mode=index";
	    }
	}

	push(@modules,
	     {'name' => "Affelio",
	      'image_normal' => "$self->{site__web_root}/icons/affelio_normal.jpg",
	      'image_over' => "$self->{site__web_root}/icons/affelio_over.jpg",
	      'url' => $dest_url,
	      'selected' => $selected}
	     );

	#########################
	#Applications
	#########################
	my $tmp_name;
	my $this_app_ref;
	while ( ($tmp_name, $this_app_ref) = each( %{$self->getAM->{apps}} ) ){
	    my %this_app = %$this_app_ref;

	    debug_print("Affelio::get_module_list: $this_app{'install_name'}");

	    my $perm_to_tab=0;
	    $perm_to_tab
		= $self->getAM->get_summed_app_perm($visitor_afid,
						   $visitor_type,
						   $this_app{'install_name'},
						   "DF_visibility");

	    if($perm_to_tab ==1 ){
		if($this_app{'install_name'} eq $self->{caller}){
		    $selected = "true";
		}else{
		    $selected = "";
		}

		my $dest_url = "$self->{site__user_afid}/apps/$this_app{'install_name'}/";
		if($self->{guest_owner_switch} eq "owner"){
		    #Owner
		    if($selected eq "true"){
			$dest_url .= $this_app{'guest_index'};
		    }else{
			if($visitor_type eq "self"){
			    $dest_url .= $this_app{'owner_index'};
			}
		    }
		}else{
		    #Guest
		    if( ($selected eq "true") && ($visitor_type eq "self")){
			$dest_url .= $this_app{'owner_index'};
		    }else{
			$dest_url .= $this_app{'guest_index'};
		    }
		}
		
		push(@modules,
		     {'selected' => $selected,
		      'name' => $this_app{'install_title'},
		      'url' => $dest_url,
		      'image_normal' => "$self->{site__user_afid}/apps/$this_app{'install_name'}/icons/normal.jpg",
		      'image_over' => "$self->{site__user_afid}/apps/$this_app{'install_name'}/icons/over.jpg"
		      }
		     );
	    }
	}#foreach

    }#method


    ######################################################################
    #translate_templateL10N
    ######################################################################
    sub translate_templateL10N{
	my $af=shift;
	my $mesg = shift;
	
	my $tag_body ="";
	my $text_value="";
	my $param_value="";
	
	while( $mesg =~ /<AF_M ([^>]+)>/ ){
	    $tag_body = $1;
	    
	    $tag_body =~ /text(\s*)=(\s*)["']([^"']*)["'](\s*)param(\s*)=(\s*)["']([^"']*)["']/;
	    $text_value=$3;
	    $param_value=$7;
	    if($text_value eq ""){
		$tag_body =~ /text(\s*)=(\s*)["']([^"']*)["']/;
		$text_value=$3;
	    }
	    
	    my $sbst = $af->{lh}->maketext($text_value, $param_value);
	    
	    debug_print("Affelio::translate tag_body = [$tag_body]\n");
	    debug_print("Affelio::translate \t text=[$text_value]\n");
	    debug_print("Affelio::translate \t param=[$param_value]\n");
	    debug_print("Affelio::translate \t sbst=[$sbst]\n");
	    
	    $mesg =~ s/\Q<AF_M $tag_body>\E/$sbst/g;
#	    debug_print("Affelio::loop end.");
	}

#	debug_print("Affelio::translate end.");
	return($mesg);
    }




    sub translate_templateL10N_old{
	my $af=shift;
	my $mesg = shift;
	
	my $tag_body ="";
	my $text_value="";
	my $param_value="";
	
	while( $mesg =~ /<AF_M ([^>]+)>/ ){
	    $tag_body = $1;
	    
	    $tag_body =~ /text(\s*)=(\s*)["']([^"']*)["'](\s*)param(\s*)=(\s*)["']([^"']*)["']/;
	    $text_value=$3;
	    $param_value=$7;
	    if($text_value eq ""){
		$tag_body =~ /text(\s*)=(\s*)["']([^"']*)["']/;
		$text_value=$3;
	    }
	    
	    my $sbst = $af->{lh}->maketext($text_value, $param_value);
	    
#	    debug_print("Affelio::translate tag_body = [$tag_body]\n");
#	    debug_print("Affelio::translate \t text=[$text_value]\n");
#	    debug_print("Affelio::translate \t param=[$param_value]\n");
#	    debug_print("Affelio::translate \t sbst=[$sbst]\n");
	    
	    $mesg =~ s/\Q<AF_M $tag_body>\E/$sbst/g;
#	    debug_print("Affelio::loop end.");
	}

#	debug_print("Affelio::translate end.");
	return($mesg);
    }
    
    
}#package
1;
##########################################################################

