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

package Affelio::App::Standalone::Admin::Messaging;
{
    use strict;

    use lib("../../../../../extlib/");
    use Error qw(:try);
    use MIME::Base64;
    use lib("../../../../../lib/");
    use Affelio;
    use Affelio::misc::CGIError;
    use Affelio::misc::Debug qw(debug_print);
    use Affelio::misc::Encoding qw(db_encode db_decode);
    use Affelio::misc::Time qw(timestamp2string get_timestamp);
    use Affelio::misc::WebInput;
    use Affelio::misc::MyCrypt;
    use Affelio::SNS::Handshaker_c;
    use Affelio::exception::CommunicationException;
    use Affelio::exception::DBException;
    use Affelio::exception::SystemException;

    use Exporter;
    @Affelio::App::Standalone::Admin::Messaging::ISA = "Exporter";
    @Affelio::App::Standalone::Admin::Messaging::EXPORT = qw (show_message_list show_message mark_as_read get_new compose send_message handler);


    #######################################################################
    #handler
    #######################################################################
    sub handler{
	my $cgi = shift;
	my $af = shift;
	my $out_ref = shift;
	
	my $wi = new Affelio::misc::WebInput();
	
	my $sub_mode = $wi->PTN_mode($cgi->url_param("action"));

	if( $sub_mode eq "send_message" ){

	    try{
		send_message($af, $cgi);
		$out_ref->{ret_msg}
		.= '<AF_M text="You message has been sent successfuly.">';
	    }catch Affelio::exception::CommunicationException with{
		my $e = shift;
		$out_ref->{err_msg} 
		.= '<AF_M text="Could not send message."><BR>' . $e;
	    };

	    $out_ref->{tmpl_file}
	    = "$af->{site__tmpl_dir}/owner_side/admin_showmessage_list.tmpl";

	    show_message_list($af, $out_ref);
	    
	}elsif( $sub_mode eq "compose" ){
	    
	    $out_ref->{tmpl_file} = "$af->{site__tmpl_dir}/owner_side/admin_composemessage.tmpl";

	    compose($af, $cgi, $out_ref);

	}elsif( $sub_mode eq "show" ){
	    $out_ref->{tmpl_file} = "$af->{site__tmpl_dir}/owner_side/admin_showmessage.tmpl";

	    mark_as_read($af, $cgi->url_param("mid"));
	    show_message($af, $cgi->url_param("mid"), $out_ref);

	}else{
	    $out_ref->{tmpl_file} = "$af->{site__tmpl_dir}/owner_side/admin_showmessage_list.tmpl";
	
	    show_message_list($af, $out_ref);
	}

    }



    #######################################################################
    #send_message
    #######################################################################    
    sub send_message{
	my $af = shift;
	my $cgi = shift;

	debug_print("StandAlone::Mesg::send: start.");

	my $msg_to = $cgi->param("msg_to");
	my $msg_title = $cgi->param("msg_title");
	my $msg_body = $cgi->param("msg_body");

	debug_print("StandAlone::Mesg::send: $msg_to $msg_title $msg_body");

	if($msg_to =~ /(.*)\/$/){
	    $msg_to = $1;
	}

	my $passAB = "";
	try{
	    $passAB = $af->getFM->get_attribute_by_afid($msg_to, "password");
	}catch Affelio::exception::DBException with{
	    my $E = shift;
	    throw Affelio::exception::SystemException($E);
	};
	if(!defined($passAB) || $passAB eq ""){
	    #Exception!
	    exit(1);
	}
	debug_print("StandAlone::Mesg::send: passAB=[$passAB]");

	my $ret="";
	try{
	    $ret = post_Message(dest_uri =>  $msg_to,
				src => $af->{site__user_afid},
				password => $passAB,
				msg_from => $af->{site__user_afid},
				msg_from_nickname => $af->{user__nickname},
				msg_to => $msg_to,
				msg_timestamp => get_timestamp(),
				msg_title => $msg_title,
				msg_body => $msg_body);
	}catch Affelio::exception::NetworkException with{
	    my $E = shift;
	    throw Affelio::exception::CommunicationException($E);

	}catch Affelio::exception::InvalidInputException with{
	    my $E = shift;
	    error($cgi, "<PRE>Exception: " . $E .  "</PRE>");
	};
    }


    #######################################################################
    #compose
    #######################################################################    
    sub compose{
	my $af = shift;
	my $cgi = shift;
	my $output_ref = shift;
    	my $wi = new Affelio::misc::WebInput;

	my $mode="";

	my $to_url;
	my $title;
	my $reply_to;
	my $reply_title;
	my $reply_body;

	$to_url = $cgi->url_param("to_url");
	$title = url_decode($cgi->url_param("title"));

	$reply_to = $cgi->param("reply_to");
	$reply_title = $cgi->param("reply_title");
	$reply_body = $cgi->param("reply_body");
	if($to_url ne ""){
	    $mode="GET__specified_dest_url";
	}elsif($reply_to ne ""){
	    $mode="POST__reply";
	}

	debug_print("StandAlone::Messaging::compose: start.");
	debug_print("StandAlone::Messaging::compose: Reply-To: [$reply_to]");
	debug_print("StandAlone::Messaging::compose: To_URL: [$to_url]");

	############################
	#To:
	############################
	my @friends_list=();
	my $result = $af->getFM->get_all_friend_list(sort => "nickname");

	#Default
	if($mode eq ""){
	    push(@friends_list, {nickname => "",
				 afid     => "",
				 selected => "selected"});
	}

	while( my @row = $result->fetchrow_array ){

	    if($row[1] !~ /\/$/){
		$row[1] .= "/";
	    }
	    if($reply_to !~ /\/$/){
		$reply_to .= "/";
	    }
	    if($to_url !~ /\/$/){
		$to_url .= "/";
	    }

	    my $selected = "";
	    if(($mode eq "POST__reply") && ($row[1] eq $reply_to)){
		$selected ="selected";
	    }elsif(($mode eq "GET__specified_dest_url") && ($row[1] eq $to_url)){
		$selected ="selected";
	    } 
	    my $t= sprintf("%-20s %s",$row[2],$row[1]);
	    $t=~ s/\s/&nbsp;/g;

	    push(@friends_list, {nickname => $t,
				 afid     => $row[1],
				 selected => $selected});
	}
	$output_ref->{"friends"} = \@friends_list;


	############################
	#Title:
	############################
	if($reply_title ne ""){
	    $output_ref->{"msg_title"} = $reply_title;
	}else{
	    $output_ref->{"msg_title"} = $title;
	}

	############################
	#Body:
	############################
	$output_ref->{"msg_body"} = $reply_body;


	debug_print("StandAlone::Messaging::compose: end.");
    }

    #######################################################################
    #mark_as_read
    #######################################################################    
    sub mark_as_read{
	my $wi = new Affelio::misc::WebInput;

	my $af = shift;
	my $mid = shift;
	$mid = $wi->PTN_num($mid);

	debug_print("StandAlone::marK_as_read: start");

	my $ret= $af->getMESGM->mark_as_read($mid);

	debug_print("StandAlone::marK_as_read: end");
    }

    #######################################################################
    #get_new
    #######################################################################    
    sub get_new{
	my $af = shift;
	debug_print("StandAlone::get_new: start");

	my $ret= $af->getMESGM->get_unread_message_num();

	debug_print("StandAlone::get_new: end");
	return($ret);
    }


    #######################################################################
    #show_message
    #######################################################################    
    sub show_message{
	my $wi = new Affelio::misc::WebInput;

	my $af = shift;
	my $mid = shift;
	$mid = $wi->PTN_num($mid);
	my $output_ref = shift;

	debug_print("StandAlone::show_message: start.");

	my @message= $af->getMESGM->retrieve_message($mid);
	my ($msg_mid, $msg_timestamp, $msg_title, $msg_type,
	    $msg_from, $msg_body, $msg_readflag) = @message;

	if($msg_type=~ /Encode\-Base64/){
	    $msg_body = decode_base64($msg_body);
	}
	debug_print("StandAlone::show_message: $msg_from $msg_title $msg_type $msg_body");

	$msg_timestamp = timestamp2string($msg_timestamp);

	if($msg_type=~ /UserToUser/){
	    my $reply_title = "Re: $msg_title";
	    my $reply_body = $msg_body;
	    $reply_body =~ s/\r\n/\n/g;
	    $reply_body =~ s/\r/\n/g;
	    $reply_body =~ s/\n/\n>>/g;
	    $reply_body = "\r\n>>" . $reply_body;

	    my $reply_to="";
	    if($msg_from =~ /HREF="(.+)">/){
		$reply_to = $1;
	    }

	    my $reply_HTML = <<EOT;
<FORM METHOD="POST" ACTION="admin.cgi?mode=messages&action=compose">
<INPUT TYPE="hidden" NAME="reply_to" VALUE="$reply_to">
<INPUT TYPE="hidden" NAME="reply_title" VALUE="$reply_title">
<INPUT TYPE="hidden" NAME="reply_body" VALUE="$reply_body">
<INPUT TYPE="submit" VALUE="<AF_M text="Reply">">
</FORM>
EOT
            $$output_ref{"reply_HTML"} = $reply_HTML;

       }

	if($msg_type!~ /HTML/){
	    #URL ---> <A HREF="URL">URL</A>
	    $msg_body = $wi->translate_URL_to_HTML($msg_body);
	    #\n ----> <BR>
	    $msg_body =~ s/\r\n/\n/g;
	    $msg_body =~ s/\r/\n/g;
	    $msg_body =~ s/\n/<BR>/g;
	}

	###############
	#UserToUser (inter-Affelio massaging
	###############
	#XXX
	# This part is quite nasty. Since $msg_from is using format
	# like '<A HREF="url">nickname</A>' due to a weird DB problem,
	# We have to change the URL to the one through outgoing.cgi
	# by using ad-hoc regexes....
	if($msg_type =~ /UserToUser/){
	    $msg_from =~ /<A HREF="(.*)">(.+)<\/A>/;
	    debug_print("StandAlone::show_message_list: \t[$1]");
	    debug_print("StandAlone::show_message_list: \t[$2]");
	    
	    $msg_from = '<A HREF="' . $af->{site__user_afid} . '/outgoing.cgi?dest_url=' . $1 . '" target="_blank">' . $2 . '</A>';
	}
	###########


	$$output_ref{"msg_timestamp"} = $msg_timestamp;
	$$output_ref{"msg_title"} = $msg_title;
	$$output_ref{"msg_from"} = $msg_from;
	$$output_ref{"msg_body"} = $msg_body;

	$$output_ref{"url2list"} = "$af->{site__user_afid}/admin.cgi?mode=messages";

	debug_print("StandAlone::show_message: end.");
    }

    #######################################################################
    #show_message_list
    #######################################################################    
    sub show_message_list{
	my $af = shift;
	my $output_ref = shift;

	debug_print("StandAlone::show_message_list: start.");

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

	my $messages= $af->getMESGM->retrieve_all_messages();

	my @message=();
	while(@message = $messages->fetchrow_array) {
	    my ($msg_mid, $msg_timestamp, $msg_title, $msg_type,
		$msg_from, $msg_body, $msg_readflag) = @message;

	    $msg_timestamp = timestamp2string($msg_timestamp);

	    debug_print("StandAlone::show_message_list: [$msg_title]");
	    debug_print("StandAlone::show_message_list: [$msg_from]");
	    debug_print("StandAlone::show_message_list: [$msg_body]");
	    debug_print("StandAlone::show_message_list: [$msg_timestamp]");

	    ###############
	    #UserToUser (inter-Affelio massaging
	    ###############
	    #XXX
	    # This part is quite nasty. Since $msg_from is using format
	    # like '<A HREF="url">nickname</A>' due to a weird DB problem,
	    # We have to change the URL to the one through outgoing.cgi
	    # by using ad-hoc regexes....
	    if($msg_type =~ /UserToUser/){
		$msg_from =~ /<A HREF="(.*)">(.+)<\/A>/;
		debug_print("StandAlone::show_message_list: \t[$1]");
		debug_print("StandAlone::show_message_list: \t[$2]");

		$msg_from = '<A HREF="' . $af->{site__user_afid} . '/outgoing.cgi?dest_url=' . $1 . '" target="_blank">' . $2 . '</A>';
	    }
	    ###########


	    my $linkurl = "$af->{site__user_afid}/admin.cgi?mode=messages&action=show&mid=$msg_mid";
	    push(@ret_messages, 
		 {
		     'msg_title' => $msg_title,
		     'msg_from' => $msg_from,
		     'msg_timestamp' => $msg_timestamp,
		     'readflag' => $msg_readflag,
		     'msg_linkurl' => $linkurl      
		     }
		 );
	}
	debug_print("StandAlone::show_message_list: end.");
    }


}
1;
