package Admin::Authorise;
use strict;
#################################################################################
# Ikonboard v3 by Jarvis Entertainment Group, Inc.
#
# No part of this script can be used outside Ikonboard without prior consent.
#
# More information available from <ib-license@jarvisgroup.net>
# (c)2001-2002 Jarvis Entertainment Group, Inc.
# 
# http://www.ikonboard.com | http://www.jarvisgroup.net
#
# Please read the license for more information
#
# 
#
#################################################################################

BEGIN {
    require 'Lib/FUNC.pm';
    require 'Lib/ADMIN.pm';
    require 'Admin/SKIN.pm';
    require 'Boardinfo.pm' or die "Cannot load Module: $!";
}


my $SKIN  = Admin::SKIN->new();
my $std   = FUNC::STD->new();
my $ADMIN = FUNC::ADMIN->new();
my $INFO  = Boardinfo->new();
my $mail  = FUNC::Mailer->new();
my $mem   = FUNC::Member->new();

sub new {
    my $pkg = shift;
    my $obj = {};
    bless $obj, $pkg;
    return $obj;
}

sub splash_reg {
    my ($obj, $db) = @_;
    
    $obj->splash( TITLE => "Manual Registration Process",
                  SUB   => "Search for awaiting email confirmation members",
                  CODE  => 'reg_list',
                  DB    => $db,
               );
}

sub list_lost {
    my ($obj, $db) = @_;
    
    $obj->splash( TITLE => "Manual Password Request Process",
                  SUB   => "Search for members awaiting lost password confirmation",
                  CODE  => 'do_listlost',
                  DB    => $db,
               );
}

sub reg_list {
    my ($obj, $db) = @_;
    $obj->do_list( TITLE => "Manual Registration Process",
                   SUB   => "Awaiting email confirmation members",
                   CODE  => 'do_reg',
                   DB    => $db,
                 );
}

sub preview {
    my ($obj, $db) = @_;
    $obj->splash( TITLE => "Preview new registrations",
                   SUB   => "Preview new registrations before the member can post",
                   CODE  => 'list_preview',
                   DB    => $db,
                 );
}

sub list_preview {
    my ($obj, $db) = @_;
    $obj->do_list( TITLE => "Preview new registrations",
                   SUB   => "Preview new registrations before the member can post",
                   CODE  => 'do_preview',
                   DB    => $db,
                 );
}

sub do_listlost {
    my ($obj, $db) = @_;
    $obj->do_list( TITLE => "Manual Password Request Process",
                   SUB   => "Search for members awaiting lost password confirmation",
                   CODE  => 'comp_listlost',
                   DB    => $db,
                 );
}


sub do_list {
    my $obj = shift;
    my %IN = ( TITLE => "",
               SUB   => "",
               CODE  => "",
               DB    => "",
               @_,
             );

    my $db = $IN{'DB'};

    my $where = $IN{'CODE'} eq 'do_reg' ? 'register' : 'lostpass';
    
    # Preview..
    $where = 'authorise' if $IN{CODE} eq 'do_preview';

    # Set up the default email setting

    my $reg_email = "Hi\\n\\nYou have been sent this email as your registration process has been completed\\n\\nYou can visit the forums ".
                    "at $iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'} and log in fully.\\n\\nRegards\\n\\nThe $iB::INFO->{'BOARDNAME'} Team";

    my $reg2_email = "Hi\n\nYou have been sent this email as your registration process has been completed\n\nYou can visit the forums ".
                    "at $iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'} and log in fully.\n\nRegards\n\nThe $iB::INFO->{'BOARDNAME'} Team";

    my $del_email = "Hi\\n\\nYou have been sent this email as your registration process has been cancelled\\n\\nYou can reregister ".
                    "at $iB::INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'} at any time.\\n\\nRegards\\n\\nThe $iB::INFO->{'BOARDNAME'} Team";

    # Do we have a date limit?

    my $date_cut = $iB::IN{'DATE_LIMIT'} ? " and DATE_ENTERED > ".(time-(60*60*24*$iB::IN{'DATE_LIMIT'})) : '';

    my $auths = $db->query(  TABLE    => 'authorisation',
                             SORT_BY  => $iB::IN{'ORDER'},
                             SORT_KEY => 'DATE_ENTERED',
                             WHERE    => "_WHERE eq \"$where\"$date_cut",
                             RANGE    => "0 to $iB::IN{'CUT_OFF'}",
                          );

    my $count = scalar(@{$auths});

    my $html = qq~<script language="javascript">
                  <!--
                  var regEmail = "$reg_email";
                  var delEmail = "$del_email";
                  function do_email() {
                     var type    = document.TheForm.ACTION.value;
                     if (type == "del") {
                         document.TheForm.THE_EMAIL.value = delEmail;
                     }
                     if (type == "reg") {
                         document.TheForm.THE_EMAIL.value = regEmail;
                     }
                  }
                  //-->
                  </script>
                 ~;

       $html .= $SKIN->title( TITLE => $IN{'TITLE'});
       $html .= $SKIN->begin_table();
       $html .= $SKIN->form_start();
       $html .= $SKIN->hidden_fields( { act   => 'auth',
                                        CODE  => $IN{'CODE'}
                                      } );

    $html .= $SKIN->section_header( TITLE => $IN{'SUB'}, TEXT => "Please select the members and the action to be taken (Total found: $count)");

    $html .= qq~<tr>
                 <td colspan='2'>
                 <table cellspacing='0' cellpadding='5' border='0' width='100%' style='border:1px solid black'>
                             <tr>
                              <td bgcolor='#8888AA' class='t' width='5%'>&nbsp;</td>
                              <td bgcolor='#8888AA' class='t' width='35%'><span style='color:white;font-size:11px'><b>Registered Name</b></span></td>
                              <td bgcolor='#8888AA' class='t' width='30%'><span style='color:white;font-size:11px'><b>Email Address</b></span></td>
                              <td bgcolor='#8888AA' class='t' width='30%'><span style='color:white;font-size:11px'><b>Date Entered</b></span></td>
                             </tr>
               ~;

    for my $a (@{$auths}) {
        my $date = $std->get_date( TIME => $a->{'DATE_ENTERED'}, METHOD => 'LONG' );
        $html .= qq~ <tr>
                      <td bgcolor='#F1F1F1' class='t' align='center'><input type='checkbox' name='mems' value='$a->{'ID'}'></td>
                      <td bgcolor='#F1F1F1' class='t'><b>$a->{'MEMBER_NAME'}</b><br>(Member ID: $a->{'MEMBER_ID'})</td>
                      <td bgcolor='#F1F1F1' class='t'>$a->{'MEMBER_EMAIL'}</td>
                      <td bgcolor='#F1F1F1' class='t'>$date</td>
                     </tr>
                   ~;
    }

    $html .= qq~ 
                  </table>
                 </td>
                </tr>
              ~;

    my $js_code = $IN{'CODE'} eq 'do_reg' ? 'onChange="do_email()"' : '';

    $html .= $SKIN->td_select( TEXT     => "Action to be taken?",
                               NAME     => 'ACTION',
                               REQ      => 1,
                               VALUES   => 'reg',
                               JS       => $js_code,
                               DATA     => [ { NAME => 'Delete Them'            , VALUE => 'del'    },
                                             { NAME => 'Complete Process'       , VALUE => 'reg'    },
                                           ],
                             );

    if ($IN{'CODE'} eq 'do_reg' or $IN{'CODE'} eq 'do_preview') {

        $html .= $SKIN->td_select( TEXT     => "Send an email to each affected member?",
                                   NAME     => 'DO_MAIL',
                                   REQ      => 1,
                                   VALUES   => '1',
                                   DATA     => [ { NAME => 'Yes'      , VALUE => '1'    },
                                                 { NAME => 'No'       , VALUE => '0'    },
                                               ],
                                 );

        $html .= $SKIN->td_textarea( TEXT => "Email Content", NAME => 'THE_EMAIL', VALUE => $reg2_email );
    }


    $html .= $SKIN->td_submit(   NAME => '', VALUE => 'Process these applicants!' );

    $html .= $SKIN->form_end();
    $html .= $SKIN->end_table();

    $ADMIN->Output( WHERE => 'MODERATE', NAV_ONE => $IN{'TITLE'}, PRINT => $html);

}


sub do_reg {
    my ($obj, $db) = @_;

    $iB::IN{'ACTION'} eq 'del' ? $obj->_delete_them($db) : $obj->_reg_them($db);

}

sub do_preview {
    my ($obj, $db) = @_;

    $iB::IN{'ACTION'} eq 'del' ? $obj->_delete_them($db) : $obj->_complete_them($db);

}

sub comp_listlost {
    my ($obj, $db) = @_;

    $iB::IN{'ACTION'} eq 'del' ? $obj->_delete_pass($db) : $obj->_comp_pass($db);

}


sub _comp_pass {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "No members chosen!") unless $iB::CGI->param('mems');

    my @to_reg = $iB::CGI->param('mems');

    my ($reg_count, $mem_name, $mem_id);

    my $auths = $db->query(  TABLE    => 'authorisation',
                             SORT_BY  => 'Z-A',
                             SORT_KEY => 'DATE_ENTERED',
                             WHERE    => "_WHERE eq 'lostpass'",
                          );

    my %IDS = map {
                     $_->{'ID'} =>
                                    {
                                        MEMBER_ID    => $_->{'MEMBER_ID'},
                                        MEMBER_NAME  => $_->{'MEMBER_NAME'},
                                        MEMBER_EMAIL => $_->{'MEMBER_EMAIL'},
                                    }
                  } @{$auths};

    for my $d (@to_reg) {

        next unless exists $IDS{ $d };

        my $new_pass   = $mem->RandomPassword();
        my $c_new_pass = $mem->Crypt($IDS{ $d }->{'MEMBER_NAME'},$new_pass);
    
        $db->update(              TABLE    => 'member_profiles',
                                  KEY      => $IDS{ $d }->{'MEMBER_ID'},
                                  ID       => $IDS{ $d }->{'MEMBER_ID'},
                                  VALUES   => { MEMBER_PASSWORD => $c_new_pass }
                   );
    
    
        my $message = $mail->parse_template( ID     => 'LOST_PASS_TWO',
                                             DB     => $db,
                                             VALUES => { U_NAME      =>  $IDS{ $d }->{'MEMBER_NAME'},
                                                         U_PASS      =>  $new_pass,
                                                       }
                                           );

        $mail->Send( TO      => $IDS{ $d }->{'MEMBER_EMAIL'},
                     FROM    => '',
                     SUBJECT => "Re: Password request",
                     MESSAGE => $message
                   );
        

        $db->delete(   TABLE     => 'authorisation',
                       KEY       => $d,
                   );

        ++$reg_count;


    } # End mail loop.


 

    $ADMIN->static_screen( URL   => "act=auth&CODE=list_lost",
                           TITLE => "$reg_count lost password requests approved",
                           TEXT  => "The changes were successful"
                         );
}




sub _delete_pass {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "No members chosen!") unless $iB::CGI->param('mems');

    my @to_del = $iB::CGI->param('mems');

    my $del_count;

    my $auths = $db->query(  TABLE    => 'authorisation',
                             SORT_BY  => 'Z-A',
                             SORT_KEY => 'DATE_ENTERED',
                             WHERE    => "_WHERE eq 'lostpass'",
                          );

    my %IDS = map {
                     $_->{'ID'} =>
                                    {
                                        MEMBER_ID    => $_->{'MEMBER_ID'},
                                        MEMBER_NAME  => $_->{'MEMBER_NAME'},
                                        MEMBER_EMAIL => $_->{'MEMBER_EMAIL'},
                                    }
                  } @{$auths};

    for my $d (@to_del) {

        next unless exists $IDS{ $d };
        
        $db->delete( TABLE  => 'authorisation',
                     KEY    => $d,
                   );

        ++$del_count;

    } # End mail loop.

    $ADMIN->static_screen( URL   => "act=auth&CODE=list_lost",
                           TITLE => "$del_count change of password requests removed",
                           TEXT  => "The changes were successful"
                         );

}
















sub  _delete_them {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "No members chosen!") unless $iB::CGI->param('mems');

    my @to_del = $iB::CGI->param('mems');

    my ($del_count, $auths);
    if ($iB::IN{'CODE'} eq 'do_register') {
	    $auths = $db->query(  TABLE    => 'authorisation',
	                          SORT_BY  => 'Z-A',
	                          SORT_KEY => 'DATE_ENTERED',
	                          WHERE    => "_WHERE eq 'register'",
	                       );
    } elsif ($iB::IN{'CODE'} eq 'do_preview') {
    	    $auths = $db->query(  TABLE    => 'authorisation',
    	    			  SORT_BT  => 'Z-A',
    	    			  SORT_KEY => 'DATE_ENTERED',
    	    			  WHERE    => "_WHERE eq 'authorise'",
    	    		       );
    }
    my %IDS = map {
                     $_->{'ID'} =>
                                    {
                                        MEMBER_ID    => $_->{'MEMBER_ID'},
                                        MEMBER_NAME  => $_->{'MEMBER_NAME'},
                                        MEMBER_EMAIL => $_->{'MEMBER_EMAIL'},
                                    }
                  } @{$auths};

    for my $d (@to_del) {

        next unless exists $IDS{ $d };
        
        $db->delete( TABLE  => 'member_profiles',
                     KEY    => $IDS{ $d }->{'MEMBER_ID'},
                   );  
###########
#
# Added by Infection
#
        $db->delete( TABLE  => 'calendar',
                     KEY    => $IDS{ $d }->{'MEMBER_ID'},
                   );
#
########


        #Delete from Name index

        $db->update_index(  TABLE     => 'member_profiles',
                            INDEX_KEY => 'MEMBER_NAME',
                            R_KEY     => $IDS{ $d }->{'MEMBER_NAME'},
                            REMOVE    => 1
                         );

        #Delete from Email index

        $db->update_index(  TABLE     => 'member_profiles',
                            INDEX_KEY => 'MEMBER_EMAIL',
                            R_KEY     => $IDS{ $d }->{'MEMBER_EMAIL'},
                            REMOVE    => 1
                        );

        $db->delete( TABLE  => 'authorisation',
                     KEY    => $d,
                   );

        # Send the email...

        if ($iB::IN{'DO_MAIL'} && $iB::IN{'THE_EMAIL'}) {
            
             $mail->Send( TO      => $IDS{ $d }->{'MEMBER_EMAIL'},
                          FROM    => '',
                          SUBJECT => "Re: Registration at $iB::INFO->{'BOARDNAME'}",
                          MESSAGE => $iB::CGI->param('THE_EMAIL'),
                        );
        }

        ++$del_count;

    } # End mail loop.

    $ADMIN->static_screen( URL   => "act=auth",
                           TITLE => "$del_count registration requests removed",
                           TEXT  => "The changes were successful"
                         );

}



sub  _reg_them {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "No members chosen!") unless $iB::CGI->param('mems');

    my @to_reg = $iB::CGI->param('mems');

    my ($reg_count, $mem_name, $mem_id);

    my $auths = $db->query(  TABLE    => 'authorisation',
                             SORT_BY  => 'Z-A',
                             SORT_KEY => 'DATE_ENTERED',
                             WHERE    => "_WHERE eq 'register'",
                          );

    my %IDS = map {
                     $_->{'ID'} =>
                                    {
                                        MEMBER_ID    => $_->{'MEMBER_ID'},
                                        MEMBER_NAME  => $_->{'MEMBER_NAME'},
                                        MEMBER_EMAIL => $_->{'MEMBER_EMAIL'},
                                    }
                  } @{$auths};

    for my $d (@to_reg) {

        next unless exists $IDS{ $d };
        

        $db->update(   TABLE    => 'member_profiles',
                       KEY      => $IDS{ $d }->{'MEMBER_ID'},
                       ID       => $IDS{ $d }->{'MEMBER_ID'},
                       VALUES   => { MEMBER_GROUP  =>  $iB::INFO->{'MEMBER_GROUP'} },
                   );
    
    
        $db->delete(   TABLE     => 'authorisation',
                       KEY       => $d,
                   );



        # Send the email...

        if ($iB::IN{'DO_MAIL'} && $iB::IN{'THE_EMAIL'}) {
            
             $mail->Send( TO      => $IDS{ $d }->{'MEMBER_EMAIL'},
                          FROM    => '',
                          SUBJECT => "Re: Registration at $iB::INFO->{'BOARDNAME'}",
                          MESSAGE => $iB::CGI->param('THE_EMAIL'),
                        );
        }

        ++$reg_count;
        $mem_name = $IDS{ $d }->{'MEMBER_NAME'};
        $mem_id   = $IDS{ $d }->{'MEMBER_ID'};

    } # End mail loop.

    my $stats = {};
    $stats->{'TOTAL_MEMBERS'}      = '+'.$reg_count;
    $stats->{'LAST_REG_MEMBER_N'}  = $mem_name;
    $stats->{'LAST_REG_MEMBER_ID'} = $mem_id;
 
    $std->ib_stats($stats);

    $ADMIN->static_screen( URL   => "act=auth",
                           TITLE => "$reg_count registration requests approved",
                           TEXT  => "The changes were successful"
                         );

}

## COMPLETE PREVIEWED REGISTRATIONS
sub  _complete_them {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "No members chosen!") unless $iB::CGI->param('mems');

    my @to_reg = $iB::CGI->param('mems');

    my ($reg_count, $mem_name, $mem_id);

    my $auths = $db->query(  TABLE    => 'authorisation',
                             SORT_BY  => 'Z-A',
                             SORT_KEY => 'DATE_ENTERED',
                             WHERE    => "_WHERE eq 'authorise'",
                          );

    my %IDS = map {
                     $_->{'ID'} =>
                                    {
                                        MEMBER_ID    => $_->{'MEMBER_ID'},
                                        MEMBER_NAME  => $_->{'MEMBER_NAME'},
                                        MEMBER_EMAIL => $_->{'MEMBER_EMAIL'},
                                    }
                  } @{$auths};

    for my $d (@to_reg) {

        next unless exists $IDS{ $d };
        

        $db->update(   TABLE    => 'member_profiles',
                       KEY      => $IDS{ $d }->{'MEMBER_ID'},
                       ID       => $IDS{ $d }->{'MEMBER_ID'},
                       VALUES   => { MEMBER_GROUP  =>  $iB::INFO->{'MEMBER_GROUP'} },
                   );
    
    
        $db->delete(   TABLE     => 'authorisation',
                       KEY       => $d,
                   );



        # Send the email...

        if ($iB::IN{'DO_MAIL'} && $iB::IN{'THE_EMAIL'}) {
            
             $mail->Send( TO      => $IDS{ $d }->{'MEMBER_EMAIL'},
                          FROM    => '',
                          SUBJECT => "Re: Registration at $iB::INFO->{'BOARDNAME'}",
                          MESSAGE => $iB::CGI->param('THE_EMAIL'),
                        );
        }

        ++$reg_count;
        $mem_name = $IDS{ $d }->{'MEMBER_NAME'};
        $mem_id   = $IDS{ $d }->{'MEMBER_ID'};

    } # End mail loop.

    my $stats = {};
    $stats->{'TOTAL_MEMBERS'}      = '+'.$reg_count;
    $stats->{'LAST_REG_MEMBER_N'}  = $mem_name;
    $stats->{'LAST_REG_MEMBER_ID'} = $mem_id;
 
    $std->ib_stats($stats);

    $ADMIN->static_screen( URL   => "act=auth",
                           TITLE => "$reg_count registration requests approved",
                           TEXT  => "The changes were successful"
                         );

}




sub splash {
    my $obj = shift;
    my %IN = ( TITLE => "",
               SUB   => "",
               CODE  => "",
               DB    => "",
               @_,
             );

    my $db = $IN{'DB'};

    my $html  = $SKIN->title( TITLE => $IN{'TITLE'});
       $html .= $SKIN->begin_table();
       $html .= $SKIN->form_start();
       $html .= $SKIN->hidden_fields( { act   => 'auth',
                                        CODE  => $IN{'CODE'}
                                      } );

    $html .= $SKIN->section_header( TITLE => $IN{'SUB'}, TEXT => "Please specify your parameters (submitting this form will bring you to another screen - it will not carry out the chosen action)");

    $html .= $SKIN->td_select( TEXT     => "Find all entries entered ...",
                               NAME     => 'DATE_LIMIT',
                               REQ      => 1,
                               VALUES   => '7',
                               DATA     => [ { NAME => 'Today'               , VALUE => '1'    },
                                             { NAME => 'this week'           , VALUE => '7'    },
                                             { NAME => 'this month'          , VALUE => '30'   },
                                             { NAME => 'the last 3 months'   , VALUE => '90'   },
                                             { NAME => 'the last 6 months'   , VALUE => '180'  },
                                             { NAME => 'the boards lifetime'           , VALUE => '0' }
                                           ],
                             );

    $html .= $SKIN->td_select( TEXT     => "limit to...",
                               NAME     => 'CUT_OFF',
                               REQ      => 1,
                               VALUES   => '7',
                               DATA     => [ { NAME => '10 entries'             , VALUE => '10'    },
                                             { NAME => '20 entries'             , VALUE => '20'    },
                                             { NAME => '50 entries'             , VALUE => '50'    },
                                             { NAME => '100 entries'            , VALUE => '100'   },
                                             { NAME => '500 entries'            , VALUE => '500'   },
                                           ],
                             );

    $html .= $SKIN->td_select( TEXT     => "Show results in...",
                               NAME     => 'ORDER',
                               REQ      => 1,
                               VALUES   => '7',
                               DATA     => [ { NAME => 'Most recent entries first'        , VALUE => 'Z-A'    },
                                             { NAME => 'Oldest entries first'             , VALUE => 'A-Z'    },
                                           ],
                             );


    $html .= $SKIN->td_submit(   NAME => '', VALUE => 'Find the members!' );

    $html .= $SKIN->form_end();
    $html .= $SKIN->end_table();

    $ADMIN->Output( WHERE => 'MODERATE', NAV_ONE => $IN{'TITLE'}, PRINT => $html);

}


sub process {
    my ($obj, $db) = @_;

    my $CodeNo = $iB::IN{'CODE'};

    my %Mode = ( 'reg_list'        => \&reg_list,
                 'do_reg'          => \&do_reg,
                 'list_lost'       => \&list_lost,
                 'do_listlost'     => \&do_listlost,
                 'comp_listlost'   => \&comp_listlost,
                 'preview'         => \&preview,
                 'list_preview'    => \&list_preview,
                 'do_preview'      => \&do_preview,
               );

    $Mode{$CodeNo} ? $Mode{$CodeNo}->($obj,$db) : splash_reg($obj,$db);
} 





1;
