#!/usr/bin/perl

BEGIN {
    use lib qw(./TZM /var/www/turizm.ru/COMMON/Lib );
}

#use diagnostics;
use CGI qw(header param);

use POSIX qw(strftime mktime locale_h);
use Data::Dumper;

# Список модулей, которые могут обрабатывать чпу урлы

use Benchmark;
use strict;
use TZM::Client;    # 2.3;
use TZM::AdmClient;
use TZM::AdmClientTemplate;
use TZM::AddTemplate 1.11;
use TZM::my_GetParam;
use TZM::Cache;
use TZM::ProductiveStat;
use TZM::LastModify;
use Cache::FileCache;
use constant PAGE404 => '/var/www/tzm.ru/missing.html';
use HTTP::Date;
use DateTime;
use Digest::MD5 qw(md5_hex);
use CGI::Util;
use TZM::MasterAgent;
use Encode qw/:all/;
use utf8;

use constant PAGE_LIMIT =>
  10;    # В поиске туров ограничение на количество страниц
use TZM::GeoTargeting;

my $LM        = TZM::LastModify->new();
my $Header_LM = $LM->check( \%ENV );

my $q  = new CGI();
my $t0 = Benchmark->new;

my @user_geoinfo = TZM::GeoTargeting::get_user_geoinfo();

use locale;

#&setlocale( LC_CTYPE, "ru_RU.CP1251" );
use vars qw(%MODIFIED);
reread_conf('TZM/TmpConfig.pm');

reread_conf('TZM/TourConfig.pm');
my ( $IS_MOSCOW_OFFICE, $IS_MO_OFFICE );

if ( $user_geoinfo[0] ) {
    $IS_MOSCOW_OFFICE =
      TZM::GeoTargeting::is_equal_region( 1, $user_geoinfo[0]->[0] );
    $IS_MO_OFFICE =
      TZM::GeoTargeting::is_equal_region( 164, $user_geoinfo[0]->[0] );
}

my ( $index, $i, $ii, $t, $title, $page, $ou, $mess, $tmp, $param );
my ( $def_param, $src_param, $rc ) = ( undef, undef, 0 );
my $ref = [];
my %headers_out;

my $status;

#fix для If-Modified-Since
my $datetime = '';

# my $add_search_param={};
my $add_search_param = undef;

my $maxitems = 10;
my $special  = undef;
my @result   = ();
my @tmp      = ();
my @pages    = ();
my $google_id;
$google_id = $q->cookie('__utma');

for ($google_id) {
    /^\d+\.(\d+)/;
    $_ = $1;
}

my @all_params = map { split '&', $_ } @ARGV;
my %params     = map { split '=', $_ } @all_params;

foreach my $k ( keys %params ) {
    $q->param( -name => $k, -value => $params{$k} );
}

my $r1;
my $progress;
my $json = $q->param('json');
my $p    = new TZM::my_GetParam;
my $co   = new TZM::Client($q);
my $co2  = new TZM::AdmClient($q);
my $tpl  = new TZM::AddTemplate( $co, co2 => $co2 );
my $tpl2 = new TZM::AdmClientTemplate($co2);
$co->{DOMAIN}    = $tpl2->{DOMAIN};
$co->{DOMAIN_DB} = $tpl2->{DOMAIN_DB};
my $DOMAIN    = $co->{DOMAIN};
my $DOMAIN_DB = $co->{DOMAIN_DB};
$tpl->check_allow_show_page();

my %tmp = $q->Vars;
$tmp{Kat}  = ( join ',', $q->param('Kat') );
$tmp{Food} = ( join ',', $q->param('Food') );

my $tmp = Dumper( \%tmp );
my $tmp_md5 =
  md5_hex( $ENV{HTTP_HOST} . "_"
      . $ENV{REQUEST_URI} . "_"
      . $tpl->{allow_show_page} . "_"
      . $tmp . "_"
      . $user_geoinfo[0]->[0] );
my $index_key = "index_" . $tmp_md5;

my $index_cache = TZM::Cache->hot_cache();
my $nohead;

eval {
    $index = $index_cache->get($index_key)
      unless $ENV{REQUEST_URI} =~ /search/;
};

unless ( $index && !TZM::Cache::_check_developer_place() ) {
    my $pStat = new TZM::ProductiveStat( co => $co, tpl => $tpl );
    $tpl->{tpl}->assign(
        IS_MOSCOW_OFFICE => $IS_MOSCOW_OFFICE,
        IS_MO_OFFICE     => $IS_MO_OFFICE,
        GEO_REGION_ID    => $user_geoinfo[0]->[2],
        ALLOW_SHOW_PAGE  => $tpl->{allow_show_page}
    );
    $co->{IS_MOSCOW_OFFICE} = $IS_MOSCOW_OFFICE;
    $co->{user_geoinfo}     = \@user_geoinfo;
    $tpl->{user_geoinfo}    = \@user_geoinfo;
    if ( $ENV{REQUEST_URI} =~ /from=yatour/ ) {
        $ENV{REQUEST_URI} =~ /\/tour(.*?)\//;
        my $tour = $1;
        $ENV{REQUEST_URI} =~ /\/(\?from.*?)$/;
        my $qs = $1;
        my $file =
          "" . $ENV{DOCUMENT_ROOT} . "ya_market/tour" . $tour . $qs . "";
        open( FN, "$file" );
        my $data = do { local $/; <FN> };
        close FN;

        if ( $data && $data =~ /<\!DOCTYPE html>/ ) {
            print $q->header( -charset => 'utf-8' );
            print $data;
            exit;
        }
    }

    # Запоминаем IP клиента (или фронтенда?)
    $co->{CLIENT_IP} = $ENV{REMOTE_ADDR} || '';

    $tpl->{tpl}->assign(
        HIDE_START => ' <!-- ',
        HIDE_END   => ' --> ',
    );
    $tpl->{tpl}->assign( GEO_OFFICE_ID => $user_geoinfo[0]->[0] )
      if @user_geoinfo;
    $p->define( def => $co->{'DefaultParam'} );
    $def_param = $p->get_param('def');
    $p->define( src => $co->{'TamaParam'} );

    $co->{TmpConf}  = \%TZM::TmpConfig::TMPCONF;
    $co->{TourConf} = \%TZM::TourConfig::ADVICECONF;

    my %data_params;

    %data_params = \%tmp;
    $src_param   = \%tmp;

    my $pagego = $q->param('Page') || 1;
    my $MorePage = $q->param('MorePage');

    if ( $q->param('MorePageStop') ) {
        $src_param->{'MorePageStop'} = $q->param('MorePageStop');
    }
    if ($MorePage) { $src_param->{'MorePage'} = $MorePage }
    $i  = 0;
    $ii = 1;

    #Для манагеров
    my $cookie         = $q->cookie('tzmuser');
    my $session_cookie = $q->cookie('tzmsession');

    #my $tracking = new TZM::Tracking;
    #$tracking->track_user(CGI => $q);

    my $login  = $q->param('login');
    my $passwd = $q->param('passwd');

    $tpl2->{logon} = {};
    $tpl2->user_auth(
        {
            login          => "$login",
            passwd         => "$passwd",
            user_cookie    => "$cookie",
            session_cookie => "$session_cookie"
        }
    );
    $tpl->{logon} = $tpl2->{logon};

    #die $tpl->{logon}->{session}.'!!!';
    $cookie = $tpl2->{logon}->{session};
    $co->{cookie} = $cookie;
    my @add_params;

#############################################################################################################################################################################################
    if ( $ENV{REQUEST_URI} =~ /act=viewinfo\&Tour=(\d+)\&spec=1/ ) {
        die "!!!/act=viewinfo\&Tour=(\d+)\&spec=1/";
    }
    elsif ( $ENV{REQUEST_URI} =~ /act=viewinfo1\&Tour=(\d+)/ && !$ENV{A9} ) {
        die "!!!/act=viewinfo1\&Tour=(\d+)/";
    }
    elsif ( $ENV{REQUEST_URI} =~ /act=search\&Country=(61|54)\&ctours=1$/ ) {
        die "!!!/act=search\&Country=(61|54)\&ctours=1$/";
    }
    elsif ( $ENV{REQUEST_URI} =~ /(.+?)\/\?page=1$/ ) {
        die "!!!/(.+?)\/\?page=1$/";
    }

    if ( $q->param("gen_right_only") ) {
        die "!!!gen_right_only";
    }
    else {
        if ( $q->param('act') eq "holiday" ) {
            die "!!!holiday";
        }
        elsif ( $q->param('act') eq "currency" ) {
            die "!!!currency";
        }
        elsif ( $q->param('act') eq 'cardtour' ) {
            die "!!!cardtour";
        }
        elsif ( $q->param('act') eq 'countries_reports' ) {
            die "!!!countries_reports";
        }
        elsif ( $q->param('act') eq 'vip' ) {
            die "!!!vip";
        }
        elsif ( $q->param('act') eq 'wedding' ) {
            die "!!!wedding";
        }
        elsif ( $q->param('act') eq 'multi_landing' ) {
            die "!!!multi_landing";

            #lp
            require TZM::ClientTemplate::MultiLanding;
            my $tpl2 = new TZM::ClientTemplate::MultiLanding( cfg => $co );
            $index = $tpl2->generator();
        }
        elsif ( $q->param('act') eq 'poezd' ) {
            die "!!!poezd";
        }
        elsif ( $q->param('act') eq 'shopping' ) {
            die "!!!shopping";
        }
        elsif ( $q->param('act') eq 'weekend' ) {
            die "!!!weekend";
        }
        elsif ( $q->param('act') eq 'weekendfrom' ) {
            die "!!!weekend_form";
        }
        elsif ( $q->param('act') eq 'individ' ) {
            die "!!!individ";
        }
        elsif ( $q->param('act') eq 'subscribe_hot' ) {
            die "!!!subscribe_hot";
        }
        elsif ( $q->param('act') eq 'manager_profile' ) {
            die "!!!manager_profile";
        }
        elsif ( $q->param('act') eq 's_offers' ) {
            die "!!!s_offers";
        }
        elsif ( $q->param('order_form') == 1 ) {
            die "!!!order_form";
        }
        elsif ( $q->param('tourSearch') == 1 ) {
            die "!!!tourSearch";
        }
        elsif ( $q->param('act') eq "avia_charter" ) {
            die "!!!avia_charter";
        }

        elsif ( $q->param('act') eq "bad_tour" && $cookie ) {
            die "!!!bad_tour";
        }

        elsif ( $q->param('icq_outside') ) {
            die "!!!icq_outside";
        }

        elsif ( $q->param('bonus_bank') ) {
            die "!!!bonus_bank";
        }

        elsif ( $q->param('bookingcenter') ) {
            die "!!!bookingcenter";
        }

        elsif ( $q->param('catalog') ) {
            die "!!!catalog";
        }

        elsif ( $q->param('act') eq "charter" ) {
            die "!!!charter";
        }

        elsif ( $q->param('act') eq 'turoperatory_po_gorodam' ) {
            die "!!!turoperatory_po_gorodam";
        }

        elsif ( $q->param('act') eq "country_code" ) {
            die "!!!country_code";
        }
        elsif ( $q->param('act') eq "newyear" ) {
            die "!!!newyear";
        }
        elsif ( $q->param('act') eq "tourtypesection" ) {
            die "!!!tourtypesection";
        }
        elsif ( $q->param('act') eq 'search_form_country' ) {
            die "!!!search_form_country";

        }
        elsif ( $def_param->{act} eq 'search' ) {
            die "!!!search";
        }

        elsif ( $def_param->{act} eq 'hots' ) {
            die "!!!hots";
        }

        elsif ( $def_param->{act} eq 'discount' ) {

            die "!!!discount";
            #Perepisivaet A Pavlov 
            #Переделал на api.1001tur.ru/discount/ 

            $title = "Дисконтные карты";
            $ou    = 1;

            my $xml_param = ();
            $tmp =
"SELECT name FROM DiscountCard WHERE cardId='$src_param->{cId}' AND email='$src_param->{email}'";

            if (
                (
                       $co2->from_database( '', $tmp )
                    && $src_param->{cId}
                    && $src_param->{email}
                )
                || ( $src_param->{cId} && $q->param('output') eq 'xml' )
              )
            {
                if ( $q->param('check') == 1 ) {
                    $tmp =
"SELECT balance FROM DiscountCard  WHERE cardId='$src_param->{cId}'";
                    my @tmp1 = $co->from_database( '', $tmp );
                    if (@tmp1) {
                        $xml_param->{check}   = 1;
                        $xml_param->{balance} = $tmp1[0]->[0];
                    }
                    else {
                        $xml_param->{check} = 0;
                    }
                }
                elsif ( $q->param('add') == 1 ) {
                    my $ma = TZM::MasterAgent->new();
                    my $u  = {
                        disc_check  => $q->param('cId'),
                        phone       => $q->param('cId'),
                        lastname    => $q->param('lastname'),
                        name        => $q->param('name'),
                        patronymic  => '',
                        gender      => 'M',
                        birthday    => $q->param('birthday') || '0000-00-00',
                        office_id   => 333,
                        mailcity    => ( $q->param('city') || '' ),
                        mailaddress => '',
                        email       => $q->param('email'),
                        mailindex   => '',
                        pasport     => ''
                    };


                    my $t = {
                        samo_manager    => 'Нормочекер',
                        office_id       => '18',
                        manager_id      => '422',
                        no_touch_system => $q->param('no_touch_system') || 0
                    };

                    if ( length( $u->{disc_check} ) == 10 ) {
                        my ( $order, $xz ) = $ma->add_user_card( $u, $t );
                        if ($order) {
                            $xml_param->{status}  = 1;
                            $xml_param->{message} = 'All good';
                        }
                        else {
                            $xml_param->{status}  = 0;
                            $xml_param->{message} = 'Invalid add';
                        }
                    }
                    else {
                        $xml_param->{status}  = 0;
                        $xml_param->{message} = 'Mobile number requred';
                    }
                }
                elsif ( $q->param('add_bonus') ) {
                    my %t = (
                        samo_manager => 'Нормочекер',
                        office_id    => '18',
                        manager_id   => '422'
                    );
                    my $cardId = $q->param('cId');
                    my $ma     = TZM::MasterAgent->new();

                    if ( length($cardId) == 10 && $q->param('sum') ) {
                        $ma->add_bonus( $cardId,
                            $q->param('operation') || 'anketa',
                            '0', $q->param('sum'), 'Нормочекер', '18', 422 );
                        $xml_param->{status}  = 1;
                        $xml_param->{message} = 'All good';
                    }
                    else {
                        $xml_param->{status}  = 0;
                        $xml_param->{message} = 'Mobile number and sum requred';
                    }
                }
                elsif ( $q->param('get_full_info') == 1 ) {
                    $tmp =
"SELECT balance, nulldate, email, cardId `exists` from DiscountCard where cardId=?";
                    my @dc =
                      $co->from_database( '', $tmp, 5, undef,
                        $src_param->{cId} );
                    if (@dc) {
                        foreach ( keys %{ $dc[0] } ) {
                            $xml_param->{$_} = $dc[0]->{$_};
                            $xml_param->{$_} =~ s/^\s+|\s+$//g;

                        }
                    }
                }
                else {
                    my $where = '';
                    my @vals;
                    $tmp =
"SELECT SUM(income) FROM DiscountCardUsers  WHERE cardId='$src_param->{cId}'";
                    my @tmp1 = $co->from_database( '', $tmp );
                    if (@tmp1) {
                        $src_param->{balance} = $tmp1[0]->[0];
                    }
                    else {
                        $src_param->{balance} = 0;
                    }

                    $tmp =
"SELECT SUM(outlay) FROM DiscountCardOutlay  WHERE cardId='$src_param->{cId}'";

                    @tmp1 = $co2->from_database( '', $tmp );
                    if (@tmp1) {
                        $src_param->{balance} -= $tmp1[0]->[0];
                    }
                    else {
                        $src_param->{balance} -= 0;
                    }

                    $src_param->{balance} =
                      sprintf( "%.2f", $src_param->{balance} || '0' );

                    $xml_param->{balance} = $src_param->{balance};
                }

#$src_param->{balance} = ($co->from_database('',"select balance from DiscountCard WHERE cardId='$src_param->{cId}'" ))[0]->[0];
            }
            else {
                $ou = 2;
            }

            #die $ou;
            #die Dumper($src_param);
            if ( $q->param('output') eq 'xml' ) {
                print "Content-Type: text/xml; charset=utf-8\n\n";
                print '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
                print '<data>';
                foreach ( sort keys %{$xml_param} ) {
                    print '<'
                      . $_ . '>'
                      . $xml_param->{$_} . '</'
                      . $_ . '>' . "\n";
                }
                print '</data>';
                exit;
            }
            else {
                $index = $tpl->gen_discount( $title, $ou, $mess, $src_param );
            }

            #-------007--------
            $p->clear('src');
        }

        elsif ( $q->param('act') eq 'birthday' ) {
            die "!!!birthday";
        }

        elsif ( $q->param('act') eq 'opinion' ) {
            die "!!!opinion";
        }

        elsif ( $q->param('act') eq 'opinion_country' ) {
            die "!!!opinion_country";
        }

        #16.11.2009 11:17:58 Angel: Предложения по московским офисам
        elsif ( $q->param('act') eq 'day_offer' ) {

            die "!!!day_offer";
        }
        elsif ( $q->param('act') eq 'spec_day_offer' ) {
            die "!!!spec_day_offer";
        }

        elsif ( $q->param('act') eq 'disable_email' ) {

            die "!!!disable_email";
        }

        elsif ( $q->param('act') eq 'europe_tours' ) {
            die "!!!europe_tours";
        }

        #17.08.2010 14:27:04 Angel: Выводим информацию о региональном офисе
        elsif ( $q->param('act') eq 'page'
            && ( $q->param('id') or $q->param('name') ) )
        {

            die "!!!page";
            $index = $tpl->gen_reg_page();
        }

        #region page
        elsif ( $q->param('act') eq 'reg_page' )
        { # && $q->param('reg_id'), если нет reg_id - выводим все регионы на одну страницу
            die "!!!reg_page";
            $index       = $tpl->gen_region_page();
            %headers_out = %{ $tpl->{headers_out} }
              if ref $tpl->{headers_out} eq 'HASH';
            if ($index) {
                $pStat->add_item('contacts');
            }
        }

        elsif ( $q->param('act') eq 'reg_page_team' && $q->param('reg_id') ) {
            die "!!!reg_page_team";
        }

        elsif ( $q->param('act') eq 'news_view' && $q->param('id') ) {
            die "!!!news_view";
        }

        elsif ( $q->param('act') eq 'add_email' && $q->param('mail') ) {
            die "!!!add_email";
        }

        elsif ( $q->param('act') eq 'sddd' ) {
            die "!!!sddd";
        }
        elsif ( $q->param('act') eq 'tour_booking' ) {
            die "!!!tour_booking";
        }

        elsif ( $q->param('act') eq 'franch' ) {
            die "!!!franch";

            #priority.htm
            if ( $q->param('subact') eq 'send' and $tpl->send_franch_verify ) {
                $index = $tpl->send_franch_send();
            }
            else {
                $index = $tpl->send_franch_form( $q->param('razdel') );
            }
        }

        elsif ( $q->param('act') eq 'mskbron' ) {
            die "!!!mskbron";
        }

        elsif ( $q->param('act') eq 'news' ) {
            die "!!!news";
        }

        elsif ( $q->param('act') eq 'reviews' ) {
            die "!!!reviews";
            if ( $q->param('subact') eq 'send' and $tpl->send_reviews_verify ) {
                $index = $tpl->send_reviews();
            }
            else {
                $index = $tpl->view_reviews( $q->param('razdel') );
            }
        }

        elsif ( $q->param('act') eq 'opros' ) {
            die "!!!opros";
        }

        elsif ( $def_param->{act} eq 'return' ) {
            die "!!!return";
        }

        elsif ( $q->param('act') eq 'speclist' ) {
            die "!!!speclist";
        }

        elsif ($def_param->{act} eq 'viewinfo'
            || $def_param->{act} eq 'selectdate' )
        {
            die "!!!viewinfo selectdate";
        }

        elsif ( $q->param('act') eq 'order_custom_lowprice' ) {
            die "!!!order_custom_lowprice";
        }
        elsif ( $def_param->{act} eq 'gen_hotels' ) {
            die "!!!gen_hotels";
        }

        elsif ( $q->param('act') eq 'installment' ) {
            die "installment'";
        }

        elsif ( $q->param("act") eq "searest" ) {
            die "!!!searest";
        }

        elsif ( $q->param("act") eq "search_form_only" ) {
            die "!!!search_form_only";
        }

        elsif ( $q->param("act") eq "all_country_list" ) {
            die "!!!all_country_list";
        }

        elsif ( $q->param("act") eq "pressrelease" ) {
            die "!!!pressrelease";
        }

        elsif ( $q->param('act') eq 'credit-form' ) {
            die "!!!credit-form";
        }
        elsif ( $q->param('act') eq 'wrapper' ) {
            die "!!!wrapper";
        }

        elsif ( $q->param('act') eq 'metro' ) {
            die "!!!metro";
            my $metro  = $q->param('station');
            my $office = $co->get_office_by_metro($metro)->fetchrow_hashref;
            my $two_office;
            unless ( $$office{'office_id'} ) {

                my $firstoffice =
                  $co->get_first_office($metro)->fetchrow_hashref;
                my $nextoffice =
                  $co->get_nearest_office_by_metro($metro)->fetchrow_hashref;

                my $of_st = $$office{'station_number'};
                my $fr_st = $$firstoffice{'station_number'};
                my $nr_st = $$nextoffice{'station_number'};

                my $st_min = $of_st - $fr_st;
                my $st_max = $nr_st - $of_st;

                if ( $st_min <= $st_max ) {
                    $two_office = $firstoffice;
                }
                else {
                    $two_office = $nextoffice;
                }
            }
            unless ( $$office{'name'} ) {
                $office =
                  $co->get_office_by_metro( $metro, 'fake' )->fetchrow_hashref;
            }

            my %meta = (
                'keywords' => $$office{'name'}
                  . ', Москва, туры, путевки, отдых',
                'description' => 'Ближайший офис 1001 Тура к станции '
                  . $$office{'name'},
            );

            $index = $tpl->gen_index(
                "Комфортная покупка туров, путевок около станции "
                  . ( $$office{'name'} || $$office{'outer_name'} )
                  . ". Продажа подарочных сертификатов на туры и билеты",
                1,
                '',
                '',
                ${ $tpl->gen_metro_office_item( $office, $two_office ) },
                0,
                \%meta
            );

        }

        elsif ( $q->param('act') eq 'article' && $q->param('page') ) {
            die "!!!article";
        }
        elsif ( $q->param('act') eq 'mod_page' ) {
            die "!!!mod_page";

            #Jdem Alinu
            my $separator = ( $ENV{DOCUMENT_ROOT} =~ /\/$/g ? '' : '/' );

            my $file =
              $ENV{DOCUMENT_ROOT} . $separator . 'new_design_tpl/domain.prefix';

            warn "!!!mod_page - "
              . $ENV{DOCUMENT_ROOT}
              . $separator
              . $q->param('file');

            if ( -e $file ) {

                open( FN, "<$file" );
                my $prefix = <FN>;
                close FN;

                if ($prefix) {

                    my $file =
                      $ENV{DOCUMENT_ROOT} . $separator . $q->param('file');

                    my $content;

                    if ( -e $file ) {
                        open( FN, "<$file" );
                        while (<FN>) { $content .= $_; }
                        close FN;
                        $index = \$content;
                    }
                    else {
                        gen_404();
                    }
                }
                else {
                    gen_404();
                }
            }
            else {
                gen_404();
            }
        }
        else {
#############################################################################################################################################################################################
            # Редиректы для Талханаева
            if ( $ENV{QUERY_STRING} =~ /wecall\=1|Search\=1/ ) {
                print
"Status: 301 Moved Permanently\nLocation: http://www.1001tur.ru/\n\n";

                #   $q->redirect(
                #			-url => $tpl->redirect301_url($1),
                #			-nph => 1,
                #			-status => 301
                #	 );
                $co->blah;
                $tpl->blah;
                exit;
            }

            my $ip = $ENV{HTTP_X_REAL_IP} || $ENV{REMOTE_ADDR} || '127.0.0.1';
            my $office_id = $co->get_office_by_ip($ip);

            $title = "ПОИСК ТУРА";
            $ou    = 0;
            $index = $tpl->gen_index( $title, $ou, $mess, '' );
        }

    }

    $index_cache->set( $index_key, $index, '3600' );
}
else {
    warn "we in cache";
}

my $md5_check;
eval { $md5_check = md5_hex($$index); };
if (   $md5_check
    && $LM->get_val( $ENV{HTTP_HOST}, $ENV{REDIRECT_URL}, 'md5' ) ne
    $md5_check )
{
    $Header_LM = $LM->set_lu(
        url => ( join '', $ENV{HTTP_HOST}, $ENV{REDIRECT_URL} ),

        #           LU  => $lu,
        md5   => $md5_check,
        table => 'index',

        #           id   => $tmp_md5
    );
    warn "save";
}
$Header_LM = CGI::Util::expires("now") unless $md5_check;
### /normal mode ###
$status = '404 Not Found'
  if ( !$index or index( $$index, '<!--404-->' ) != -1 )
  ;    # Пока только для майских праздников

if ( $headers_out{status} == 301 || $headers_out{status} == 404 ) {
    print "Status: $headers_out{status}\n";
    if ( $headers_out{location} ) {
        if ( $headers_out{location} =~ m|http://| ) {
            print "Location: " . $headers_out{location} . "\n";
        }
        else {
            print "Location: http://$ENV{HTTP_HOST}$headers_out{location}\n";
        }
    }
    print "\n";
    exit;
}

#fix for last modify

my $ims = $ENV{'HTTP_IF_MODIFIED_SINCE'};
$ims =~ s/;.*//;    # for Netscape 4
$ims = str2time($ims);
my $imst;

if ( $datetime =~ /(\d+)-(\d+)-(\d+)/ ) {
    my $dt_new = DateTime->new(
        year      => $1,
        month     => $2,
        day       => $3,
        time_zone => 'GMT',
    );
    $imst = $dt_new->epoch;
}

if ( $q->param('json') eq '1' ) {
    print "Access-Control-Allow-Origin: *\n";
    print "Access-Control-Allow-Methods: GET, POST, PUT\n";
    print "Access-Control-Allow-Headers: X-Custom-Header\n";
    print "Content-Type: text/javascript; charset=utf-8\n\n";
}
elsif ( $tpl->{page_no_cache} )
{    # При необходимости не кешировать страницу в браузере
    print
qq~Content-type: text/html; charset=utf-8\nExpires: Mon, 26 Jul 1997 05:00:00 GMT\nCache-Control: no-cache, must-revalidate\nPragma: no-cache\n$tpl->{set_cookie}\n~;
}
elsif ( $ims && $imst && $imst <= $ims and !$q->cookie('user1001') ) {

    warn "we in 304";
    print "Status: 304 Not Modified\n\n";
    exit;
}
elsif ( $q->param('export_csv') ) {
    my $msg = '';
    $msg .= "Content-Type: application/vnd.ms-excel\n";
    $msg .= "Content-Disposition:attachment;filename=result.csv\n";
    $msg .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\n";
    $msg .= "Cache-Control: no-cache, must-revalidate\n";
    $msg .= "Pragma: no-cache, must-revalidate\n";
    print "$msg\n";
}
else {

    #    $datetime = time2str(time());
    if ( !$q->param('nohead') && $status !~ /404/ && !$nohead ) {
        $tpl->step_testing( $index, $co2 );

        unless ( $q->cookie('user1001') ) {

            print $q->header(
                -type          => 'text/html; charset=utf-8',
                -status        => $status,
                -COOKIE        => $tpl->{cookies},
                -last_modified => $Header_LM ? $Header_LM : time2str( time() )
            );

        }
        else {
            print $q->header(
                -type          => 'text/html; charset=utf-8',
                -status        => $status,
                -COOKIE        => $tpl->{cookies},
                -cache_control => 'no-cache, must-revalidate',
            );
        }
    }
}

if ( $status =~ /404/ ) {
    gen_404();
}
elsif ( !$status || $ENV{HTTP_HOST} !~ /^www\./ ) {
    $tpl->parse_Includes($index);
    develop_urls($index);
    my $t1 = Benchmark->new;

    my $diff = timediff( $t1, $t0 );
    my $full_bench = timestr($diff);
    $tmp =~ s/\n//g;
    $tmp =~ s/\r//g;
    $tmp =~ s/\s//g;
    warn "TM-$ENV{SERVER_NAME} $ENV{REQUEST_URI},$full_bench,$tmp";

    if ($index) {
        Encode::_utf8_off($$index) if $json;
        print $$index;
    }
    else {
        gen_404();
    }
}

# Clean up;
$tpl->blah;
$co->blah;

############ SUBROUTINE ONLY!!!!!!!!!!!! Reload config files unde mod_perl ##############

sub gen_404 {
    my $datetime = time2str( time() );
    print
"Status: 404 Not Found\nContent-type: text/html; charset=utf-8\n\n";
    open( FILE, PAGE404 );
    print while (<FILE>);
    close(FILE);
    exit;
}

#Простановка урлов для тестовой площадки
sub develop_urls {
    my $content = shift;
    my $separator = ( $ENV{DOCUMENT_ROOT} =~ /\/$/g ? '' : '/' );
    my $file =
      $ENV{DOCUMENT_ROOT} . $separator . 'new_design_tpl/domain.prefix';
    my $file_task =
      $ENV{DOCUMENT_ROOT} . $separator . 'new_design_tpl/task.prefix';
    my $file_sub =
      $ENV{DOCUMENT_ROOT} . $separator . 'new_design_tpl/subdomain.prefix';
    my $task;
    my $sub;
    if ( -e $file_task and -e $file_sub ) {
        open( FN, "<$file_task" ) or die $!;
        $task = <FN>;
        close FN;

        open( FN, "<$file_sub" ) or die $!;
        $sub = <FN>;
        close FN;
    }

    #if ( -e $file ) {
    #open( FN, "<$file" ) or die $!;
    #my $prefix = <FN>;
    #close FN;
    my $prefix = 'www';
    if ( $prefix and $prefix ne 'www' ) {

        $prefix =~ s/\s//g;
        if ( $task and $sub ) {

            #Сначало поддомены
            $task =~ s/\s//g;
            $sub =~ s/\s//g;

            $$content =~
              s/(?![www|$prefix])(\w+)\.1001tur/${task}$1\.${sub}1001tur/mg;
        }
        else {

            #Сначало поддомены
            $$content =~
              s/(?![www|$prefix])(\w+)\.1001tur/$1\.$prefix\.1001tur/g;

        }

        #Основной домен

        $$content =~ s/www\.1001tur/$prefix\.1001tur/mg;

    }

    #}
    #else {
    #    die $file;
    #}

}

sub reread_conf {
    my $file = shift;
    return unless defined $file;
    return unless -e $file and -r _;
    my $mod = ( stat $file )[9];
    unless ( $MODIFIED{$file} and $MODIFIED{$file} == $mod ) {
        my $result;
        unless ( $result = do $file ) {
            warn "couldn t parse $file: $@" if $@;
            warn "couldn t do $file: $!" unless defined $result;
            warn "couldn t run $file" unless $result;
        }
        $MODIFIED{$file} = $mod;    # Update the MODIFICATION times
    }
    return 1;
}

sub redirect_301 {
    my $URI = shift;
    print "Status: 301 Moved Permanently\nLocation: http://"
      . $ENV{HTTP_HOST}
      . $URI . "\n\n";
    $co->blah;
    $tpl->blah;
    exit;

}

1;

