#!/usr/bin/perl

use strict;
use Template;
use CGI::Lite;
use FCGI;
use Compress::Zlib;
use XML::Simple;
use Digest::MD5 qw(md5_hex);
use Digest::SHA qw/sha256/;

require LWP;
require "/www/mine.sk/wow/chat/modules/globals.pm";
require "/www/mine.sk/wow/chat/modules/sqldb.pm";
require "/www/mine.sk/wow/chat/modules/sessions.pm";
require "/www/mine.sk/wow/chat/modules/tt.pm";
require "/www/mine.sk/wow/chat/modules/system.pm";
require "/www/mine.sk/wow/chat/modules/pokec.pm";

my $ret_template = tt::init($globals::fs_dir.'/chat/templates');
my $tt = $ret_template->{template};
my $dbh = sqldb::init($globals::mysql->{database},$globals::mysql->{interface},$globals::mysql->{user}, $globals::mysql->{password});
my $cgi = CGI::Lite->new();
my $xs = XML::Simple->new();


my $request = FCGI::Request();

my $map_qualities = { '0' => '11', '1' => '12', '2' => '13', '3' => '14', '4' => '10', '5' => '9', '6' => '15', };
my $map_backgrounds = { '0' => { 'basic' => '000000', 'lite' => '0C0C0C', 'extra' => '444444', }, '2' => { 'basic' => '111111', 'lite' => '222222', 'extra' => '444444', }, };

my $cities;
$main::get_cities->execute();
my $cities_array = $main::get_cities->fetchall_arrayref({});
foreach (@{$cities_array}) {
   $cities->{$_->{city_id}} = $_;
}
$main::get_cities->finish();

my $jobs;
$main::get_jobs->execute();
my $jobs_array = $main::get_jobs->fetchall_arrayref({});
foreach (@{$jobs_array}) {
   $jobs->{$_->{job_id}} = $_;
}
$main::get_jobs->finish();

my $tv_channels;
#$main::get_tv_channels->execute();
#foreach (@{$main::get_tv_channels->fetchall_arrayref({})}) {
#   $tv_channels->{$_->{name}} = $_->{channel_id};
#}
#$main::get_tv_channels->finish();


$main::get_substitutions->execute();
my $substitutions_id = $main::get_substitutions->fetchall_hashref('id');
$main::get_substitutions->finish();

$main::get_substitutions->execute();
my $substitutions = $main::get_substitutions->fetchall_arrayref({});
$main::get_substitutions->finish();

$main::get_channels->execute();
my $channels = $main::get_channels->fetchall_arrayref({});
$main::get_channels->finish();

my $map_armory_server_id;
$main::get_servers->execute();
foreach my $server (@{$main::get_servers->fetchall_arrayref({})}) {
   $map_armory_server_id->{$server->{server_id}} = $server->{armory_server_id};
}
$main::get_servers->finish();


my $loop_instance = 10000;
while($request->Accept() >= 0) {

   
   $dbh = &sqldb::check($dbh);
   if ($dbh eq 0) {
      warn "sql connection problem";
      print "Location: /chat/static.html\n\n";
      next;

   } else {

      my ($html,$page,$template);
      my $q = $cgi->parse_new_form_data();
      my $c = $cgi->parse_cookies();

      if (!defined($q->{page}) || $q->{page} eq '') {
         $q->{page} = 'blank';
      }

      if (!defined($q->{lang_id}) || $q->{lang_id} !~ /^\d+$/) {$q->{lang_id} = 1;}
      if (defined($q->{'s'})) {
         $q->{'s'} =~ s/\D//gs;
      }

      my $template = $tt->{$q->{lang_id}};


      my $hua = 0;
      if ($ENV{HTTP_USER_AGENT} =~ /MSIE/i) {
         $hua = 1;
      } elsif ($ENV{HTTP_USER_AGENT} =~ /Mozilla/i && $ENV{HTTP_USER_AGENT} !~ /MSIE/i) {
         $hua = 2;
      } elsif ($ENV{HTTP_USER_AGENT} =~ /Opera/i) {
         $hua = 3;
      }

      my $usegzip;
      foreach my $enc ( split( /\s*,\s*/, $ENV{HTTP_ACCEPT_ENCODING} )) {
         $enc =~ s/;.*$//s;
         $usegzip = $enc if ( $enc =~ /^(x-)?gzip$/ );
      }

      my $is_ssl = 0;
      if ($ENV{SERVER_PORT} == 443) {
         $is_ssl = 1;
      }


      my $contenttype = 'text/html';


      my $vars = {
		query => $q, 
		logged => 0,
		cities => $cities,
		cities_array => $cities_array,
		jobs => $jobs,
		jobs_array => $jobs_array,
		encoding => 'utf-8',
		hua => $hua,
		gzip => $usegzip,
		is_ssl => $is_ssl,
		theme_id => 0,
                map_armory_server_id => $map_armory_server_id,
      };

      my ($server_name,$world_status,$auth_status,$web_status,$stamp,$stamp_last_up,$stamp_last_down,$stamp_last_ws,$players,$gamemasters,$vips,$horde,$alliance,$last_state,$limit,$version,$ip,$gm_plevel);


      if (!defined($q->{graph}) || $q->{graph} !~ /^\d+$/) {$q->{graph} = 1;}
      if (!defined($q->{chat}) || $q->{chat} !~ /^\d+$/) {$q->{chat} = 1;}
      if (!defined($q->{sid})) {
         $q->{sid} = sessions::create_session($dbh, { ip => $ENV{REMOTE_ADDR}, }, );
      } else {
         if (sessions::check_duplicate_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, ) ) {
            $q->{sid} = sessions::create_session($dbh, { ip => $ENV{REMOTE_ADDR}, force_sid => $q->{sid}, }, );
         } else {
            my $ret_prolong_session = sessions::prolong_session($dbh, {sid => $q->{sid}, }, );
            my $ret_session = sessions::get_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, server_id => $q->{'s'}, }, );
            if ($ret_session->{ec} == 1) {
               if ($ret_session->{nick_id} != 0) {
                  $vars->{session_id} = $ret_session->{session_id};
                  $vars->{logged} = 1;
                  $vars->{nick_id} = $ret_session->{nick_id};
                  $vars->{nick} = $ret_session->{nick};
                  $vars->{global_level} = $ret_session->{global_level};
                  $vars->{level} = $ret_session->{level};
                  $vars->{chat_rank} = $ret_session->{chat_rank};
                  $vars->{chat_rank_points} = $ret_session->{chat_rank_points};
                  $vars->{pending_chat_rank_points} = $ret_session->{pending_chat_rank_points};
                  $vars->{punish_id} = $ret_session->{punish_id};
                  $vars->{channel_id} = $ret_session->{channel_id};
                  $vars->{server_id} = $ret_session->{server_id};
                  $vars->{guild_server_id} = $ret_session->{guild_server_id};
                  $vars->{incline} = $ret_session->{incline};
                  $vars->{incline_colors} = $ret_session->{incline_colors};
                  $vars->{incline_chat} = $ret_session->{incline_chat};
                  $vars->{show_graph} = $ret_session->{show_graph};
                  $vars->{show_chat} = $ret_session->{show_chat};
                  $vars->{show_info} = $ret_session->{show_info};
                  $vars->{show_guild} = $ret_session->{show_guild};
                  $vars->{guilds_type} = $ret_session->{guilds_type};
                  $vars->{privates_type} = $ret_session->{privates_type};
                  $vars->{privates_size} = $ret_session->{privates_size};
                  $vars->{nicks_panel} = $ret_session->{nicks_panel};
                  $vars->{hold_me_frak} = $ret_session->{hold_me_frak};
                  $vars->{hide_blabla} = $ret_session->{hide_blabla};
                  $vars->{hold_to_nick} = $ret_session->{hold_to_nick};
                  $vars->{reverse_chat} = $ret_session->{reverse_chat};
                  $vars->{fade_in} = $ret_session->{fade_in};
                  $vars->{refresh_id} = $ret_session->{refresh_id};
                  $vars->{graph_id} = $ret_session->{graph_id};
                  $vars->{lines_id} = $ret_session->{lines_id};
                  $vars->{chat_font} = $ret_session->{chat_font};
                  $vars->{ding_change} = $ret_session->{ding_change};
                  $vars->{segregate} = $ret_session->{segregate};
                  $vars->{active_nicks} = $ret_session->{active_nicks};
                  $vars->{mark_messages} = $ret_session->{mark_messages};
                  $vars->{mark_how} = $ret_session->{mark_how};
                  $vars->{autocomplete_nicks} = $ret_session->{autocomplete_nicks};
                  $vars->{show_macros} = $ret_session->{show_macros};
                  $vars->{background} = $ret_session->{background};
                  $vars->{theme_id} = $ret_session->{theme_id};
                  $vars->{import_messages} = $ret_session->{import_messages};
                  $vars->{frame_size} = $ret_session->{frame_size};
                  $vars->{auction_type} = $ret_session->{auction_type};
                  $vars->{show_joins} = $ret_session->{show_joins};
                  $vars->{import_ingame_chat} = $ret_session->{import_ingame_chat};
                  $vars->{wowchat_email} = $ret_session->{wowchat_email};
                  $vars->{wowchat_new_mail} = $ret_session->{wowchat_new_mail};
                  $vars->{doafk} = $ret_session->{doafk};
                  $vars->{afk} = $ret_session->{afk};
                  $vars->{pokec_i9} = $ret_session->{pokec_i9};
                  $vars->{pokec_channel} = $ret_session->{pokec_channel};
                  $vars->{pokec_last_msgid} = $ret_session->{pokec_last_msgid};
                  $vars->{last_action_utime} = $ret_session->{last_action};
                  $vars->{last_no_afk_utime} = $ret_session->{last_no_afk_utime};
                  $vars->{last_action} = &plain_time_format($ret_session->{last_action});
                  $vars->{last_message_id} = $ret_session->{last_message_id};

                  if (defined($c->{'s_'.$ret_session->{nick_id}})) {
#                     warn "!!!!!!! ".$c->{'s_'.$ret_session->{nick_id}};
                  }

               } else {
                  $vars->{session_id} = $ret_session->{session_id};
                  $vars->{logged} = 0;
                  $vars->{theme_id} = 0;
                  $vars->{global_level} = 0;
                  $vars->{level} = 0;
                  $vars->{last_message_id} = 0;
                  $vars->{chat_font} = 2;
                  $vars->{graph_id} = 24;
               }
            } else {
               $vars->{logged} = 0;
               $vars->{theme_id} = 0;
               $vars->{global_level} = 0;
               $vars->{level} = 0;
               $vars->{last_message_id} = 0;
            }

         }
      }



      my $hf = 0;
      my $location = '';
      my $set_cookie = '';



      if ($q->{page} eq 'ajax_logout') {
         $hf = 0;
         $contenttype = 'text/xml';

         $main::get_set_rank_points->execute($vars->{nick_id});
         my $tmp_rank_points = $main::get_set_rank_points->fetchrow_hashref();
         $main::get_set_rank_points->finish();

#warn "         if (defined($tmp_rank_points->{chat_rank}) && defined($tmp_rank_points->{points})) {";

         if (defined($tmp_rank_points->{chat_rank}) && defined($tmp_rank_points->{points}) && $tmp_rank_points->{afk} == 0) {

#warn "main::log_rank_points->execute($vars->{nick_id},$vars->{session_id},$tmp_rank_points->{last_no_afk},$tmp_rank_points->{chat_rank},$tmp_rank_points->{points});";
            $main::log_rank_points->execute($vars->{nick_id},$vars->{session_id},$tmp_rank_points->{last_no_afk},$tmp_rank_points->{chat_rank},$tmp_rank_points->{points});
#warn "main::set_rank_points->execute($vars->{nick_id});";
            $main::set_rank_points->execute($vars->{nick_id});
         }
         my $ret_del_nick_from_session = sessions::del_nick_from_session($dbh, { nick_id => $vars->{nick_id}, sid => $q->{sid}, session_id => $vars->{session_id}, }, );
         my $ret_add_action = system::add_action( { action => 17, session_id => $vars->{session_id}, }, );
                           
#         $set_cookie = 'Set-Cookie: x=1; domain=wow.mine.sk; path=/chat;'."\n";
#         $location = $globals::init_script.'?page=frame&sid='.$q->{sid}.'&s='.$q->{'s'};
         my $ret_disconnect = pokec::disconnect($vars->{pokec_i9});
         $main::set_pokec_i9->execute('',$vars->{nick_id});

         $page = 'ajax_logout';


      } elsif ($q->{page} eq 'channel') {
      
         $hf = 1;
         $page = 'channel';

         if ($q->{devel} eq '1') {
            $page = 'channel_devel';
         }


#         $vars->{style} = "background-image: url('images/xmas-party-anime-wallpaper.jpg'); background-repeat: no-repeat; background-attachment: fixed;";
         $vars->{style} = "background-repeat: no-repeat; background-attachment: fixed;";
         

       
         open (FILE,$globals::fs_dir."/chat/templates/motd_".$q->{'s'}.".tt2");
         while (my $line = <FILE>) {
            $vars->{motd} .= $line;
         }
         close(FILE);
         $vars->{motd} =~ s/%S/$q->{sid}/gs;
 
 
         if (defined($vars->{nick_id}) && $vars->{nick_id} > 0) {
            my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
            if ($ret_punish->{is_punished} == 1) {
               $vars->{is_punished} = 1;
               $vars->{ban} = $ret_punish->{ban};
               $vars->{mute} = $ret_punish->{mute};
               $vars->{stop} = $ret_punish->{stop};
               $vars->{ban_utime} = $ret_punish->{ban_utime};
               $vars->{mute_utime} = $ret_punish->{mute_utime};
               $vars->{stop_utime} = $ret_punish->{stop_utime};
               $vars->{ban_id} = $ret_punish->{ban_id};
               $vars->{mute_id} = $ret_punish->{mute_id};
               $vars->{stop_id} = $ret_punish->{stop_id};
                                             
            }
         }
        
         my $selected_server;
         my $servers_group = [];
         
         $main::get_servers_by_group->execute($q->{'s'});
         if ($main::get_servers_by_group->rows() != 0) {
            $servers_group = $main::get_servers_by_group->fetchall_arrayref({});

#            if ($vars->{server_id} != 0) {
#               $selected_server = $vars->{server_id};
#            } else {
#               $selected_server = $q->{'s'};
#            }
#         } else {
#            $selected_server = $q->{'s'};
         }
         $main::get_servers_by_group->finish();




         $main::get_server->execute($q->{'s'});
         my $server_data = $main::get_server->fetchrow_hashref();
         $main::get_server->finish();
                                    


#         if ($vars->{nick_id} == 1) {warn "main::get_server_in_group->execute($vars->{channel_id},$server_data->{server_group});";}
         

         $main::get_server_in_group->execute($q->{channel_id},$server_data->{server_group});
         if ($main::get_server_in_group->rows() == 0) {
            $vars->{server_id} = $q->{'s'};
            $selected_server = $q->{'s'};
         } else {
            if ($vars->{server_id} == 0) {
               $vars->{server_id} = $vars->{channel_id};
               $selected_server = $vars->{channel_id};
            } else {
               $selected_server = $q->{'s'};
            }
         }
                                                                                                               



         $vars->{servers_group} = $servers_group;
         $vars->{selected_server} = $selected_server;
         
         my $all = 0;
         if ($vars->{level} > 0 || $vars->{global_level} > 0) {$all = 1;}
         my $ret_ingame_gamemasters = system::get_ingame_gamemasters( { server_id => $selected_server, all => $all, }, );
#         my $ret_ingame_gamemasters = system::get_ingame_gamemasters( { server_id => $selected_server, }, );

         $vars->{gamemasters} = $ret_ingame_gamemasters->{gm_list};

         my $get_last_server_state = system::get_last_server_state( { server_id => $selected_server, }, );
         $vars->{state} = $get_last_server_state->{state};

         my $ret_session_data =  sessions::get_session_data($dbh, {session_id => $vars->{session_id} , } );
         my $session_data = $ret_session_data->{session_data};

         $vars->{afk_timer} = system::ptf($vars->{last_action_utime});

         my $ret_chat_pms_count = system::get_chat_pms_count( { nick_id => $vars->{nick_id}, }, );
         $vars->{pm_count} = $ret_chat_pms_count->{count};
                        
         my $ret_guild_chat_messages_count = system::get_guild_chat_messages_count( { nick_id => $vars->{nick_id}, }, );
         $vars->{g_count} = $ret_guild_chat_messages_count->{count};
                                                                  
         $vars->{localtime} = time();

         my $last_action_id = system::get_last_action_id();
         my $ret_set_session_data = sessions::set_session_data( $dbh, { session_id => $vars->{session_id}, name=> 'last_action', value => $last_action_id, } );

         my $ret_user_events = system::get_user_events( { nick_id => $vars->{nick_id}, }, );
         $vars->{user_events} = $ret_user_events->{user_events};

         if ($vars->{global_level} > 0) {
            $vars->{unprocessed_tickets_count} = system::get_unprocessed_tickets_count();
         }
                                      










         if (defined($vars->{nick_id}) && $vars->{nick_id} > 0) {

            $main::get_gsm_number_by_nick_id->execute($vars->{nick_id});
            $vars->{gsm} = $main::get_gsm_number_by_nick_id->fetchrow_hashref();
            $main::get_gsm_number_by_nick_id->finish();


            if (defined($vars->{show_macros}) && $vars->{show_macros} == 1) {
               my $ret_macros_by_nick_id = system::get_macros_by_nick_id( { nick_id => $vars->{nick_id}, }, );
               my $macros = $ret_macros_by_nick_id->{macros};
               $vars->{macros} = $macros;
            }

            my $ret_is_in_guilds_by_nick_id_channel_id = system::get_is_in_guilds_by_nick_id_channel_id( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
            $vars->{in_guilds} = $ret_is_in_guilds_by_nick_id_channel_id->{guilds};

            my $ret_is_on_channel = system::is_nick_id_on_channel( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
            if ($ret_is_on_channel->{rv} == 0) {

               my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
               if ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{ban} != 1)) {
                  system::add_session_to_channel( { session_id => $vars->{session_id}, channel_id => $q->{'s'}, }, );
                  $ret_is_on_channel = system::is_nick_id_on_channel( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
               }
            }
            $vars->{is_on_channel} = $ret_is_on_channel->{rv};

            my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );


            if ($ret_punish->{is_punished} == 1) {
               $vars->{is_punished} = 1;
               $vars->{ban} = $ret_punish->{ban};
               $vars->{ban_time} = $ret_punish->{ban_time};

               $vars->{mute} = $ret_punish->{mute};
               $vars->{mute_time} = $ret_punish->{mute_time};

               $vars->{stop} = $ret_punish->{stop};
               $vars->{stop_time} = $ret_punish->{stop_time};

            } else {
               $vars->{is_punished} = 0;
            }
         } elsif (defined($q->{ban}) && $q->{ban} eq '1') {
            my $ret_punish = system::get_punished( { nick_id => $q->{nick_id}, channel_id => $q->{'s'}, }, );

            $vars->{release_punish} = $ret_punish->{ban_time};
            $vars->{refresh} = 1;
            $vars->{refresh_time} = $ret_punish->{ban_time}+1;
         } else {

            my $ret_create_challenge = system::create_challenge( { session_hex => $q->{sid}, }, );
            $vars->{challenge} = $ret_create_challenge->{challenge};



         }







                                          

      } elsif ($q->{page} eq 'ajax_refresh') {

         $hf = 0;
         $contenttype = 'text/xml';

         system::prolong_session_on_channel( { session_id => $vars->{session_id}, channel_id => $q->{'s'}, ajax => 1, }, );
         
         if ($vars->{logged} == 1) {

            if (($vars->{afk} == 0 && $q->{set_afk} == 1) || ($vars->{afk} == 0 && $vars->{doafk} == 1)) {
               $main::set_afk->execute($vars->{nick_id});

               my $ret_punish;
            
               if (defined($vars->{nick_id}) && $vars->{nick_id} > 0) {
                  $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
                  if ($ret_punish->{is_punished} == 1) {
                     $vars->{is_punished} = 1;
#                     $vars->{ban} = $ret_punish->{ban};
#                     $vars->{ban_time} = $ret_punish->{ban_time};
#                     $vars->{mute} = $ret_punish->{mute};
#                     $vars->{mute_time} = $ret_punish->{mute_time};
#                     $vars->{mute_message} = $ret_punish->{mute_message};
#                     $vars->{mute_punisher} = $ret_punish->{mute_punisher};
#                     $vars->{stop} = $ret_punish->{stop};
#                     $vars->{stop_time} = $ret_punish->{stop_time};
#                     $vars->{stop_message} = $ret_punish->{stop_message};
#                     $vars->{stop_punisher} = $ret_punish->{stop_punisher};
                  }
               }

               my $tmp_rank_points = 0;
               if ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{stop} != 1)) {
                  $main::get_set_rank_points->execute($vars->{nick_id});
                  $tmp_rank_points = $main::get_set_rank_points->fetchrow_hashref();
                  $main::get_set_rank_points->finish();
                  $main::log_rank_points->execute($vars->{nick_id},$vars->{session_id},$tmp_rank_points->{last_no_afk},$tmp_rank_points->{chat_rank},$tmp_rank_points->{points});
                  $main::set_rank_points->execute($vars->{nick_id});
                  my $ret_del_bind_sessions_aways = system::del_bind_sessions_aways( { nick_id => $vars->{nick_id}, }, );
                  my $ret_set_session_data = sessions::set_session_data( $dbh, { session_id => $vars->{session_id}, name => 'pending_points', value => 0, } );
               }
               my $ret_add_action = system::add_action( { action => 16, nick_id => $vars->{'nick_id'}, value => 1, char_value => int($tmp_rank_points->{points}), }, );
               $main::set_past_action->execute($vars->{nick_id});
            } elsif ($vars->{afk} == 1 && $vars->{doafk} == 0) {
               $main::set_no_afk->execute($vars->{nick_id});
               $main::set_last_action->execute($vars->{nick_id});
               my $ret_add_action = system::add_action( { action => 16, nick_id => $vars->{'nick_id'}, value => 0, }, );
#               sessions::set_session_data( $dbh, { session_id => $vars->{session_id}, name => 'pending_points', value => 0, } );
            }
         }

         if ($q->{set_afk} != 1) {

            my $ret_session_data =  sessions::get_session_data($dbh, {session_id => $vars->{session_id} , } );
            my $session_data = $ret_session_data->{session_data};

            if (($session_data->{pending_points} != int($vars->{pending_chat_rank_points})) && ($vars->{afk} == 0)) {
#if ($vars->{nick_id} == 1) {
#   warn " $vars->{afk} :: if ($session_data->{pending_points} != ".int($vars->{pending_chat_rank_points}).')';
#}
               my $ret_add_action = system::add_action( { action => 22, nick_id => $vars->{'nick_id'}, }, );
               my $ret_set_session_data = sessions::set_session_data( $dbh, { session_id => $vars->{session_id}, name => 'pending_points', value => int($vars->{pending_chat_rank_points}), } );
            }

            my $ignorelist;
            $main::get_channel_ignored_nicks->execute($vars->{nick_id});
            foreach (@{$main::get_channel_ignored_nicks->fetchall_arrayref({})}) {
               $ignorelist->{$_->{block_id}} = 1;
            }
            $main::get_channel_ignored_nicks->finish();

            my $friendlist;
            $main::get_nick_friends->execute($vars->{nick_id});
            foreach (@{$main::get_nick_friends->fetchall_arrayref({})}) {
               $friendlist->{$_->{friend_id}} = $_;
            }
            $main::get_nick_friends->finish();


            my $ret_is_in_guilds_by_nick_id_channel_id = system::get_is_in_guilds_by_nick_id_channel_id( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
            my $in_guilds = $ret_is_in_guilds_by_nick_id_channel_id->{guilds};


            $main::get_server->execute($q->{'s'});
            my $server_data = $main::get_server->fetchrow_hashref();
            $main::get_server->finish();

#            if ($vars->{nick_id} == 1) {warn "main::get_server_in_group->execute($vars->{channel_id},$server_data->{server_group});";}


            $main::get_server_in_group->execute($vars->{channel_id},$server_data->{server_group});
            if ($main::get_server_in_group->rows() == 0) {
               $vars->{server_id} = $q->{'s'};
            } else {
               if ($vars->{server_id} == 0) {
                  $vars->{server_id} = $vars->{channel_id};
               }
                                          
            }

            if (!defined($q->{'last'}) || $q->{'last'} == 0 || $q->{'last'} =~ /\D/) {$q->{'last'} = $session_data->{'last_action'};}

#            warn "LAST = $q->{last} vs ".$session_data->{'last_action'};
            


            if (defined($vars->{nick_id}) && $vars->{nick_id} > 0) {
               my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
               if ($ret_punish->{is_punished} == 1) {
                  $vars->{is_punished} = 1;
                  $vars->{ban} = $ret_punish->{ban};

#if ($vars->{nick_id} == 1) {
#warn "!!! $vars->{nick_id} $ret_punish->{ban}";
#}


               }
            }

            my $ret_last_actions = system::get_last_actions( {
			last_action_id => $q->{'last'},
			debug => $q->{debug},
			init => $q->{init},
			last_action_utime => $vars->{last_action_utime},
			session_id => $vars->{session_id},
#			last_action_id => $session_data->{'last_action'},
			channel_id => $q->{'s'},
			server_id => $vars->{server_id},
			nick_id => $vars->{nick_id},
			level => $vars->{level},
			global_level => $vars->{global_level},
			incline => $vars->{incline},
			ignorelist => $ignorelist,
			friendlist => $friendlist,
			graph_id => $vars->{graph_id},
			nick => $vars->{nick},
			mark_messages => $vars->{mark_messages},
			last_no_afk_utime => $vars->{last_no_afk_utime},
			chat_rank => $vars->{chat_rank},
			session_hex => $q->{'sid'},
			show_graph => $vars->{show_graph},
                        pending_chat_rank_points => $vars->{pending_chat_rank_points},
                        privates_type => $vars->{privates_type},
                        guilds_type => $vars->{guilds_type},
                        hide_blabla => $vars->{hide_blabla},
                        in_guilds => $in_guilds,
			ban => $vars->{ban},
			import_ingame_chat => $vars->{import_ingame_chat},
            }, );
            my $last_action_id;

            if (defined($q->{init}) && $q->{init} == 1 ) {
               $last_action_id = system::get_last_action_id();
            } else {
               if (scalar(@{$ret_last_actions->{actions}}) != 0) {
                  $last_action_id = $ret_last_actions->{actions}->[-1]->{id};
               }
            }
            
            $vars->{last_action_id} = $last_action_id;
            $vars->{actions} = $ret_last_actions->{actions};
            $vars->{tx_bytes} = $session_data->{'tx_bytes'};
            $vars->{utime} = time();

            my $ret_set_session_data;
            if (defined($last_action_id)) {
               $ret_set_session_data = sessions::set_session_data( $dbh, { session_id => $vars->{session_id}, name => 'last_action', value => $last_action_id, } );
            }
         }

         $page = 'ajax_refresh';

#         warn "$vars->{last_no_afk_utime} $vars->{chat_rank} $vars->{c}";


      } elsif ($q->{page} eq 'css') {
         $page = 'css';
         $hf = 0;
         $location = '';

         $contenttype = 'text/css';

      } elsif ($q->{page} eq 'menu') {
         $hf = 1;
         $location = '';
         $page = 'menu';
         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{extra};
                                          

      } elsif ($q->{page} eq 'ajax_send') {
         $hf = 0;
         $contenttype = 'text/xml';
         $page = 'ajax_send';


         if ($q->{action} == 2) {
         

            my $ret_nick_activated = system::get_nick_activated( { nick_id => $vars->{nick_id}, }, );

            if ($ret_nick_activated->{state} == 1) {

               my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );

               my $message;

               if ($vars->{level} > 0 || $vars->{chat_rank} >= 8) {
                  $message = system::htmlfilter($q->{message});
               } else {
                  my $message1 = system::bwfilter($q->{message});
                  $message = system::htmlfilter($message1);
               }

               if ($vars->{nick_id} != 0 && defined($q->{message}) && $q->{message} !~ /^\s*$/ && ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{ban} != 1))) {

                  my ($server_name,$world_status,$auth_status,$web_status,$stamp,$stamp_last_up,$stamp_last_down,$stamp_last_ws,$players,$gamemasters,$vips,$horde,$alliance,$limit,$version,$ip,$gm_plevel);
                  if ($message =~ /%/) {
                     $main::get_last->execute($q->{'s'});
                     ($server_name,$world_status,$auth_status,$web_status,$stamp,$stamp_last_up,$stamp_last_down,$stamp_last_ws,$players,$gamemasters,$vips,$horde,$alliance,$limit,$version,$ip,$gm_plevel) = $main::get_last->fetchrow_array();
                     $main::get_last->finish();
                  }


                  $message =~ s/%r/$ip/gs;
                  $message =~ s/%R/set realmlist $ip/gs;
                  $message =~ s/%s/$server_name/gs;
                  $message =~ s/%n/$vars->{nick}/gs;
                  $message =~ s/%l/$limit/gs;
                  $message =~ s/%v/$version/gs;
                  $message =~ s/%c/$q->{s}/gs;
                  if ($message !~ /admin\.fcgi/) {
                     $message =~ s/sid=$q->{sid}/sid=%S/gs;
                  }
                  $message =~ s/šulin\.net/xn--ulin-f6a.net/gsi;

                  $message =~ s/\[(item=\d+)\|.+?]/[$1]/gsi;
                  if (defined($map_armory_server_id->{$q->{'s'}}) && $map_armory_server_id->{$q->{'s'}} != 0) {
#                     $message =~ s/(http\:\/\/)?wow\.allakhazam\.com(\/db)?\/item.html\?witem=(\d+)(\&amp;locale=.+?;source=.+?\b)/[item=$3]/gsi;
#                     $message =~ s/(http\:\/\/)?www\.wowhead\.com\/item=(\d+)/[item=$2]/gsi;
#                     $message =~ s/(http\:\/\/)?www\.wowhead\.com\/npc=(\d+)/[npc=$2]/gsi;
#                     $message =~ s/(http\:\/\/)?www\.wowhead\.com\/quest=(\d+)/[quest=$2]/gsi;
#                     $message =~ s/(http\:\/\/)?www\.wowhead\.com\/spell=(\d+)/[spell=$2]/gsi;
#                     $message =~ s/(http\:\/\/)?www\.wowhead\.com\/achievement=(\d+)/[achievement=$2]/gsi;
#                     $message =~ s/(http\:\/\/)?thottbot\.com\/i(\d+)/[item=$2]/gsi;
                  }

#                  $message =~ s/(http\:\/\/)?www\.wowarmory\.sk\/player\-status\.fcgi\?id=(\d+)\&amp;page=char\&amp;s=(\d+)/[player=$2]/gsi;
                                 

#                  $message =~ s/(http\:\/\/)?wow\.mine\.sk\/chat\/player\-status\.fcgi\?id=(\d+)&amp;page=char&amp;s=(\d+)/[player=$2]/gsi;
#               $message =~ s/(http\:\/\/)?wow\.mine\.sk\/chat\/misc\.fcgi\?page=show_profile.+?&amp;nick_id=(\d+)/[profile=$1]/gsi;
#               $message =~ s/(http\:\/\/)?wow\.mine\.sk\/chat\/misc\.fcgi\?page=search_message.+?&amp;channel=(\d+)&amp;text=(.*?)&amp;nick=(\d*)&amp;from_day=(\d+)&amp;from_month=(\d+)&amp;from_year=(\d+)&amp;to_day=(\d+)&amp;to_month=(\d+)&amp;to_year=(\d+)&amp;from_hour=(\d+)&amp;from_minute=(\d+)&amp;from_second=(\d+)&amp;to_hour=(\d+)&amp;to_minute=(\d+)&amp;to_second=(\d+)/[search=$1,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$2]/gsi;
#               $message =~ s/(http\:\/\/)?wow\.mine\.sk\/chat\/misc\.fcgi\?album_id=(\d+)&amp;nick_id=(\d+)&amp;page=show_album(&amp;sid=.{12})?/[album=$3,$2]/gsi;

                  if ($message =~ m/(https?\:\/\/)?www\.youtube\.com\/.*?v=([a-zA-Z0-9\_\-]+).*/) {
                     my $youtube_hash = $2;
                     
                     my $ret_youtube = system::get_youtube_id_by_hash( { hash => $youtube_hash} );
                     my $yt_id;
                     if ($ret_youtube->{ec} == 0) {
                     
                        my $rval = system::wget('http://gdata.youtube.com/feeds/api/videos/'.$youtube_hash);
                        my $data;
                        if ($rval->{state} == 1) {
                           my $ref = $xs->XMLin($rval->{'content'});
                           my $yt_time = &sec2min($ref->{'media:group'}->{'yt:duration'}->{'seconds'});
                           my $yt_title = $ref->{'title'}->{'content'};
                           $main::add_youtube_info->execute($youtube_hash,$yt_time,$yt_title);
                           $yt_id = $main::add_youtube_info->{mysql_insertid};

                        }
                     } else {
                        $yt_id = $ret_youtube->{youtube}->{id};
                     }
                     if ($yt_id) {
                        if ($4) {
                           $message =~ s/(https?\:\/\/)?www\.youtube\.com\/.*?v=([a-zA-Z0-9\_\-]+)(&amp;feature=related)?(#t=(\d+))?/[youtube=$yt_id,$4]/gs;
                        } else {
                           $message =~ s/(https?\:\/\/)?www\.youtube\.com\/.*?v=([a-zA-Z0-9\_\-]+)(&amp;feature=related)?(#t=(\d+))?/[youtube=$yt_id]/gs;
                        }
                     }
                  }


                  my $sla = 0;

                  if ($q->{to_nick} eq '') {


                     $main::is_valid_channel->execute($q->{'s'});

                     if ($ret_nick_activated->{state} == 1 && $main::is_valid_channel->rows() == 1) {

                        my $ret_is_on_channel = system::is_nick_id_on_channel( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
                        if ($ret_is_on_channel->{rv} != 1) {
#warn "system::add_session_to_channel( { session_id => $vars->{session_id}, channel_id => $q->{'s'}, }, );";

                           system::add_session_to_channel( { session_id => $vars->{session_id}, channel_id => $q->{'s'}, }, );
                           $ret_is_on_channel = system::is_nick_id_on_channel( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
                        }

                        if ($ret_is_on_channel->{rv} == 1) {
                           my $ret_session_quizz_state_by_session_id = system::get_session_quizz_state_by_session_id( { session_id => $vars->{session_id}, channel_id => $q->{'s'}, }, );
                           if ($ret_session_quizz_state_by_session_id->{quizz_state} != 0) {
                              my $ret_running_quizz_by_channel_id = system::get_running_quizz_by_channel_id( { channel_id => $q->{'s'}, }, );

                              if ($ret_running_quizz_by_channel_id->{rv} == 1 && $ret_running_quizz_by_channel_id->{quizz}->{id} == $ret_session_quizz_state_by_session_id->{quizz_state}) {

                                 my $quizz = $ret_running_quizz_by_channel_id->{quizz};
                                 my $ret_last_answer_by_quizz_id = system::get_last_answer_by_quizz_id( { quizz_id => $quizz->{id}, }, );
                                 my $answer = $ret_last_answer_by_quizz_id->{answer};
                                 if (lc($answer->{answer_text}) eq lc($message)) {
#if ($vars->{nick_id} == 1) {warn "if (lc($answer->{answer_text}) eq lc($message)) {";}
                                    system::mark_winned_quizz_question( { quizz_id => $quizz->{id}, bind_id => $answer->{id}, question_id => $answer->{question_id}, nick_id => $vars->{nick_id}, quizzmaster_id => $quizz->{quizzmaster_id}, winner => $vars->{nick}, total_rounds => $quizz->{total_rounds}, channel_id => $q->{'s'}, }, );
                                 }

                              }
                           }


#                     $message = substitute($message);

                           my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
                           $vars->{is_punished} = $ret_punish->{is_punished};

                           if ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{mute} != 1)) {

                              if (defined($q->{prepend}) && $q->{prepend} > 0) {
                                 if ($q->{prepend} == 1) {$message = '/me '.$message;}
                                 if ($q->{prepend} == 2) {$message = '/frak '.$message;}
                                 if ($q->{prepend} == 3) {$message = '/guild '.$message;}
                                 if ($q->{prepend} == 4) {$message = '/horde '.$message;}
                                 if ($q->{prepend} == 5) {$message = '/alliance '.$message;}
                                 if ($q->{prepend} == 6) {$message = '/nogroup '.$message;}
                              }

                              my $faction;
                              if ($vars->{level} > 0 || $vars->{global_level} > 0) {
                                 $faction = 0;
                              } else {
                                 if ($vars->{incline} == 1) {
                                    $faction = 1;
                                 } elsif ($vars->{incline} == 2) {
                                    $faction = 2;
                                 } elsif ($vars->{incline} == 3) {
                                    $faction = 3;
                                 }
                              }

                              $main::get_profile->execute($vars->{nick_id});
                              my $ret_profile = $main::get_profile->fetchrow_hashref();
                              $main::get_profile->finish();

                              my $message_id;
                              if ($message =~ /^[\\\/]me (.+)$/) {
                                 my $ret_message = system::add_chat_message( { msg_type => 'm', channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, message => $1, ip => $ENV{REMOTE_ADDR}, }, );
                                 $message_id = $ret_message->{message_id};
                                 system::add_action( { action => 1, channel_id => $q->{'s'}, message_id => $message_id, }, );
                                 $main::add_history_chat->execute('m',$q->{'s'},$vars->{nick_id},$1,$ENV{REMOTE_ADDR});
                                 if ($vars->{hold_me_frak} == 1) {
                                    $q->{prepend} = 1; #-
                                 }

#                           system::add_wowchat_action( { action_type => 0, action_code => 7, channel_id => $q->{'s'}, user_id1 => $vars->{nick_id}, action_text => system::htmlfilter($1.' (imported)'), action_me => 1, faction_id => 0, faction_color => 4+$vars->{incline}, text_id => $message_id, } );

                              } elsif (($faction == 0 || $faction == 2) && ($message =~ /^[\\\/]horde (.+)$/ || $message =~ /^[\\\/]h (.+)$/)) {

                                 my $ret_message = system::add_chat_message( { msg_type => 'f', faction => 2, channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, message => $1, ip => $ENV{REMOTE_ADDR}, }, );
                                 $message_id = $ret_message->{message_id};
                                 system::add_action( { action => 1, channel_id => $q->{'s'}, message_id => $message_id, }, );
                                 $main::add_history_chat->execute('f',$q->{'s'},$vars->{nick_id},$1,$ENV{REMOTE_ADDR});
                                 if ($vars->{hold_me_frak} == 1) {
                                    $q->{prepend} = 4; #-
                                 }

#                           system::add_wowchat_action( { action_type => 0, action_code => 7, channel_id => $q->{'s'}, user_id1 => $vars->{nick_id}, action_text => system::htmlfilter($1.' (imported)'), action_me => 0, faction_id => 1, faction_color => 4+$vars->{incline}, text_id => $message_id, } );


                              } elsif (($faction == 0 || $faction == 1) && ($message =~ /^[\\\/]alliance (.+)$/ || $message =~ /^[\\\/]a (.+)$/)) {

                                 my $ret_message = system::add_chat_message( { msg_type => 'f', faction => 1, channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, message => $1, ip => $ENV{REMOTE_ADDR}, }, );
                                 $message_id = $ret_message->{message_id};
                                 system::add_action( { action => 1, channel_id => $q->{'s'}, message_id => $message_id, }, );
                                 $main::add_history_chat->execute('f',$q->{'s'},$vars->{nick_id},$1,$ENV{REMOTE_ADDR});
                                 if ($vars->{hold_me_frak} == 1) {
                                    $q->{prepend} = 5; #-
                                 }

#                           system::add_wowchat_action( { action_type => 0, action_code => 7, channel_id => $q->{'s'}, user_id1 => $vars->{nick_id}, action_text => system::htmlfilter($1.' (imported)'), action_me => 0, faction_id => 2, faction_color => 4+$vars->{incline}, text_id => $message_id, } );

                              } elsif (($faction == 0 || $faction == 3) && ($message =~ /^[\\\/]nogroup (.+)$/ || $message =~ /^[\\\/]n (.+)$/)) {

                                 my $ret_message = system::add_chat_message( { msg_type => 'f', faction => 3, channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, message => $1, ip => $ENV{REMOTE_ADDR}, }, );
                                 $message_id = $ret_message->{message_id};
                                 system::add_action( { action => 1, channel_id => $q->{'s'}, message_id => $message_id, }, );
                                 $main::add_history_chat->execute('f',$q->{'s'},$vars->{nick_id},$1,$ENV{REMOTE_ADDR});
                                 if ($vars->{hold_me_frak} == 1) {
                                    $q->{prepend} = 6; #-
                                 }

#                           system::add_wowchat_action( { action_type => 0, action_code => 7, channel_id => $q->{'s'}, user_id1 => $vars->{nick_id}, action_text => system::htmlfilter($1.' (imported)'), action_me => 0, faction_id => 3, faction_color => 4+$vars->{incline}, text_id => $message_id,  } );


                              } elsif ($message =~ /^[\\\/]frak (.+)$/ || $message =~ /^[\\\/]f (.+)$/ || $message =~ /^[\\\/]gm (.+)$/ || $message =~ /^[\\\/]admin (.+)$/) {

                                 my $ret_message = system::add_chat_message( { msg_type => 'f', faction => $faction, channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, message => $1, ip => $ENV{REMOTE_ADDR}, }, );
                                 $message_id = $ret_message->{message_id};
                                 system::add_action( { action => 1, channel_id => $q->{'s'}, message_id => $message_id, }, );
                                 $main::add_history_chat->execute('f',$q->{'s'},$vars->{nick_id},$1,$ENV{REMOTE_ADDR});
                                 if ($vars->{hold_me_frak} == 1) {
                                    $q->{prepend} = 2; #-
                                 }

                              } elsif ($message =~ /^[\\\/]guild (.+)$/ || $message =~ /^[\\\/]g (.+)$/) {

                                 my $ret_is_in_guilds_by_nick_id_channel_id = system::get_is_in_guilds_by_nick_id_channel_id( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
                                 my $guild_id = $ret_is_in_guilds_by_nick_id_channel_id->{guilds}->[0]->{guild_id};

#                           $main::get_guild_id_by_channel_and_nick_id->execute($q->{'s'},$vars->{nick_id});
#                           my $guild_id = $main::get_guild_id_by_channel_and_nick_id->fetchrow();
#                           $main::get_guild_id_by_channel_and_nick_id->finish();
                                 $q->{prepend} = 3;
                                 if (defined($guild_id) && $guild_id != 0) {
                                    system::add_guild_chat( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, guild_id => $guild_id, message => $1, ip => $ENV{REMOTE_ADDR}, channel_id => $q->{'s'}, } );
                                 }

                              } elsif ($message =~ /^[\\\/]away(.*)$/) {
                                 my $amessage = $1;
                                 if ($amessage eq '') {
                                    $main::set_away_message_by_nick_id->execute('',$vars->{nick_id});
                                 } else {
                                    $amessage =~ s/^ //;
                                    $main::get_away_message_by_shortcut_nick_id->execute($amessage,$vars->{nick_id});
                                    if ($main::get_away_message_by_shortcut_nick_id->rows() == 1) {
                                       my $away_message = $main::get_away_message_by_shortcut_nick_id->fetchrow_hashref();
                                       $main::set_away_message_by_nick_id->execute($away_message->{message},$vars->{nick_id});
                                    } else {
                                       $main::set_away_message_by_nick_id->execute($amessage,$vars->{nick_id});
                                    }
                                    $main::get_away_message_by_shortcut_nick_id->finish();
                                 }

                              } elsif ($message =~ /^[\\\/](cry|applaud|fart|rofl|rude|salute|scare|scratch|sleep|spit|surprised|excited|tired|wave|jk|lick|listen|kiss|blow|kneel|sexy|smell|apologize|bite|bye|congrats|cong|flex|hello|hi|hug|hungry|laugh|massage|shy|bark|smile|chicken|hail|love|no|greet|taunt|dance|thirsty|pray|thanks|slap|wink|cheer|bored|facepalm)(.*)$/) {

                                 system::emote( { channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, ip => $ENV{REMOTE_ADDR}, emote => $1, suffix => $2, sex => $ret_profile->{profile_sex}, }, );

                              } elsif ($message =~ /^\!(.+)$/) {
                                 my $arr;
                                 @{$arr} = split(' ',$1);
                                 my $cmd = shift(@{$arr});
                                 if ($cmd eq 'char') {

                                 } elsif ($cmd eq 'limit') {
                                    $main::add_private->execute(0,$vars->{nick_id},'Preco sa nejde pripojit na server, ked je len '.$players.' postav a limit je 120 hracov? Pretoze je rozdiel v pocte postav v hre a pocte prihlasenych uzivatelov, ktori nemusia byt vsetci prihaseny s postavami v hre. Navyse v kazdom momente sa na server hlasia nejaki ludia.',0,$ENV{REMOTE_ADDR},0);
                                 } elsif ($cmd eq 'realmlist') {
                                    $main::add_private->execute(0,$vars->{nick_id},'V subore realmlist.wtf je nutne mat napisane: set realmlist '.$ip,0,$ENV{REMOTE_ADDR},0);
                                 } elsif ($cmd eq 'hram') {
                                    my $ret_session_quizz_state_by_session_id = system::get_session_quizz_state_by_session_id( { session_id => $vars->{session_id}, channel_id => $q->{'s'}, }, );
                                    if ($ret_session_quizz_state_by_session_id->{quizz_state} == 0) {
                                       my $ret_running_quizz_by_channel_id = system::get_running_quizz_by_channel_id( { channel_id => $q->{'s'}, }, );
                                       my $quizz = $ret_running_quizz_by_channel_id->{quizz};
                                       if ($ret_running_quizz_by_channel_id->{rv} == 1) {
                                          system::set_quizz_state_to_channel_session_id( { quizz_id => $quizz->{id}, session_id => $vars->{session_id}, channel_id => $q->{'s'}, }, );
                                          $main::add_private_showed->execute(0,$vars->{nick_id},'Bol si prihlaseny do kvizu.',0,$ENV{REMOTE_ADDR},0);
                                       } else {
                                          $main::add_private_showed->execute(0,$vars->{nick_id},'Nie je mozne prihlasit do kvizu - ziaden neprebieha.',0,$ENV{REMOTE_ADDR},0);
                                       }
                                    } else {
                                       $main::add_private_showed->execute(0,$vars->{nick_id},'Uz si prihlaseny do kvizu',0,$ENV{REMOTE_ADDR},0);
                                    }

                                 } elsif ($cmd eq 'friends') {
                                    $main::get_nick_friends_online->execute($vars->{nick_id});
                                    my $friends = $main::get_nick_friends_online->fetchall_arrayref({});
                                    if (scalar(@{$friends}) != 0) {
                                       my $fmessage;
                                       my $pom = 0;
                                       foreach my $friend (@{$friends}) {
                                          ++$pom;
                                          $fmessage .= $friend->{nick} . '@'.$friend->{channel_name};
                                          if ($friend->{afk} == 1) {$fmessage .= ' (AFK)';}
                                          if (scalar(@{$friends}) > $pom) {$fmessage .= ' , ';}
                                       }
                                       $main::add_private_showed->execute(0,$vars->{nick_id},'Tvoji priatelia su prihlaseni: '.$fmessage,0,$ENV{REMOTE_ADDR},0);
                                    }
                                    $main::get_nick_friends_online->finish();
                                 } elsif ($cmd eq 'tv' && $vars->{chat_rank} >= 2) {
                                    if (scalar(@{$arr}) == 0) {
                                       $main::add_private->execute(0,$vars->{nick_id},'Pouzitie: !tv kanal ('. lc join(', ',keys(%{$tv_channels})) .')',0,$ENV{REMOTE_ADDR},0);
                                    } else {
                                       my $chan = lc $arr->[0];
                                       $main::get_actual_tv1->execute($tv_channels->{$chan});
                                       if (defined($tv_channels->{$chan})) {
                                          if ($main::get_actual_tv1->rows() != 0) {
                                             my $actual = $main::get_actual_tv1->fetchrow_hashref();

#warn "$actual->{name}.'. Potom ide: '.$actual->{'next'}";

                                             $main::add_private->execute(0,$vars->{nick_id},'Na kanali '. uc($arr->[0]) .' ide od '.$actual->{ts}.' do '.$actual->{till}.': '.$actual->{name}.'. Potom ide: '.$actual->{'next'},0,$ENV{REMOTE_ADDR},0);
                                          } else {
                                             $main::get_actual_tv2->execute($tv_channels->{$chan});
                                             if ($main::get_actual_tv2->rows() != 0) {
                                                my $actual = $main::get_actual_tv2->fetchrow_hashref();
                                                $main::add_private->execute(0,$vars->{nick_id},'Na kanali '. uc($arr->[0]) .' ide od '.$actual->{ts}.': '.$actual->{name},0,$ENV{REMOTE_ADDR},0);
                                             } else {
                                                $main::add_private->execute(0,$vars->{nick_id},'Na kanali '. uc($arr->[0]) .' momentalne nic nejde',0,$ENV{REMOTE_ADDR},0);
                                             }
                                          }
                                       } else {
                                          $main::add_private->execute(0,$vars->{nick_id},'Kanal '. uc($arr->[0]) .' nemonitorujem',0,$ENV{REMOTE_ADDR},0);
                                       }
                                    }
                                 } elsif ($cmd eq 'seen') {
                                    if (scalar(@{$arr}) == 0) {
                                       my $message = 'Pouzitie: !seen nick';

                                       $main::add_private_showed->execute(0,$vars->{nick_id},$message,0,$ENV{REMOTE_ADDR},0);
                                       my $message_id = $main::add_private_showed->{mysql_insertid};
                                       system::add_action( { action => 18, nick_id => $vars->{nick_id}, message_id => $message_id, value => '1', }, );

                                    } else {
                                       my $nick = lc $arr->[0];
                                       $main::get_last_seen_by_name->execute($nick);
                                       my $seen = $main::get_last_seen_by_name->fetchrow_hashref();
                                       my $message;
                                       if ($seen->{logout} eq '00.00.00 00:00') {
                                          $message = $seen->{nick}.' je stale prihlaseny od '.$seen->{login};
                                       } else {
                                          $message = $seen->{nick}.' bol naposledy prihlaseny od '.$seen->{login}.' do '.$seen->{logout};
                                       }

                                       $main::add_private_showed->execute(0,$vars->{nick_id},$message,0,$ENV{REMOTE_ADDR},0);
                                       my $message_id = $main::add_private_showed->{mysql_insertid};
                                       system::add_action( { action => 18, nick_id => $vars->{nick_id}, message_id => $message_id, value => '1', }, );
                                    }

                                 } elsif ($cmd eq 'logout') {
                                    $main::get_set_rank_points->execute($vars->{nick_id});
                                    my $tmp_rank_points = $main::get_set_rank_points->fetchrow_hashref();
                                    $main::get_set_rank_points->finish();
                                    if (defined($tmp_rank_points->{chat_rank}) && defined($tmp_rank_points->{points}) && $tmp_rank_points->{afk} == 0) {
                                       $main::log_rank_points->execute($vars->{nick_id},$vars->{session_id},$tmp_rank_points->{last_no_afk},$tmp_rank_points->{rank},$tmp_rank_points->{points});
                                       $main::set_rank_points->execute($vars->{nick_id});
                                       sessions::del_nick_from_session($dbh, { nick_id => $vars->{nick_id}, sid => $q->{sid}, session_id => $vars->{session_id}, }, );
                                       system::add_action( { action => 17, session_id => $vars->{session_id}, }, );
                                    }

#                              system::add_wowchat_action( { action_type => 0, action_code => 1, user_id2 => $vars->{nick_id}, action_text => 'Ziaden exit message (imported)', action_hostname => 'imported: '.system::mask_address($ENV{REMOTE_ADDR}), } );

                                    $set_cookie = 'Set-Cookie: x=1; domain=wow.mine.sk; path=/chat;'."\n";
                                    $location = $globals::init_script.'?page=frame&sid='.$q->{sid}.'&s='.$q->{'s'};
                                    my $ret_disconnect = pokec::disconnect($vars->{pokec_i9});
                                    $main::set_pokec_i9->execute('',$vars->{nick_id});
                                    $sla = 1;
                                 }

                              } else {
                                 if ($message =~ /^[=\d\+\-\*\/\(\)\[\]\.\^,\% ]+$/ && $message =~ /[\+\-\*\/\^\%]/) {
                                    $message .= ' = '.&calculator($message);
                                    $main::add_private_showed->execute(0,$vars->{nick_id},$message,0,$ENV{REMOTE_ADDR},0);
                                    my $message_id = $main::add_private_showed->{mysql_insertid};
                                    system::add_action( { action => 18, nick_id => $vars->{nick_id}, message_id => $message_id, value => '1', }, );

                                 } else {
                                    $main::add_chat->execute('c',$q->{'s'},$vars->{nick_id},$message,$ENV{REMOTE_ADDR});
                                    my $message_id = $main::add_chat->{mysql_insertid};
#                              system::add_wowchat_action( { action_type => 0, action_code => 7, channel_id => $q->{'s'}, user_id1 => $vars->{nick_id}, action_text => system::htmlfilter($message.' (imported)'), action_me => 0, faction_id => 0, faction_color => 4+$vars->{incline}, text_id => $message_id, } );
                                    system::add_action( { action => 1, channel_id => $q->{'s'}, message_id => $message_id, }, );
                            
                                    $main::add_history_chat->execute('c',$q->{'s'},$vars->{nick_id},$message,$ENV{REMOTE_ADDR});
#                              system::add_event( { channel_id => $q->{'s'}, event_type => 1, record_id => $main::add_chat->{mysql_insertid}, } );
                                    $sla = 1;
                                 }
                              }
                              $main::set_chat_messages_count->execute($q->{'s'});
                           }
                        }
#                  $sla = 1;
                        $vars->{return_value} = 0; # message sent
 
                     } else {
                        $vars->{return_value} = 7; # not on channel or not activated
                     }
                 
                  } else {

warn "piseme PM $vars->{nick_id} -> $q->{to_nick}";

                     $main::get_nick_id->execute($q->{to_nick});
                     if ($main::get_nick_id->rows == 1) {
                        my $to_nick_id = $main::get_nick_id->fetchrow();

                        if ($message =~ /^[\\\/](cry|applaud|fart|rofl|rude|salute|scare|scratch|spit|surprised|excited|tired|wave|jk|lick|listen|kiss|kneel|sexy|smell|apologize|bite|bye|congrats|cong|flex|hello|hi|hug|hungry|laugh|massage|shy|bark|smile|chicken|hail|love|no|greet|taunt|dance|thirsty|pray|thanks|slap|wink|cheer|bored|facepalm)$/) {
  
                           system::emote( { channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, ip => $ENV{REMOTE_ADDR}, emote => $1, target_id => $to_nick_id, target => $q->{to_nick}, }, );
                           $vars->{return_value} = 0;
   
                        } else {
                           $vars->{to_nick_id} = $to_nick_id;

                           $main::get_ignored->execute($to_nick_id,$vars->{nick_id});
                           my $deleted = 0;
                           if ($main::get_ignored->rows() != 0) {
                              $deleted = 1;
                              my $ignore_id = $main::get_ignored->fetchrow();
                              $main::add_block->execute($ignore_id);
                           } else {
                              system::add_action( { action => 15, nick_id => $to_nick_id, }, );
                           }                                                

                           $main::get_afk_state_by_nick_id->execute($to_nick_id);
                           my $state = $main::get_afk_state_by_nick_id->fetchrow_hashref();
                           $main::get_afk_state_by_nick_id->finish();


                           if ($deleted == 1 || $to_nick_id == $vars->{nick_id} || $state->{afk} == 1 || $state->{session_id} eq '' ) {
                              $sla = 0;
                           } else {
                              $sla = 1;
                           }
                           $main::get_ignored->finish();
                           if (!defined($q->{message_id}) || $q->{message_id} eq '') {$q->{message_id} = 0;}
                           $main::add_private->execute($vars->{nick_id},$to_nick_id,$message,$q->{message_id},$ENV{REMOTE_ADDR},$deleted);
                           my $msg_id = $main::add_private->{mysql_insertid};
                           system::add_action( { action => 18, nick_id => $to_nick_id, message_id => $msg_id, }, );
                           system::add_action( { action => 18, nick_id => $vars->{nick_id}, message_id => $msg_id, }, );

                           $main::add_history_private->execute($msg_id,$vars->{nick_id},$to_nick_id,$message,$ENV{REMOTE_ADDR},$deleted);

                           my $ret_away_afk_message_by_nick_id = system::get_away_afk_message_by_nick_id( { nick_id => $to_nick_id, session_id => $vars->{session_id}, }, );
                           if ($ret_away_afk_message_by_nick_id->{rv} == 1) {
                              $main::add_private->execute($to_nick_id,$vars->{nick_id},'Automaticka odpoved od uzivatela: '.$ret_away_afk_message_by_nick_id->{away_message},0,0,0);
                              my $msg_id2 = $main::add_private->{mysql_insertid};
                              system::add_action( { action => 15, nick_id => $vars->{nick_id}, }, );
                              system::add_action( { action => 18, nick_id => $vars->{nick_id}, message_id => $msg_id2, }, );
                                                   
                           }
                           $vars->{return_value} = 0;

                        }

                     } else {
                        $vars->{return_value} = 3;
                     }

                     $main::get_nick_id->finish();
                  }

                  if ($sla == 1) {
                     $main::set_last_action->execute($vars->{nick_id});
                  }

                  $vars->{return_value} = 0; # message sent



               } else { # not logged, banned or empty message
                  $vars->{is_punished} = $ret_punish->{is_punished};
                  $vars->{return_value} = 2;
               }


            } else {
               $vars->{return_value} = 1; # not activated
            }


         } elsif ($q->{action} == 1) {

            my $enc_password;
            if (defined($q->{response}) && $q->{response} =~ /^.{64}$/) {
               my $ret_check_challenge = system::check_challenge( { login => $q->{nick_login}, session_hex => $q->{sid}, response => $q->{response}, } );
               if ($ret_check_challenge->{rv} == 1) {
                  $q->{nick_password} = $ret_check_challenge->{password};
                  $enc_password = $ret_check_challenge->{enc_password};
               }
            }

            my ($nick_id,$level,$channel_id,$email,$chat_rank,$state,$nick);
            my $rv = 0;
            $main::get_nick_by_enc->execute($q->{nick_login},$enc_password);
            if ($main::get_nick_by_enc->rows() == 1) {
               $rv = 1;
               ($nick_id,$level,$channel_id,$email,$chat_rank,$state,$nick) = $main::get_nick_by_enc->fetchrow_array();
               $main::get_nick_by_enc->finish();
            } else {
#               TMP PASS

            }


            my $ret_count = sessions::get_logged_nick_count($dbh, { nick_id => $nick_id, }, );
            if ($rv == 1) {

#               system::add_wowchat_action( { action_type => 0, action_code => 0, user_id2 => $nick_id, action_hostname => 'imported: '.system::mask_address($ENV{REMOTE_ADDR}), } );


               my $ret_punish = system::get_punished( { nick_id => $nick_id, channel_id => $channel_id, }, );

               if ($ret_punish->{is_punished} == 1 && $ret_punish->{ban} == 1) {
#warn "DEBUG :: banned :(";
                  my $ret_punish2 = system::get_punished( { nick_id => $nick_id, }, );
                  if ($ret_punish2->{is_punished} == 0 || ($ret_punish2->{is_punished} == 1 && $ret_punish2->{ban} != 1)) {
#warn " DEBUG :: but not global ... setting channel_id to 0";
                     $main::set_channel->execute(0,0,$nick_id);
                     $channel_id = 0;
                     $ret_punish->{is_punished} = 0;
                  }
               }


               if ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{ban} != 1)) {

                  sessions::add_nick_to_session($dbh, { nick_id => $nick_id, sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, );
                  my $ret_session = sessions::get_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, );
                  if ($ret_session->{ec} == 1) {
                     if ($ret_session->{nick_id} != 0) {

                        $vars->{session_id} = $ret_session->{session_id};
                        $vars->{privates_type} = $ret_session->{privates_type};
#                        warn "DO AFK = $ret_session->{doafk}";
#                        warn "last_a = $ret_session->{last_a}";
                     }
                  }

                  if (defined($vars->{session_id})) {
                     system::add_session_to_channel( { session_id => $vars->{session_id}, channel_id => $channel_id, }, );
                     system::add_action( { action => 26, channel_id => $channel_id, nick_id => $nick_id, value => 1, }, );

                  }

#                  my $ret_session = sessions::get_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, );
#                  if ($ret_session->{ec} == 1) {
#                     if ($ret_session->{nick_id} != 0) {
#                        $vars->{privates_type} = $ret_session->{privates_type};
#                     }
#                  }


#warn "main::get_nick_to_notify->execute($nick_id);";

                  $main::get_nick_to_notify->execute($nick_id);
                  foreach my $friend (@{$main::get_nick_to_notify->fetchall_arrayref({})}) {
#warn "main::add_private_showed->execute(0,$friend->{nick_id},'Tvoj priatel '.$friend->{nick}.' sa prave prihlasil na '.$friend->{channel_name},0,$ENV{REMOTE_ADDR},0);";
                     $main::add_private_showed->execute(0,$friend->{nick_id},'Tvoj priatel '.$friend->{nick}.' sa prave prihlasil na '.$friend->{channel_name},0,$ENV{REMOTE_ADDR},0);
                     my $message_id = $main::add_private_showed->{mysql_insertid};
#warn "system::add_action( { action => 18, nick_id => $friend->{nick_id}, message_id => $message_id, }, );";
                     system::add_action( { action => 18, nick_id => $friend->{nick_id}, message_id => $message_id, }, );

                     if ($friend->{email} == 1) {

                        $main::get_nick_by_nick_id->execute($friend->{nick_id});
                        my $nick_data = $main::get_nick_by_nick_id->fetchrow_hashref();
                        my $msg = MIME::Lite->new(
                                From                    => 'friendnotify',
                                To                      => $nick_data->{email},
                                Subject                 => 'Tvoj priatel '.$friend->{nick}.' sa prave prihlasil',
                                Type                    => 'text/plain',
                                'Auto-Submitted:'       => 'auto-generated',
                                'X-Originating-IP:'     => $ENV{REMOTE_ADDR},
                                Data                    => '',
                        );
                        $main::get_nick_by_nick_id->finish();
                        $msg->send;
                     }


                  }
                  $main::get_nick_to_notify->finish();

                  $main::get_nick_friends_online->execute($nick_id);
                  my $friends = $main::get_nick_friends_online->fetchall_arrayref({});
                  if (scalar(@{$friends}) != 0) {
                     my $message;
                     my $pom = 0;
                     foreach my $friend (@{$friends}) {
                        ++$pom;
                        $message .= $friend->{nick} . '@'.$friend->{channel_name};
                        if ($friend->{afk} == 1) {$message .= ' (AFK)';}
                        if (scalar(@{$friends}) > $pom) {$message .= ' , ';}
                     }
                     $main::add_private_showed->execute(0,$nick_id,'Tvoji priatelia su prihlaseni: '.$message,0,$ENV{REMOTE_ADDR},0);
                     my $message_id = $main::add_private_showed->{mysql_insertid};
                     system::add_action( { action => 18, nick_id => $nick_id, message_id => $message_id, }, );
                  }
                  $main::get_nick_friends_online->finish();


                  my $browser_hash_id;
                  $main::get_browser_hash_id->execute(md5_hex($ENV{HTTP_USER_AGENT}));
                  if ($main::get_browser_hash_id->rows() == 0) {
                     $main::add_browser_hash->execute(md5_hex($ENV{HTTP_USER_AGENT}),$ENV{HTTP_USER_AGENT});
                     $browser_hash_id = $main::add_browser_hash->{mysql_insertid};
                  } else {
                     $browser_hash_id = $main::get_browser_hash_id->fetchrow();
                  }


                  if ($vars->{privates_type} == 0) {
                     $main::get_unshowed_private->execute($nick_id);
                     foreach my $msg (@{$main::get_unshowed_private->fetchall_arrayref({})}) {
                        $main::set_showed_history->execute($msg->{id});
                        system::add_action( { action => 18, nick_id => $nick_id, message_id => $msg->{id}, }, );
                     }
                     $main::get_unshowed_private->finish();
                     $main::move_unshowed_private->execute($nick_id);
                  }

                  $main::update_user_first_last->execute($ENV{REMOTE_ADDR},$browser_hash_id,$nick_id);

               }
            }










#warn " nick_id = $nick_id ; nick = $nick ; rv = $rv";





            $vars->{nick_id} = $nick_id;
            $vars->{nick} = $nick;
            $vars->{rv} = $rv;


         } elsif ($q->{action} == 3) {
            if (sessions::check_duplicate_session($dbh, { sid => $q->{sid}, ip => $ENV{REMOTE_ADDR}, }, ) ) {
               $q->{sid} = sessions::create_session($dbh, { ip => $ENV{REMOTE_ADDR}, force_sid => $q->{sid}, }, );
            }

            my $ret_create_challenge = system::create_challenge( { session_hex => $q->{sid}, }, );
            $vars->{challenge} = $ret_create_challenge->{challenge};
         } elsif ($q->{action} == 4) {

            $main::set_showed_chat->execute($q->{message_id});
            $main::set_showed_history->execute($q->{message_id});
            system::add_action( { action => 15, nick_id => $vars->{nick_id}, }, );

            my $ret_channel_message_by_message_id = system::get_channel_message_by_message_id( { message_id => $q->{message_id}, }, );
            my $message = $ret_channel_message_by_message_id->{message};

            system::add_action( { action => 24, nick_id => $message->{channel_id}, message_id => $q->{message_id}, }, );



         } elsif ($q->{action} == 5) {

            $main::get_is_logged->execute($q->{nick_id});
            $vars->{nick_logged} = $main::get_is_logged->fetchrow();
            $main::get_is_logged->finish();

            $main::get_nick_joined_channels->execute($q->{nick_id});
            my $chans;
            if ($main::get_nick_joined_channels->rows() > 0) {
               $chans = $main::get_nick_joined_channels->fetchall_arrayref({});
            }
            $main::get_nick_joined_channels->finish();
            $vars->{nick_channels} = $chans;

            $main::get_privates_user_last->execute($q->{nick_id},$vars->{nick_id},$vars->{nick_id},$q->{nick_id},$q->{nick_id});
            my $lines = $main::get_privates_user_last->fetchall_arrayref({});
            foreach my $x (@{$lines}) {
               $x->{message} =~ s/\[player=(\d+),(\d+)\]/&system::rewrite_player($1,$2)/egs;
            }
            $vars->{lines} = $lines;
            $main::get_privates_user_last->finish();

         } elsif ($q->{action} == 6) {
            my $ret_guild_by_guild_id = system::get_guild_by_guild_id( { guild_id => $q->{guild_id}, } );
            $vars->{guild_info} = $ret_guild_by_guild_id->{guild_info};

         }










      } elsif ($q->{page} eq 'send_receive') {
         $hf = 1;
         $location = '';
         $page = 'send_receive';
         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{extra};


         if (defined($vars->{nick_id}) && $vars->{nick_id} > 0) {

            $main::get_gsm_number_by_nick_id->execute($vars->{nick_id});
            $vars->{gsm} = $main::get_gsm_number_by_nick_id->fetchrow_hashref();
            $vars->{gsm} = { 'confirmed_gsm_number' => 'x' };
            $main::get_gsm_number_by_nick_id->finish();


            if (defined($vars->{show_macros}) && $vars->{show_macros} == 1) {
               my $ret_macros_by_nick_id = system::get_macros_by_nick_id( { nick_id => $vars->{nick_id}, }, );
               my $macros = $ret_macros_by_nick_id->{macros};
               $vars->{macros} = $macros;
            }

            my $ret_is_in_guilds_by_nick_id_channel_id = system::get_is_in_guilds_by_nick_id_channel_id( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
            $vars->{in_guilds} = $ret_is_in_guilds_by_nick_id_channel_id->{guilds};

            my $ret_is_on_channel = system::is_nick_id_on_channel( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
            if ($ret_is_on_channel->{rv} == 0) {

               my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
               if ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{ban} != 1)) {
                  system::add_session_to_channel( { session_id => $vars->{session_id}, channel_id => $q->{'s'}, }, );
                  $ret_is_on_channel = system::is_nick_id_on_channel( { nick_id => $vars->{nick_id}, channel_id => $q->{'s'}, }, );
               }
            }
            $vars->{is_on_channel} = $ret_is_on_channel->{rv};

            my $ret_punish = system::get_punished( { nick_id => $vars->{nick_id}, channel_id => $q->{s}, }, );


            if ($ret_punish->{is_punished} == 1) {
               $vars->{is_punished} = 1;
               $vars->{ban} = $ret_punish->{ban};
               $vars->{ban_time} = $ret_punish->{ban_time};

               $vars->{mute} = $ret_punish->{mute};
               $vars->{mute_time} = $ret_punish->{mute_time};

               $vars->{stop} = $ret_punish->{stop};
               $vars->{stop_time} = $ret_punish->{stop_time};

            } else {
               $vars->{is_punished} = 0;
            }
         } elsif (defined($q->{ban}) && $q->{ban} eq '1') {
            my $ret_punish = system::get_punished( { nick_id => $q->{nick_id}, channel_id => $q->{s}, }, );

            $vars->{release_punish} = $ret_punish->{ban_time};
            $vars->{refresh} = 1;
            $vars->{refresh_time} = $ret_punish->{ban_time}+1;
         } else {

            my $ret_create_challenge = system::create_challenge( { session_hex => $q->{sid}, }, );
            $vars->{challenge} = $ret_create_challenge->{challenge};



         }
      }




      if ($location eq '' && -f $globals::datadir."/templates/".$page.".tt2") {
         if ($usegzip) {print 'Content-Encoding: '.$usegzip."\n";}
         print 'Content-type: '.$contenttype."\n\n";
         if ($hf == 1) {$template->process('header.tt2', $vars, \$html) || warn $template->error();}
         $template->process($page.'.tt2', $vars, \$html) || warn $template->error();
# 
#         if ($page eq 'ajax_refresh' && $vars->{nick_id} == 1) {warn $html;}
#
         if ($hf == 1) {$template->process('footer.tt2', $vars, \$html) || warn $template->error();}
         if ($usegzip) {$html = Compress::Zlib::memGzip( $html );}

         if ($page eq 'ajax_refresh') {
            my $ret_set_session_data = sessions::set_session_data( $dbh, { session_id => $vars->{session_id}, name=> 'tx_bytes', value => length($html), math_add => 1, } );
         }
   
         print $html;
         $html = '';
      } elsif ($location ne '') {
         if ($set_cookie ne '') {print $set_cookie;}
         print 'Location: '.$location."\n\n";
         $request->Finish();
         next;
      } else {
         print 'Content-type: text/html'."\n\n".'bububu';
      }

      undef $vars;

   }

   $loop_instance--;

   if ($loop_instance <= 1) {
      last;
   }
}

$request->Finish();



sub plain_time_format($) {
   my ($utime) = @_;
   my $h = int($utime / 3600);
   my $stack = $utime % 3600;
   my $m = int($stack / 60);
   my $s= $stack  % 60;
   my $out;
   if ($h != 0) {$out = $h.'h ';}
   if ($m != 0) {$out .= $m.'m ';}
   if ($s != 0) {$out .= $s.'s ';}
   return $out;
}


sub sec2min($) {
   my $sec = shift;
   my $m = int($sec/60);
   my $s = $sec%60;
   if ($s < 10) {$s = '0'.$s;}
   return $m.':'.$s;
}


sub calculator($) {
   my ($to_eval) = @_;
   $to_eval =~ s/,/./gs;
   $to_eval =~ s/\^/**/gs;
   $to_eval =~ s/[^\d\+\-\*\/\(\)\[\]\.\% ]//gs;
   $to_eval =~ s/=//gs;
#   warn "calculator \"$to_eval\"";
   return eval($to_eval);
}






