$versions{'upgrade_manager-ext_lib.pl'} = '06.6.00.0000';

# Contains all sub routines (functions) to upgrade AgoraCart software libraries and modules.

#######################################################################
#
# AgoraCart and all associated files, except where noted, are
# Copyright 2001 to Present jointly by K-Factor Technologies, Inc.
# and by C E Mayo (aka Mister Ed) at AgoraCart.com & K-Factor.net
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This copyright notice may not be removed or altered in any way.
#
#######################################################################

#STUFF TO USE
    #######################################################################
    #$test_perl_module  = `perl -MFile::Copy -e 'print "$File::Copy::VERSION\n"'`;
    #######################################################################

# Show versions of files from the manager (if logged in)
# http://.../.../manager.cgi?mgr_seshun=$in{'mgr_seshun'}&versions=1

local ($modname)  = 'upgrade_manager-ext_lib.pl';
local ($test_repeats) = '0';

$updateErrorMessage  = q{};
$mgr_upgrade_error_message     = q{};
$mgr_core_backupdir = "$mgrdir/zbackup_archives";

{    # Begin code hiding

    register_extension( $modname, 'Upgrade Versions', $versions{$modname} );
    add_settings_choice(
        'Upgrade Manager',
        'Upgrade Your Store Software',
        'display_upgrade_options'
    );
    register_menu(
        'display_upgrade_options', 'main_upgrade_manager_screen',
        $modname,  'Display Store Upgrade Options'
    );
    register_menu(
        'versions', 'show_manager_versions',
        $modname,  'Show Module Versions'
    );
    register_menu( 'updateCartFile', 'get_and_update_cart_file', $modname,
        'Get and save-write updated cart file' );
    register_menu( 'updateCoreFile', 'get_and_update_core_files', $modname,
        'Get, save and backup cart core files' );
    register_menu(
        'displayPaymentGatewayInstaller', 'display_gateway_install_page',
        $modname, 'Display Payment Gateway Install options'
    );
    register_menu(
        'clicktoinstallpaymentgateway', 'perform_payment_gateway_install',
        $modname, 'Install Payment Gateway Files'
    );
    register_menu( 'clicktoremovepaymentgateway', 'perform_payment_gateway_removal',
        $modname, 'Remove Payment Gateway Files' );

}

#######################################################################

sub get_and_update_cart_file {

    local $passedPluginStatus  = "$in{'pluginStatus'}";
    local $sourceFileName   = $in{'sourceFileName'};
    local $storeFileName  = "$in{'storeFileName'}";
    local $sourcePath  = "$in{'sourcePath'}";
    local $storePath  = "$in{'storePath'}";
    local ( $storeFile, $serverFile ) = q{};

    # untaint path/file
    $sourceFileName =~ /^([\/-\@\w.\-]+)$/;
    $sourceFileName = $1;
    $storeFileName =~ /^([\/-\@\w.\-]+)$/;
    $storeFileName = $1;
    $sourcePath =~ /^([\/-\@\w.\-]+)$/;
    $sourcePath = $1;
    $storePath =~ /^([\/-\@\w.\-]+)$/;
    $storePath = $1;

    $storeFile = $storePath . $storeFileName;
    $serverFile = $sourcePath . $sourceFileName;

    if ( $passedPluginStatus eq 'tarball' ) {
        &get_and_update_cart_plugin_group();
    }
    elsif ( $passedPluginStatus eq 'twoTextFiles' ) {
        # get/update actual file
        &get_and_update_cart_text_file();

        # get/update plugin manifest file
        $storeFile =~ s/\./_plugin_manifest\./;
        $storeFile =~ s/pl$/inc/;
        $serverFile =~ s/\./_plugin_manifest\./;
        &get_and_update_cart_text_file();
    }
    else {
        &get_and_update_cart_text_file();
    }

    &main_upgrade_manager_screen();

}

#######################################################################

sub get_and_update_cart_text_file {

    my $file       = q{};
    my $test       = q{};
    my $timethingy = time;

    if ( $serverFile ) {
        my $url = "https://agoracart.com/$serverFile";
        $file = simple_secure_URL_file_getter($url);

        if ( ( $file =~ /do not have permission to access/i )
            || ( $file =~ /Not Found/ ) )
        {
            $test = "ERROR: $storeFile is not reachable for updates.<br>";
            $file = q{};
        }

    }
    else {
        $file = q{};
    }

    # error conditionals added by Mister Ed March 15, 2006
    if ( $file ) {

        #create backup file.  added by Mister Ed Feb 6, 2006
        if (-e "./$storeFile") {
            my $filename5 = $storeFile;
            $filename5 =~ s/pl$/txt/;
            $filename5 =~ s/cgi$/txt/;
            # for backup file name, in case something goes wrong.
            $filename5 =~ s/\./_r66_update_$timethingy\./;

            # use File::Copy;
            copy( $storeFile, $filename5 );

            # use system command if File::Copy not there
            # add in error check later?
            # system("cp $filename2 $filename5");
        }

        open( UPDATEFILE, ">./$storeFile" ) || my_die("Can't Open $storeFile");
        print( UPDATEFILE $file );
        close(UPDATEFILE);


        if ( $storeFile =~ /cgi$/ ) {
            system("chmod 755 ./$storeFile");
        }

        # error messages and conditionals added by Mister Ed March 15, 2006
        $updateErrorMessage .=
"SUCCESS ... $storeFile was successfully updated.<br><br><b>DO NOT RELOAD / REFRESH THIS PAGE!</b><br><br>";

    }
    elsif ( $test ) {
        $updateErrorMessage .= $test;
    }
    else {
        $updateErrorMessage .=
"ERROR: $storeFile was not reachable for updates. <br><b>Please, check your Member's Only password settings.</b>";
    }

}

#######################################################################
# updates AgoraCart core files by downloading a compressed tar (tgz)
# file(s). Backups are compressed into an archive and stored in the
# manager's rollback directory. Downloaded archive file is then uncompressed
# to overwrite the existing files.  Only core files are backed up and changed.

sub get_and_update_core_files {

    my ( $file, $test, $file2remode ) = q{};
    my $timethingy = time;
    my $tarballname = 'core_backup_' . $timethingy . '.tgz';

    # Build list of update archives we want to download from AgoraCart.com
    my @filearray = ( 'core.tgz|downloadupdates/Route66/' );

    my @inventory = (); # Create inventory of files & directories to add to backup archive
    my @dirs = ( 'manager/core','./manager/ext_libs','manager/assets','system66/cart','system66/checkout','system66/library','system66/payment_gateways','system66/perl_modules','system66/shipping','system66/view','view66/assets' );

    # core Perl modules, but in eval so we don't load it unless needed
    eval("use Archive::Extract;");
    eval("use Archive::Tar;");
    eval("use File::Find;");
    $Archive::Tar::CHMOD = 0; # PRESERVE PERMISSIONS!

    print &$manager_page_header('AgoraCart Community Route 66 Version Core Updates in Progress', '', '', '', '' );

    if ( !(-d "$mgr_core_backupdir") ) {
        system("mkdir $mgr_core_backupdir");
        chmod $mgr_perms_mode, "$mgr_core_backupdir";
    }

    # Create backup

    print '<br><h2>Creating a Backup Archive of Current Core Store Files ... </h2><br><br>';

    print '<form><textarea class="form-control" rows="12">';

    foreach $dir (@dirs) {
        $dir =~ /^([-+@\w.\/]+)$/;
        $dir = $1;
        find (sub { $File::Find::untaint = 1; push @inventory, $File::Find::name; print "Adding " . $File::Find::name . " to backup archive\n";}, $dir);
    }

    # Create a new tar object & add files.
    my $tar = Archive::Tar->new();
    $tar->add_files( @inventory );
    $tar->add_files('manager/manager.cgi');
    $tar->add_files('agora.cgi');

    print '</textarea></form><p><br></p>';

    # Write compressed backup tar file to rollback directory
    $tar->write( "$mgr_core_backupdir/$tarballname", COMPRESS_GZIP );

    # remove older achives than the last 7 backup archives
    system("ls -1t $mgr_core_backupdir/*.tgz  | tail -n +8 | xargs rm -f");

    foreach my $corefilearray (@filearray) {
        my ( $filename, $filenamegetlocation ) = split( /\|/, $corefilearray );
        chomp $filenamegetlocation;

        print '<h2>Updating Core Store Files ... </h2><br><br>';

        my $url = "https://agoracart.com/$filenamegetlocation$filename";
        $file = simple_secure_URL_file_getter($url);

        if ( $file =~ /error/i  ) {
            $file = q{};
        }

        # success/error conditionals
        if ( $file ) {

            print "$filename successfully retrieved from AgoraCart.com<br>";
            open( UPDATEFILE, ">./$filename" ) || my_die("Can't Open $filename");
            print( UPDATEFILE $file );
            close(UPDATEFILE);
            print "$filename successfully saved<br><br>";

        }
        else {
            print 'ERROR: The requested files were not reachable for updates.  Please check your password settings.<br>';
        }
        $file = q{};

        # Now extract upgrade file
        $Archive::Tar::CHMOD = 0; # PRESERVE PERMISSIONS!
        my $artar = Archive::Tar->new();
        $artar->read( $filename );
        $artar->extract();
        print "<h4>Files/Directories Updated by $filename:</h4><br>";
        my @files = Archive::Tar->list_archive($filename);
        print '<form><textarea class="form-control" rows="12">';
        foreach $file (@files) {
            print "$file\n";
        }
        print '</textarea></form><p><br></p>';
        unlink("$filename");

        if ( $filename eq 'core.tgz' ) {
            $file2remode = "agora.cgi";
            system("chmod 755 ./$file2remode");
            $file2remode = "pplistnr.cgi";
            system("chmod 755 ./$file2remode");
            $file2remode = "manager/manager.cgi";
            system("chmod 755 ./$file2remode");
        }

    }

    # delete old core & misc files no longer used nor supported. Loads updated file/list.
    require_supporting_libraries( __FILE__, __LINE__, "$mgrcoredir/depreciated_files.pl" );
    &delete_these_old_files();

    # Adds misc files not normally in core updates that were added since last update. Loads updated file/list.
    require_supporting_libraries( __FILE__, __LINE__, "$mgrcoredir/new_files.pl" );
    &add_these_new_files();

    print <<ENDOFTEXT;
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<input name="display_upgrade_options" type="hidden" value="Submit">
<button class="btn btn-primary btn-lg mgr-center" style="display: block;">Back to Store Upgrade Manager</button>
</form>
<p><br><br><br><br></p>
ENDOFTEXT
    print &$manager_page_footer;

    call_exit();
}

#######################################################################
sub main_upgrade_manager_screen {

    # Show %in if requested
    my $in =
      $in{'showin'} && $in{'showin'} ? build_table_from_hash( 'Incoming Variables', \%in ) : q{};

    # Show ENV if requested
    my $env = $in{'showenv'} && $in{'showenv'}  ? build_table_from_hash( 'Environment Variables', \%ENV ) : q{};

    # overwrite the global versions hash so that all libs and add-ons are found.
    %versions = installed_versions();

    my $today = time();
    my $compareTimes = $today - $mgr_lastchecked_update_status;

    $versions = build_table_from_hash('Core AgoraCart Files Already Installed');

    print &$manager_page_header( "AgoraCart Route 66 Version File Upgrade Manager", '', '', '', '' );

    print qq~
<h1 class='mgr-page-title'>Store Update Manager</h1>
<p><br></p>
~;

    if ( $in{'system_edit_success'} ) {
        print <<ENDOFTEXT;
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-success">
        <h4 class="text-primary mgr-center">Updates Attempted:</h4>
        <p>$updateErrorMessage</p>
        </div>
    </div>
<div class="row col-xs-12 col-sm-12"><p><br></p></div>
ENDOFTEXT
    }

    my $test_perl_version = sprintf( "%vd", $^V );
    my $os_version = "$^O";
    my $perl_test_error_mesage = q{};
    my $perl_test_status = 'OK! ';
    my ( $major, $majorMin, $minner ) = split( /\./, $test_perl_version );
    if (
       ( $major > 5 )
       || (  ( $major == 5 ) && ( $majorMin >= 8 ) && ( $minner >= 8 ) )
     ) {
        $perl_test_status = 'OK! '; #ok for now
    }
    elsif (
  ( $major < 5 )
  || (  ( $major == 5 ) && ( $majorMin < 8 ) )
  || (  ( $major == 5 ) && ( $majorMin == 8 ) && ( $minner < 9 ) )
) {
        $perl_test_error_mesage =
"<font color=red><b>WARNING: Your Perl version is VERY old (Released before 2006)</b>.</font> The current Perl version on newer servers is 5.12.4 or 5.16.2.  The AgoraCart Route 66 version requires Perl 5.8.8 or higher, but <b>versions 5.10.1/5.12.4 thru 5.20.x are recommended</b>. Please ask your hosting provider if they have an additional Perl version installed that your scripts can use.<br><br>";
        $perl_test_status .=
'<font color=red size=2>but very old. See warning message at bottom!</font>';
    }
    if ( ( $major == 5 ) && ( $majorMin < 12 ) && ( $minner < 9 ) ) {
        $perl_test_error_mesage = qq||;
        $perl_test_status .= 'but slightly outdated!';
    }

    print qq~
<div class="row col-xs-12 col-sm-12"><p><br></p>
<b>Perl version:</b> $test_perl_version $perl_test_status | <b>Operating System:</b> $os_version
<p><br><br></p></div><div class="row col-xs-12 col-sm-12" align="center">
<div class="table-responsive"><table class="table-condensed"><tr>
~;

    print qq~
<td>
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<input name="displayPaymentGatewayInstaller" type="hidden" value="Submit">
<button class="btn btn-primary mgr-center">Install Payment Gateways</button>
</form>
</td>
~;

    print qq~
</form>
</td>
</tr></table><p><br><br></p></div></div>
</font>
~;

    print $versions . $in . $env;

    print $perl_test_error_mesage;

    print qq|
<p>* time = number of seconds since 1970 (EPOCH) in most cases.</p>
<p><br><br><br></p>
|;
    print &$manager_page_footer;

    call_exit();
}

#######################################################################

sub show_manager_versions {
    1;
}

#######################################################################
# Expects a string to be used for a title and a reference to a hash
# Returns a string of an html table

sub build_table_from_hash {

    my ($title) = @_;
    my ( @upline ) = '';
    my ( $coretest, $upgradecoreverholder, $current_versions ) = q{};

    # read files for updates for community version add-ons
    $mgr_upgrade_error_message = "yes";
    my $content = simple_secure_URL_file_getter('https://agoracart.com/downloadupdates/Route66/comupgrade66addons.txt');

    my $error1 = 'Authorization Required';
    my $error2 = 'server could not verify';
    my $error3 = 'was not found';

    if ( ( $content ) && ( ( $content !~ /$error1/i ) || ( $content !~ /$error2/i )  || ( $content !~ /$error3/i ) ) ) {
        $mgr_upgrade_error_message = 'no';
    }

    @upline = split( /\n/, $content );

    $current_versions = simple_secure_URL_file_getter($mgr_versions_URL);
    my ($upversion,$edge_cur_version,$agoracgi_version,$lang_version,$viewers_version) = split(/\|/, "$current_versions");
    chomp $viewers_version;
    if ( $sc_mgr_upgrade_tier eq 'Edge' ) {
        $upversion = $edge_cur_version;
    }
    if ( ( $versions{'agora.cgi'} lt $agoracgi_version ) || ( $versions{'manager.cgi'} lt $upversion ) ) { $coretest = 'upgrade'; }
        $upgradecoreverholder = "$upversion";

    my $table = qq|
<h3 class='mgr-page-title'>AgoraCart Community Version Update - Core Only</h3>
<p><br></p>|;

    if ( $coretest eq 'upgrade' ) {
        $table .= qq~
<table border="0" cellspacing="0" cellpadding="9" valign="top"><tr><td width="300" valign="top">
<font size="+1" color="red">Upgrade to Version: $upgradecoreverholder</font></td>
<td valign="top"><form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<input type="hidden" name="coreToUpgrade" value="$upkey"><input type="hidden" name="system_edit_success" value="yes">
<input name="updateCoreFile" type="hidden" value="Submit">
<button class="btn btn-primary btn-sm mgr-center">Update Now</button></form></td></tr>
<tr><td colspan="2"><font size="-1"><b>Note:</b> File backups under this method are placed in compressed archive file (.tgz) with a "server-time-numbered" name within the <b>$mgr_core_backupdir</b> sub-directory of your store manager areas.</td></tr></table><p><br></p>~;
    }
    else {
        $table .=
qq|<font size="+1" color="green">  &nbsp;&nbsp; Currently Installed: $versions{'manager.cgi'} &nbsp;&nbsp;<b>OK! &nbsp; - &nbsp; Up to Date</b></font><p><br><br></p>|;
    }

    $table .= qq|
<h3 class='mgr-page-title'>"Gold Version" Add-on Modules</h3>
<p><br></p>
<p class="well">For upgrades to any currently installed file listed below, a backup will be created in the form of <b>filenamehere_r66_update.servertimehere</b> in case something goes wrong as well as to ensure that each backup file is unique.</p>
<p><br></p>

<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr bgcolor="#c0c0c0"><td bgcolor="#c0c0c0"><b>File Name</b></td>
<td bgcolor="#c0c0c0"><b>Your Version</b></td>
<td bgcolor="#c0c0c0"><b>Pre-install Notes</b></td>
<td bgcolor="#c0c0c0"><b>Option</b></td></tr>
|;
    foreach my $line (@upline) {
        my ( $upkey, $upversion, $upfilename, $upgradeStorePath, $upgradeSourcePath, $pluginStatus, $notusedyet, $notes ) = split( /\|/, $line );
        my ( $button_status, $disable_me, $pluginElements ) = q{};
        my $button_text = 'Update Now';
        chomp $notes;
        my $tempthingy = "$versions{$upkey}";
        if ( $versions{$upkey} eq '' ) {
            $tempthingy = '<b>not installed</b>';
            $button_text = 'Install';
        }
        if ( $pluginStatus ) {
            $pluginElements = qq|<input type="hidden" name="pluginStatus" value="$pluginStatus">|;
        }
        # not upgraded for Route 66 yet, so disable upgrade until it is ready
        if ( $upversion eq '' ) {
            $button_status = ' disabled';
            $disable_me = 'yes';
        }
        $table .=
qq~  <tr><td align="left"><font size="-1">$upkey</font></td><td align="left"><font size="-1">$tempthingy</font></td><td align="left">~;
        if ( $disable_me ) {
            $table .= qq~
<font size="-1">$notes</font></td><td><font size="-1"><div align=center>Not Avail yet<br>
<form action="manager.cgi" method="post">
<button class="btn btn-sm mgr-center$button_status">$button_text</button>
</form></div>
</font></td></tr>
~;
        }
        elsif ( $versions{$upkey} lt $upversion ) {
            $table .= qq~
<font size="-1">$notes</font></td><td><font size="-1"><div align=center>update to:<br>$upversion<br>
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<input type="hidden" name="sourceFileName" value="$upfilename">
<input type="hidden" name="storeFileName" value="$upkey">
<input type="hidden" name="storePath" value="$upgradeStorePath">
<input type="hidden" name="sourcePath" value="$upgradeSourcePath">
$pluginElements
<input type="hidden" name="system_edit_success" value="yes">
<input name="updateCartFile" type="hidden" value="Submit">
<button class="btn btn-primary btn-sm mgr-center$button_status">$button_text</button>
</form></div>
</font></td></tr>
~;
        }
        else {
            $table .=
qq|<font size="-1">$notes</font></td><td><button class="btn btn-sm mgr-center disbled"><b>Up to Date</b></button></td></tr>|;
        }

        $disable_me = q{};

    }
    $table .= "</table></div><br>\n";

    return $table;
}

#######################################################################

# Expects nothing
# Returns hash of installed versions in list context or
# reference to hash in scalar context

sub installed_versions {

    # Do nothing if called as a lvalue
    return undef unless defined wantarray;

    # Grab versions from known locations
    my $versions =
`grep -h "^\\\$versions{'.*'}\\ *=" $mgrlibdir/*.pl $mgrdir/*.cgi $mgrcoredir/*.pl ./*.cgi $mgrdir/plug_ins/*.pl $sc_paygates_dir/managers/*.pl $sc_paygates_dir/managers/*.pl $sc_syscart_dir/*.pl $sc_syscheckout_dir/*.pl $sc_lib_dir/*.pl $sc_shiplib_dir/*.pl $sc_add_on_modules_dir/*.pl $sc_sysview_dir/*.pl $sc_sysview_dir/*.inc 2> /dev/null`;

    # Build hash of installed versions
    my %installed_versions;

    for my $version ( split /\n/, $versions ) {
        my ( $key, $val ) = $version =~ /versions{'(.*?)'}\s*=\s*'(.*?)'/;
        if ( $val eq '' ) {
            ( $key, $val ) = $version =~ /versions{'(.*?)'}\s*=\s*"(.*?)"/;
        }
        $installed_versions{$key} = $val;
    }

    return wantarray ? %installed_versions : \%installed_versions;
}

#######################################################################

sub perform_payment_gateway_removal {

    $in{'sc_PaymentGatewayToremove'} =~ /([\w\-\/]+)/;
    $in{'sc_PaymentGatewayToremove'} = "$1";
    my $filename = "$in{'sc_PaymentGatewayToremove'}";
    my $active_gate = '';
    $updateErrorMessage = '';

    if ( $sc_gateway_name =~ /$filename/i ) {
        $in{'sc_PaymentGatewayToremove'} = q{};
        $updateErrorMessage =
"You attempted to Delete your Primary Gateway. Please change your store settings before trying to remove the $filename payment gateway files.<br>";
    }

    if ( $mc_mgr_gateways_enabled =~ /$in{'sc_PaymentGatewayToremove'}/i ) {
        $active_gate = 'yes';
    }

    if ( ( $in{'sc_PaymentGatewayToremove'} ) && ( $active_gate eq '' ) ) {

        if ( $in{'removepguserlib'} ) {
            my $local_delete = "$sc_userpay_conf_dir/$filename" . "-user_lib.pl";
            if ( -e "$local_delete" ) {
                `rm -f $local_delete`;
                $updateErrorMessage .= "$local_delete removed.<br>";
            }
        }
        if ( $in{'removepgorderform'} ) {
            my $local_delete =
              "$sc_form_dir_path/$filename" . "-orderform.html";
            if ( -e "$local_delete" ) {
                `rm -f $local_delete`;
                $updateErrorMessage .= "$local_delete removed.<br>";
            }
        }
        if ( $in{'removepgorderlib'} ) {
            my $local_delete = "$sc_paygates_dir/$filename" . "-order_lib.pl";
            if ( -e "$local_delete" ) {
                `rm -f $local_delete`;
                $updateErrorMessage .= "$local_delete removed.<br>";
            }
        }
        if ( $in{'removepgmgrlib'} ) {
            my $local_delete = "$mc_paygatesmgr_path/$filename" . "-mgr_lib.pl";
            if ( -e "$local_delete" ) {
                `rm -f $local_delete`;
                $updateErrorMessage .= "$local_delete removed.<br>";
            }
        }

        $updateErrorMessage .= '<br>Selected Gateway Files were removed and/or did not exist.<br>';

    }
    elsif ( ( $in{'sc_PaymentGatewayToremove'} ) && ( $active_gate eq 'yes' ) ) {
        $updateErrorMessage = 'Active Gateway Selected. Please deactivate before removing. Request Cancelled.<br>';
    }
    else {
        $updateErrorMessage = 'No Gateway Selected. Request Cancelled.<br>';
    }

    display_gateway_install_page();
}

#######################################################################

sub perform_payment_gateway_install {

    local ( $serverFile, $storeFile );
    $in{'sc_newPaymentGatewayToinstall'} =~ /([\w\-\/]+)/;
    $in{'sc_newPaymentGatewayToinstall'} = "$1";
    my ( $gatewayname, $memberlevel ) =  split( /\//, $in{'sc_newPaymentGatewayToinstall'} );

    if ( $in{'sc_newPaymentGatewayToinstall'} ) {
        # install/reinstall default user settings - wipes out existing settings file
        if ( $in{'installpguserlib'} ) {
            $storeFile = "$sc_userpay_conf_dir/$gatewayname" . '-user_lib.pl';
            $serverFile = "downloadupdates/Route66/gateways/$gatewayname" . '-user_lib.txt';
            &get_and_update_cart_text_file();
        }
        # install/reinstall default order form - wipes out any user customizations - good for upgrading to newer version.
        if ( $in{'installpgorderform'} ) {
            $storeFile = "$sc_form_dir_path/$gatewayname" . '-orderform.html';
            $serverFile = "downloadupdates/Route66/gateways/$sc_lang_path/$sc_cssframework_dir_for_URL/$gatewayname" . '-orderform.txt';
            &get_and_update_cart_text_file();
        }
        # install/upgrade order lib for manager selected gateway.
        if ( $in{'installpgorderlib'} ) {
            $storeFile = "$sc_paygates_dir/$gatewayname" . '-order_lib.pl';
            $serverFile = "downloadupdates/Route66/gateways/$gatewayname" . '-order_lib.txt';
            &get_and_update_cart_text_file();
        }
        if ( $in{'installpgmgrlib'} ) {
            $storeFile = "$mc_paygatesmgr_path/$gatewayname" . '-mgr_lib.pl';
            $serverFile = "downloadupdates/Route66/gateways/$gatewayname" . '-mgr_lib.txt';
            &get_and_update_cart_text_file();
        }

        $updateErrorMessage .= 'Selected Gateway Installation / Upgrade Completed.<br>';

    }
    else {
        $updateErrorMessage = "No Gateway Selected. Request Cancelled.<br>";
    }

    display_gateway_install_page();
}

#######################################################################

sub display_gateway_install_page {

    my $my_available_gateways = q{};

    print &$manager_page_header( 'AgoraCart Payment Gateways: Install &amp; Remove', '', '', '', '' );

    load_custom( "$mgrlibdir",   '-ext_lib.pl' ); # reload
    load_custom( "$mc_paygatesmgr_path", '-mgr_lib.pl' ); # reload

    my $error2 = 'server could not verify';

    my $mylist_of_gateway_options = q{};
    @gwlist = split( /\|/, $mc_gateways );
    foreach $item (@gwlist) {
        if ( $item ) {
            my ($filename, $displayname)= split( /::/, $item );
            if ( $displayname eq '' ) { $displayname = $filename;}
            $item_lc = $item;
            $item_lc =~ tr/A-Z/a-z/;
            $zlist{$item_lc} = "<option value='$item'>$displayname</option>\n";
        }
    }
    foreach $item ( sort( keys %zlist ) ) {
        $mylist_of_gateway_options .= $zlist{$item};
    }

    my $url = "https://agoracart.com/downloadupdates/Route66/compaygates66.txt";
    my $content = simple_secure_URL_file_getter($url);

    if ( ( $content ) && ( $content !~ /$error2/i ) ) {
        my @line = split( /\n/, $content );
        foreach $line (@line) {
            chomp $line;
            my ( $bareGateName, $displayname, $junk ) = split( / \- /, $line, 3 );
            if ( $junk =~ /Standard/ ) {
                $my_available_gateways .=
qq~<option value="$bareGateName/member">$displayname</option>\n~;
            }
        }
    }

    if ( $in{'system_edit_success'} ) {
        print <<ENDOFTEXT;
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-success">
    <h4 class="text-primary mgr-center">Updates Attempted:</h4>
    <p>$updateErrorMessage</p>
    </div>
</div>
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
<p><br><br><br></p>
</div>
ENDOFTEXT
    }

    print qq~
<h2 class='mgr-page-title'>Payment Gateway Install / Upgrade</h2>
<p><br></p>

<p class="well">This section allows you to install new gateways or update existing ones.  You can install any combination of the files as needed <b>NOTE:</b> Existing files upgraded/installed using this method will be overwritten.  For example if you altered your order form previously a payment gateway and you select to install the order form option for the same gateway, your customized order form will be replaced with the default one. This is advisable only if you have messed up on an order form or you wish to get the newest version of the form and can redo the customizations.<br><br>
For more information on available gateways, please visit the <a href="https://AgoraCart.com/paymentgateways.php" target="_blank">Supported Gateways Page at AgoraCart.com</a><br><br><a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&display_upgrade_options=yes">Back to Upgrade manager</a></p>
<p><br></p>

<p><b>Select a Payment Gateway to Install / Upgrade: </b></p>
<form action="manager.cgi" method="post">
<input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<select name="sc_newPaymentGatewayToinstall">
<option></option>
$my_available_gateways
</select>
<p><br></p>
<p>
<input type="checkbox" name="installpgmgrlib" value="1"> Install/Upgrade Gateway Settings Manager (common for upgrades)<br><br>
<input type="checkbox" name="installpgorderlib" value="1"> Install/Upgrade Order Processing Libraries (common for upgrades)<br><br>
<input type="checkbox" name="installpguserlib" value="1"> Install Blank Settings File (erases any existing settings)<br><br>
<input type="checkbox" name="installpgorderform" value="1"> Install Default Order Form (leave blank for most upgrades)<br>
</p>
<p><br></p>
<input type="hidden" name="system_edit_success" value="yes">
<input name="clicktoinstallpaymentgateway" type="hidden" value="Submit">
<button class="btn btn-primary btn-lg mgr-center" style="display: block;">Install / Upgrade Selected Gateway</button>
</form>

<p><br><hr><br></p>

<h2 class='mgr-page-title'>Payment Gateway Uninstall / Removal</h2>
<p><br></p>

<p class="well">This section allows you to remove entire payment gateways or portions of existing gateways.  You can remove any combination of the files as needed. Once the Manager Settings file for a gateway is removed, you can no longer remove files for that gateway, so make sure to delete all the desired gateway files before or at the same time as deleting the manager file. <b>NOTE: once you remove the file(s) for the selected gateway, it is gone forever, so make sure you select the correct gateway as there are no second chances with this tool.</b><br><br><a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&display_upgrade_options=yes">Back to Upgrade manager</a></p>
<p><br></p>


<p><b>Select a Payment Gateway to Remove components for: </b></p>
<form action="manager.cgi" method="post">
<input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<select name="sc_PaymentGatewayToremove">
<option></option>
$mylist_of_gateway_options
</select>
<p><br></p>
<p>
<input type="checkbox" name="removepguserlib" value="1"> Remove Gateway Settings File<br><br>
<input type="checkbox" name="removepgorderform" value="1"> Remove Existing Order Form<br><br>
<input type="checkbox" name="removepgmgrlib" value="1"> Remove Gateway Settings Manager<br><br>
<input type="checkbox" name="removepgorderlib" value="1"> Remove Order Processing Library<br>
</p>
<p><br></p>
<input type="hidden" name="system_edit_success" value="yes">
<input name="clicktoremovepaymentgateway" type="hidden" value="Submit">
<button class="btn btn-primary btn-lg mgr-center" style="display: block;">Remove Selected Gateway</button>
</form>
<p><br><hr><br></p>
~;

    # Grab versions from known locations
    my $gversions =
`grep -h "^\\\$versions{'.*'}\\ *=" $sc_paygates_dir/*-order_lib.pl $mc_paygatesmgr_path/*-mgr_lib.pl 2> /dev/null`;

    # Build hash of installed versions
    my %instgversions;

    for my $gversion ( split /\n/, $gversions ) {
        my ( $key, $val ) = $gversion =~ /versions{'(.*?)'}\s*=\s*'(.*?)'/;
        $instgversions{$key} = $val;
    }

    my @line = q{};

    $mgr_upgrade_error_message = 'yes';

    my $url2 = "https://agoracart.com/downloadupdates/Route66/compaygatesup66.txt";
    my $content2 = simple_secure_URL_file_getter($url2);
    my $error2 = "This server could not verify";

    if ( ( $content2 ) && (  $content2 !~ /$error2/i ) ) {
        $mgr_upgrade_error_message = 'no';
    }

    @line = split( /\n/, $content2 );

    foreach $line (@line) {
        my ( $upkey, $upversion, $notes ) = split( /\|/, $line );
        chomp $notes;
        $updatesAvailable{$upkey} = "$upversion";
        $upnotes{$upkey} = "$notes";
    }

    print
qq|



<h2 class='mgr-page-title'>Primary Gateway Modules Currently Installed</h2>
<p><br></p>

<p class="well">Below is a list of gateway files installed in the <b>$sc_paygates_dir/</b> sub-directory of your store.  If out of date, you should use the installer/updater tool above for the order library and the settings manager. If not being used, we recommend that you at least delete the order library file using the remove gateway selector above.<br><br><a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&display_upgrade_options=yes">Back to Upgrade manager</a></p>
<p><br></p>

<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr bgcolor="#c0c0c0"><td bgcolor="#c0c0c0"><b>Gateway File Name</b></td>
<td bgcolor="#c0c0c0"><b>Your Version</b></td>
<td bgcolor="#c0c0c0"><b>Gateway Notes</b></td>
<td bgcolor="#c0c0c0"><b>Status</b></td></tr>
|;

    for my $keys ( sort keys(%instgversions) ) {
        my $tempthingy = "$upnotes{$keys}";
        if ( $upnotes{$keys} eq "" ) { $tempthingy = '&nbsp;'; }
        print
qq~<tr><td>$keys</td><td>$instgversions{$keys}</td><td>$tempthingy</td><td>
~;
        if ( $updatesAvailable{$keys} eq '' ) {
            print
"<font size=-1><center>Non-Standard Version</center></font></td></tr>";
        }
        elsif ( $instgversions{$keys} lt $updatesAvailable{$keys} ) {
            print
qq~  <font size=-1><div align=center>update to:<br>$updatesAvailable{$keys}<br></div></font></td></tr>~;
        }
        else {
            print
"<font size=-1><center>Installed</center></font></td></tr>";
        }

    }
    print "</table><p><br><br><br><br></p>\n";

    print &$manager_page_footer;

    call_exit();
}

#######################################################################

1;
