#!/usr/bin/perl

package screen_cache;

use strict;

use FindBin;
use lib "$FindBin::Bin/../";
use lib "$FindBin::Bin/../DADA/perllib";
BEGIN { 
	my $b__dir = ( getpwuid($>) )[7].'/perl';
    push @INC,$b__dir.'5/lib/perl5',$b__dir.'5/lib/perl5/x86_64-linux-thread-multi',$b__dir.'lib',map { $b__dir . $_ } @INC;
}


my $verbose;
my $c; 

my $Plugin_Config = {};

$Plugin_Config->{Plugin_URL}         = $DADA::Config::S_PROGRAM_URL . '/plugins/screen_cache/';

# Set to, 1, to enable
$Plugin_Config->{Allow_Manual_Run}   = 1;

# Pick some sort of passcode, for a semblance of security 
$Plugin_Config->{Manual_Run_Passcode} = '';

use     DADA::App::ScreenCache;

# use some of those Modules
use DADA::Template::HTML;
use DADA::App::Guts;
use DADA::MailingList::Settings;

sub reset_globals { 
    $verbose = 0; 
    $c       = DADA::App::ScreenCache->new;
}


run()
  unless caller();

sub run {
    reset_globals(); 
    my $q = shift; 
    main($q);
}

sub main {
    
    my $q = shift;
	my $prm = $q->param('prm') || undef; 
	
    if ($prm) {
        if ( $prm eq 'view' ) {
            # Probably have to deal with headers, here. 
            return ({}, $c->cached( $q->param('filename'),{-check_for_header => 1}) ); # -check_for_header doing anything? 
        }
        elsif ( $prm eq 'remove' ) {
            $c->remove( $q->param('filename') );
            return view($q);
        }
        elsif ( $prm eq 'flush' ) {
            $c->flush;
            return view($q);
        }
    }
    else {
	    if (   keys %{ $q->Vars }
	        && $q->param('run')
	        && xss_filter( scalar $q->param('run') ) == 1
	        && $Plugin_Config->{Allow_Manual_Run} == 1 )
	    {
	        return cgi_manual_start($q);
	    }
		else { 
        	return view($q);
		}	
    }
}

sub view {

    my $q = shift; 
    
    my ( $admin_list, $root_login, $checksout, $error_msg ) = check_list_security(
        -cgi_obj  => $q,
        -Function => 'screen_cache'
    );
    if(!$checksout){ 
        return({}, $error_msg); 
    }
    
    my $list = $admin_list;	
    my $file_list = $c->cached_screens;

    my $app_file_list = [];

    for my $entry (@$file_list) {
        my $cutoff_name = $entry->{name};
        my $l    = length($cutoff_name);
        my $size = 50;
        my $take = $l < $size ? $l : $size;
        $cutoff_name = substr( $cutoff_name, 0, $take );
        $entry->{cutoff_name} = $cutoff_name;
        $entry->{dotdot} = $l < $size ? '' : '...';

        push( @$app_file_list, $entry );

    }

    my $curl_location = `which curl`;
       $curl_location = strip( make_safer($curl_location) );

    require DADA::Template::Widgets;
    my $scrn = DADA::Template::Widgets::wrap_screen(
        {
			-screen         => 'plugins/screen_cache/view.tmpl', 
			-with           => 'admin', 
			-wrapper_params => { 
				-Root_Login => $root_login,
				-List       => $list,  
			},
            -vars   => {
				Plugin_URL          => $Plugin_Config->{Plugin_URL}, 
				Allow_Manual_Run    => $Plugin_Config->{Allow_Manual_Run},  
				Manual_Run_Passcode => $Plugin_Config->{Manual_Run_Passcode},
                file_list           => $app_file_list,
				curl_location       => $curl_location, 
                cache_active        => $DADA::Config::SCREEN_CACHE ne "1" ? 0 : 1,
            },
        }
    );
    return ({}, $scrn);

}

sub cgi_manual_start {
    my $q = shift; 
    
    if (
        (
            xss_filter( scalar $q->param('passcode') ) eq
            $Plugin_Config->{Manual_Run_Passcode}
        )
        || ( $Plugin_Config->{Manual_Run_Passcode} eq '' )
      )
    {


        if ( defined( xss_filter( scalar $q->param('verbose') ) ) ) {
            $verbose = xss_filter( scalar $q->param('verbose') );
        }
        else {
            $verbose = 1;
        }

     	$c->flush;
		return ({}, 'All cached screens have been removed.'); 
    }
    else {
        return ({}, "$DADA::Config::PROGRAM_NAME $DADA::Config::VER Authorization Denied.");
    }
}

=pod

=head1 NAME 

screen_cache.cgi - View/Removed Dada Mail cached sceens

=head1 Obtaining The Plugin

screen_cache.cgi is located in the, I<dada/plugins> directory of the Dada Mail distribution, under the name: C<screen_cache.cgi>

=head1 DESCRIPTION 

See the feature overview on Dada Mail's Screen Cache: 

L<https://dadamailproject.com/support/documentation/features-screen_cache.pod.html>

This plugins allows you to view and remove any currently cached screens. 


=head1 Installation 

This plugin can be installed during a Dada Mail install/upgrade, using the included installer that comes with Dada Mail. The below installation instructions go through how to install the plugin manually.

=head2 Change permissions of "screen_cache.cgi" to 755

The, C<screen_cache.cgi> plugin will be located in your, I<dada/plugins> diretory. Change the script to, C<755>

=head2 Configure your .dada_config file

Now, edit your C<.dada_config> file, so that it shows the plugin in the left-hand menu, under the, B<Plugins> heading: 

First, see if the following lines are present in your C<.dada_config> file: 

 # start cut for list control panel menu
 =cut

 =cut
 # end cut for list control panel menu

If they are, remove them. 

Then, find these lines: 

 #					{
 #					-Title      => 'Screen Cache',
 #					-Title_URL  => $S_PROGRAM_URL."/screen_cache",
 #					-Function   => 'screen_cache',
 #					-Activated  => 0,
 #					},

Uncomment the lines, by taking off the, "#"'s: 

 					{
 					-Title      => 'Screen Cache',
 					-Title_URL  => $S_PROGRAM_URL."/screen_cache",
 					-Function   => 'screen_cache',
 					-Activated  => 0,
 					},

Save your C<.dada_config> file.

=head1 COPYRIGHT

Copyright (c) 1999 - 2023 Justin Simoni All rights reserved. 

=head1 LICENSE

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.

=cut


