#!/usr/bin/perl -T
$versions{'agora.cgi'} = '06.6.00.0005';

# Route 66 - Legacy Compatibility Version
#######################################################################
#
# 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.
#
#######################################################################

BEGIN { use lib 'system66/perl_modules'; unshift( @INC, 'system66/perl_modules' ); }

use Encode;
use CGI::Simple::Standard qw(:cgi-lib :core :misc :cookie -autoload);
use Locale::Country;

$| = 1; # Flush
$ENV{"PATH"} = "/bin:/usr/bin";
$time = time;
$main_program_running = 'yes';
( $sc_global_bot_tracker, $cart_id ) = q{};
$sc_agoracart_platform = 'Route66';
( $TABLET, $MOBILE ) = q{}; # mobile and tablet device constants
$use_seo_toggle = q{}; # toggle to allow certain SEO oriented URL parameters to be used
%form_data;
%cookie;
$sc_special_checkout_variable1 =  q{}; # reserved for random key generation
$sc_special_checkout_variable3 = q{}; # available
$sc_special_misc_variable1  = q{};
$sc_special_misc_variable2  = q{};
$sc_special_misc_variable3  = q{};
( $sc_header_printed, $sc_ask_for_return, $sc_gateway_count, $gateway_row_remainder ) = 0;
( $sc_header_status, $sc_test_data_to_print, $cartlinks ) = q{};
( $cookie, $cookie2 ) = q{};
$are_any_query_fields_filled_in = 'no';
$sc_visitor_http_user_agent = $ENV{"HTTP_USER_AGENT"};
$sc_visitor_http_user_agent =~ s/[\=\.\/\(\)\,\;\:\+\-\_\s]+//g;
$gateway_row_cells_needed = 1;
( $gateway_choice_last_cell_div, $gateway_choice_normal_cell_div ) = q{};

eval q~
     use HTTP::BrowserDetect;
     my $browser = HTTP::BrowserDetect->new($ENV{"HTTP_USER_AGENT"});
     if ( $browser->tablet() ) {
         $TABLET = 1;
     }
     elsif ( $browser->mobile() ) {
         $MOBILE = 1;
     }
     if ( $browser->robot() ) {
         $sc_global_bot_tracker = '1';
     }
     $sc_visitor_browser_string = $browser->browser_string().'/'.$browser->version();
~;

require_supporting_libraries( __FILE__, __LINE__,
    './system66/library/common_subroutines.pl',
    './system66/library/dates.pl',
    './system66/library/infosec.pl',
    './system66/library/cookies_sessions_cart_ids.pl',
    './system66/library/misc_core.pl',
    './system66/library/log_and_error_subroutines.pl',
    './system66/library/starter_routines.pl',
    './user_config66/cart/agora_user_lib.pl',
    './system66/library/tags_and_tokens.pl',
    './system66/cart/cart_formatters.pl',
    './system66/library/startup_sys_2.pl'
);

# language defaults if missing
if ( $sc_lang_path eq '' ) { $sc_lang_path = 'eng_us'; }
if ( $sc_html_lang eq '' ) { $sc_html_lang = 'en'; }
if ( $sc_lang_id eq '' ) { $sc_lang_id = 1; }
if ( $sc_store_id eq '' ) { $sc_store_id = '0'; }

# used at indexer in *form_data
$sc_subcat_title_name = $sc_subcat_index_field . '_for_title';

require_supporting_libraries( __FILE__, __LINE__,
    './system66/library/agora_setup.pl' );
require_supporting_libraries( __FILE__, __LINE__,
    "$sc_lib_dir/loader_routines.pl" );

require_supporting_libraries( __FILE__, __LINE__, "$sc_lang_dir/$sc_lang_path/agora_messages.pl");

$sc_template_language_location = "$sc_hedfut_templates_dir/$sc_headerTemplateRoot/$sc_lang_path" . '.inc';
if ( -f $sc_template_language_location ) {
  require_supporting_libraries( __FILE__, __LINE__, "$sc_template_language_location");
}

require_supporting_libraries( __FILE__, __LINE__, "$sc_lang_dir/$sc_lang_path/user_changes_to_language.pl" );

ReadParse(*form_data);
delete( $form_data{'CGI'} ); # delete weirdness from new lib
&xssKiller;
&untaintFormData;

if ( $form_data{'cart_id'} ) {
    &untaintCartID;
}

&browserBarSubmitPrevent;

codehook( 'after_loading_setup_db' );

&startupCart_stepTwo;

codehook('special_navigation');

if ( ( $sc_debug_mode eq 'yes' ) && ( $sc_collect_test_data eq 'yes' ) ) {
    $sc_test_data_to_print .= "\$page = $page<br>\$sc_global_bot_tracker = $sc_global_bot_tracker<br>";
}

# If a blog page request, we do this instead
if ( $form_data{'blog'} ) {
    # load blog files then go to blog - stubbed out for now.
    #require_supporting_libraries( __FILE__, __LINE__, "" );
    #gotoBlog;
    call_exit();
}

# May want to change the header for no-cache under certain circumstances
agora_starter_section();
codehook( 'load_order_lib_before' );
require_supporting_libraries( __FILE__, __LINE__,
    './system66/view/widgets_agorascript.pl',
    "$sc_html_setup_file_path",
    "$sc_order_lib_path" );
codehook( 'load_order_lib_after' );

# Begin - Run cart's ecommerce functions only if not a bot
if ( $sc_global_bot_tracker ne '1' ) {

    if ( $form_data{'display_cart'} ) {
        &print_agora_http_headers();
        &load_product_libs;
        &load_cart_libs;
        display_cart_contents();
        call_exit();
    }
    elsif ( form_check('add_to_cart_button') ) {
        &print_agora_http_headers();
        &load_product_libs;
        &load_cart_libs;
        add_to_the_cart();
        agora_cookie_save();
        call_exit();
    }
    elsif ( $form_data{'modify_cart_button'} ) {
        &print_agora_http_headers();
        &load_product_libs;
        &load_cart_libs;
        display_cart_contents();
        call_exit();
    }
    elsif ( form_check('submit_change_quantity_button') ) {
        &print_agora_http_headers();
        &load_product_libs;
        &load_cart_libs;
        modify_quantity_of_items_in_cart();
        call_exit();
    }
    elsif ( form_check('submit_deletion_button') ) {
        &print_agora_http_headers();
        &load_product_libs;
        &load_cart_libs;
        delete_from_cart();
        call_exit();
    }
    elsif ( form_check('order_form_button') ) {
        &print_agora_http_headers();
        require_supporting_libraries( __FILE__, __LINE__,
            "$sc_display_orderform_path" );
        &load_product_libs;
        &load_cart_libs;
        display_order_form();
        agora_cookie_save();
        call_exit();
    }
    elsif ( $form_data{'clear_order_form_button'} ) {
        &print_agora_http_headers();
        require_supporting_libraries( __FILE__, __LINE__,
            "$sc_display_orderform_path" );
        &load_product_libs;
        &load_cart_libs;
        clear_verify_file();
        #codehook("display_cleared_order_form");
        display_order_form();
        agora_cookie_save();
        call_exit();
    }
    elsif (
              ( ( form_check('submit_order_form_button') ) && $form_data{'order_form'} &&  $form_data{'gateway'} && $form_data{'order_api_mode'} && ( $sc_API_access_gateways_allowed =~ /$form_data{'gateway'}/ ) && ( $sc_API_access_double_check_string =~ /$form_data{'order_api_mode'}/ ) )
              || ( $form_data{'shortcut_button'} && $form_data{'gateway'} && $form_data{'order_api_mode'} && ( $sc_API_access_gateways_allowed =~ /$form_data{'shortcut_button'}/ ) && ( $sc_API_access_gateways_allowed =~ /$form_data{'gateway'}/ ) && ( $sc_API_access_double_check_string =~ /$form_data{'order_api_mode'}/ ) )
            )
           {
        &print_agora_http_headers();
        require_supporting_libraries( __FILE__, __LINE__,
            './system66/checkout/order_paypal_api.pl' );
        process_api_order_form();
        agora_cookie_save();
        codehook('redirect_to_api');
        call_exit();
    }
    elsif ( $form_data{'submit_order_form_button'} ) {
        if ($sc_test_repeat) {

            &print_agora_http_headers();
            require_supporting_libraries( __FILE__, __LINE__,
                "$sc_display_orderform_path" );
            &load_product_libs;
            &load_cart_libs;
            display_order_form();
        }
        else {
            &print_agora_http_headers();
            require_supporting_libraries( __FILE__, __LINE__,
                './system66/checkout/order_email_helpers.pl',
                './system66/checkout/order_processing.pl' );
            &load_product_libs;
            &load_cart_libs;
            process_order_form();
        }
        agora_cookie_save();
        call_exit();
    }

}
# End - Run cart's ecommerce functions only if not a bot

if ( (
        $page
        || $search_request # outmoded?
        || $form_data{'continue_shopping_button'}
        || $are_any_query_fields_filled_in eq 'yes'
      )
      && ( $form_data{'return_to_frontpage_button'} eq '' )
  )
  {
    if ( ( (  $form_data{'continue_shopping_button'} ) || (  $form_data{'next'} ) ) && (  $form_data{'product'} eq '' ) ) {
        $form_data{'product'} = ".";
    }
    &load_product_libs;
    #&load_cart_libs;
    $sc_ask_for_return = 1;
    display_products_for_sale();
    if ( $sc_global_bot_tracker ne '1' ) {
        agora_cookie_save();
    }
    call_exit();
}
elsif ( $cartlink ) {
    display_page();
}

$sc_processing_order = 'yes';    # assume unless we fall through
codehook( 'gateway_response' );
$sc_processing_order = 'no';

# If we got here, then just output the front page
output_frontpage();
call_exit();

######################################################################
#                         End of main script
######################################################################

#
#
#
#
#

#######################################################################
#                       Require Supporting Libraries
#######################################################################

# require_supporting_libraries is used to read in some of
# the supporting files that this script will take
# advantage of.
#
# require_supporting_libraries takes a list of arguments
# beginning with the current filename, the current line
# number and continuing with the list of files which must
# be required using the following syntax:
#
# &require_supporting_libraries (__FILE__, __LINE__,
#                               "file1", "file2",
#                               "file3"...);
#
# Note: __FILE__ and __LINE__ are special Perl variables
# which contain the current filename and line number
# respectively.  We'll continually use these two variables
# throughout the rest of this script in order to generate
# useful error messages.

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

sub require_supporting_libraries {

    # The libraries are required by us,so exit if loading error
    local ( $file, $line, @require_files ) = @_;
    local ($require_file);
    request_supporting_libraries( 'warn exit', $file, $line, @require_files );
}

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

sub request_supporting_libraries {

    # The incoming file and line arguments are split into
    # the local variables $file and $line while the file list
    # is assigned to the local list array @require_files.
    #
    # $require_file which will just be a temporary holder
    # variable for our foreach processing is also defined as a
    # local variable.

    local ( $what_to_do_on_error, $file, $line, @require_files ) = @_;
    local ($require_file);

    # Next, the script checks to see if every file in the
    # @require_files list array exists (-e) and is readable by
    # it (-r). If so, the script goes ahead and requires it.

    foreach $require_file (@require_files) {
        if ( -e "$require_file" && -r "$require_file" )
        {    # file is there, now try to require it
            $result =
              eval('require "$require_file"');   # require it in a not-fatal way
            if ( $@ ne "" ) {
                if ( $what_to_do_on_error =~ /warn/i ) {
                    if ( $error_header_done ne 'yes' ) {
                        $error_header_done = 'yes';
                        print $sc_browser_header;
                    }
                    print "<p>$agora_error_message01 $@ $agora_error_message01b  \($ENV{'SERVER_ADMIN'}\)<br></p>";
                }
                if ( $what_to_do_on_error =~ /exit/i ) {
                    call_exit();
                }
            }
        }

        # If not, the scripts sends back an error message that
        # will help the admin isolate the problem with the script.

        else {

            if ( $what_to_do_on_error =~ /warn/i ) {
                if ( $error_header_done ne 'yes' ) {
                    $error_header_done = 'yes';
                    print $sc_browser_header;
                }
                print qq|$agora_error_message02 $require_file at line $line in $file. $agora_error_message02   ($ENV{'SERVER_ADMIN'})<br>\n|;
            }

            if ( $what_to_do_on_error =~ /exit/i ) {
                call_exit();
            }
        }

    } # End of foreach $require_file (@require_files)
}

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