#!/usr/bin/perl

use strict;
use Template;
use CGI::Lite;
use FCGI;
#use String::Similarity;
use Digest::MD5 qw(md5_hex);
use Compress::Zlib;
use Time::HiRes qw(gettimeofday tv_interval);
use Text::Iconv;
use MIME::Lite;
use XML::Simple;

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 $ua = new LWP::UserAgent;
my $converter = Text::Iconv->new("utf-8", "windows-1250");
my $xs = XML::Simple->new();

$cgi->set_directory ($globals::datadir.'/tmp');


my $request = FCGI::Request();

my $refreshs = { '1' => '10', '2' => '15', '3' => '20', };
my $lines = { '1' => '10', '2' => '15', '3' => '20', '4' => '25', '5' => '30', };
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 $guilds;
#$main::get_servers->execute();
#foreach my $server (@{$main::get_servers->fetchall_arrayref({})}) {
#   $main::get_guilds->execute();
#   foreach (@{$main::get_guilds->fetchall_arrayref({})}) {
#      $guilds->{$_->{server_id}}->{$_->{id}} = $_;
#   }
#   $main::get_guilds->finish();
#}

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_maps->execute();
my $maps = $main::get_maps->fetchall_hashref('map_id');
$main::get_maps->finish();

$main::get_zones->execute();
my $zones = $main::get_zones->fetchall_hashref('zone_id');
$main::get_zones->finish();

$main::get_skills->execute();
my $skills_array = $main::get_skills->fetchall_arrayref({});
$main::get_skills->finish();

#$main::get_ranks->execute();
#my $ranks = $main::get_ranks->fetchall_hashref('rank_id');
#$main::get_ranks->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 = 100;
while($request->Accept() >= 0) {

   my $t0 = [gettimeofday];

   $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($c->{x}) || $c->{x} eq '') && defined($c->{l}) && $c->{l} ne '' && defined($c->{p}) && $c->{p} ne '' && (!defined($q->{page}) || $q->{page} eq '')) {
         $q->{page} = 'redirect';
      } elsif ((!defined($c->{x}) || $c->{x} eq '') && defined($c->{l}) && $c->{l} ne '' && defined($c->{r}) && $c->{r} ne '' && (!defined($q->{page}) || $q->{page} eq '')) {
         $q->{page} = 'redirect';
      } elsif (!defined($q->{page}) || $q->{page} eq '') {
         $q->{page} = 'frame';
      }

      if (!defined($q->{lang_id}) || $q->{lang_id} !~ /^\d+$/) {$q->{lang_id} = 1;}
#      if (!defined($q->{s}) || $q->{s} !~ /^\d+$/) {$q->{s} = 0;}
      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,
		guilds => $guilds,
		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 {
            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->{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->{theme_id} = $ret_session->{theme_id};
                  $vars->{import_messages} => $ret_session->{import_messages};
                  $vars->{frame_size} => $ret_session->{frame_size};
                  $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 $num = 0;

#      if (defined($vars->{channel_id}) && $vars->{channel_id} =~ /^\d+$/) {
#         $num = $vars->{channel_id};
#      } elsif(defined($q->{s}) && $q->{s} =~ /^\d+$/) {
         $num = $q->{s};
#      }


      if ($num != 0) {
         $main::get_last->execute($num);
         ($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();


#                  my $last_state;
         if ($world_status == 1 && $auth_status == 1 && $web_status == 1) {
            $last_state = 1;
         } elsif ($world_status == 0 && $auth_status == 0 && $web_status == 0) {
            $last_state = 0;
         } else {
            $last_state = 2;
         }

         if (!defined($q->{last_state}) || $q->{last_state} !~ /^\d+$/) {$q->{last_state} = $last_state;}

         $vars->{last_state} = $last_state;
         $vars->{world_status} = $world_status;
         $vars->{auth_status} = $auth_status;
         $vars->{web_status} = $web_status;
         $vars->{last_players} = $players+$vips;
         $vars->{last_gms} = $gamemasters;
         $vars->{last_players_h} = $horde;
         $vars->{last_players_a} = $alliance;
         $vars->{from_last_change} = $stamp;
         $vars->{last_ws} = $stamp_last_ws;
         $vars->{last_up} = $stamp_last_up;
         $vars->{last_down} = $stamp_last_down;
         $vars->{limit} = $limit;
         $vars->{server_name} = $server_name;
         $vars->{version} = $version;
         $vars->{ip} = $ip;
      }


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



      if ($q->{page} eq 'redirect') {
         $vars->{doctype} = 2;
         $vars->{title} = 1;
         $hf = 0;


         if ((!defined($c->{x}) || $c->{x} eq '') && (!defined($q->{what}) || $q->{what} eq '') && defined($c->{l}) && $c->{l} ne '' && defined($c->{p}) && $c->{p} ne '') {
            $q->{what} = 'login';
#            $q->{nick_login} = $c->{l};
#            $q->{nick_password} = $c->{p};
         } elsif ((!defined($c->{x}) || $c->{x} eq '') && (!defined($q->{what}) || $q->{what} eq '') && defined($c->{l}) && $c->{l} ne '' && defined($c->{r}) && $c->{r} ne '') {
#            $q->{what} = 'login';
#            $q->{nick_login} = $c->{l};
#warn "checkujeme... ";

#            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();
#            }
                                                                                                                                                         
#            my $ret_password_by_login_and_response = system::get_password_by_login_and_response( { login => $q->{nick_login}, response => $c->{r}, browser_hash_id => $browser_hash_id, }, );
#warn "system::get_password_by_login_and_response( { login => $q->{login}, response => $c->{r}, }, )";
#            if ($ret_password_by_login_and_response->{rv} == 1) {
#               $q->{nick_password} = $ret_password_by_login_and_response->{password};

#warn "q->{password} = $ret_password_by_login_and_response->{password}";

#            }

         }

         if ($q->{what} eq 'login') {









            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) {
                  $enc_password = $ret_check_challenge->{enc_password};
                  $q->{nick_password} = $ret_check_challenge->{password};
               }
            }

            $main::get_nick_by_enc->execute($q->{nick_login},$enc_password);

            my ($nick_id,$level,$channel_id,$email,$chat_rank,$account_state,$nick);
            my $is_ok = 0;
            if ($main::get_nick_by_enc->rows() == 1) {
               $is_ok = 1;
               ($nick_id,$level,$channel_id,$email,$chat_rank,$account_state,$nick) = $main::get_nick_by_enc->fetchrow();
              $main::get_nick_by_enc->finish();
            } else {
#               warn "main::get_nick_by_tmp_password->execute($q->{login},$q->{password});";
               
               $main::get_nick_by_tmp_password->execute($q->{nick_login},$enc_password);
               if ($main::get_nick_by_tmp_password->rows() == 1) {
                  $is_ok = 1;
                  ($nick_id,$level,$channel_id,$email,$chat_rank,$account_state,$nick) = $main::get_nick_by_tmp_password->fetchrow();
#n.id,n.level,n.channel_id,n.email,n.chat_rank,n.state,n.nick 
                  my $msg = MIME::Lite->new(
			From			=> 'PasswordChange',
			To			=> $email,
			Subject			=> 'Zaslanie noveho hesla (Automaticky generovany E-mail)',
			Type			=> 'text/plain',
			'Auto-Submitted:'	=> 'auto-generated',
			'X-Originating-IP:'	=> $ENV{REMOTE_ADDR},
			Data                    => 'Tento mail Vam bol odoslany na zaklade zmeny hesla po pouziti docasneho hesla (z IP adresy '.$ENV{REMOTE_ADDR}.')'."\n\n".'Vase nove prihlasovacie heslo bolo zmenene'."\n\n".'mine.sk Crew',
                  );

                  $msg->send;

                  $main::del_temporary_passwords_by_nick_id->execute($nick_id);
                  $main::change_enc_password->execute($enc_password,$nick_id);
                  $main::get_nick_by_tmp_password->finish();
               }
            }


            my $ret_count = sessions::get_logged_nick_count($dbh, { nick_id => $nick_id, }, );
            if ($is_ok == 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 ($nick_id == 45608) {
                  $ret_punish->{is_punished} = 1;
                  $ret_punish->{ban} = 1;
               }

               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 ($nick_id == 45608) {
                  $ret_punish->{is_punished} = 1;
                  $ret_punish->{ban} = 1;
               }

               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();

                  $location = $globals::init_script.'?page=frame&sid='.$q->{sid}.'&s='.$channel_id;

                  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();
                  }

#                  my $ret_pokec;
#                  if ($pokec_login ne '' && $pokec_password ne '' && ($pokec_id ne '' && $pokec_id != 0) && ($pokec_channel ne '' && $pokec_channel != 0)) {
#                     my $ret_select_room = pokec::select_room($pokec_i9,$pokec_channel);
#                     if ($ret_select_room->{rv} == 0) {
#                        my $ret_connect = pokec::connect($pokec_login,$pokec_password,$pokec_channel);
#                        if ($ret_connect->{rv} == 1) {
#                           $main::set_pokec_i9->execute($ret_connect->{i9},$nick_id);
#                        } else {
#                           $main::set_pokec->execute('','','','',$nick_id);
#                        }
#                     }
#                  }

                  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);
=cut
                  if (defined($q->{message}) && $q->{message} ne '') {
                     my $message;
                     if ($vars->{level} > 0 || $vars->{chat_rank} >= 6) {
                        $message = system::htmlfilter($q->{message});
                     } else {
                        my $message1 = system::bwfilter($q->{message});
                        $message = system::htmlfilter($message1);
                     }
                     $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\:\/\/)?www\.wowarmory\.sk\/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=$2]/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=$2,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$3]/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/(http\:\/\/)?www\.youtube\.com\/.*?v=([a-zA-Z0-9\_\-]+).*/) {
                         my $youtube_hash = $2;
                         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);
                            my $yt_id = $main::add_youtube_info->{mysql_insertid};
                            
                            $message =~ s/(http\:\/\/)?www\.youtube\.com\/.*?v=([a-zA-Z0-9\_\-]+).*/[youtube=$yt_id]/gs;
                         }
                      }
                     

                     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) {
                        $faction = 0;
                     } else {
                        if ($vars->{incline} == 1) {
                           $faction = 1;
                        } elsif ($vars->{incline} == 2) {
                           $faction = 2;
                        } elsif ($vars->{incline} == 3) {
                           $faction = 3;
                        }
                     }


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

                        } elsif (($faction == 0 || $faction == 2) && ($message =~ /^[\\\/]horde (.+)$/ || $message =~ /^[\\\/]h (.+)$/)) {
                           system::add_chat_message( { msg_type => 'f', faction => 2, channel_id => $q->{s}, nick_id => $nick_id, message => $1, ip => $ENV{REMOTE_ADDR} } );;
                           $main::add_history_chat->execute('c',$q->{s},$nick_id,$message,$ENV{REMOTE_ADDR});
                           if ($vars->{hold_me_frak} == 1) {
                              $q->{prepend} = 4;
                           }

                        } elsif (($faction == 0 || $faction == 1) && ($message =~ /^[\\\/]alliance (.+)$/ || $message =~ /^[\\\/]a (.+)$/)) {
                           system::add_chat_message( { msg_type => 'f', faction => 1, channel_id => $q->{s}, nick_id => $nick_id, message => $1, ip => $ENV{REMOTE_ADDR} } );;
                           $main::add_history_chat->execute('c',$q->{s},$nick_id,$message,$ENV{REMOTE_ADDR});
                           if ($vars->{hold_me_frak} == 1) {
                              $q->{prepend} = 5;
                           }

                        } elsif (($faction == 0 || $faction == 3) && ($message =~ /^[\\\/]nogroup (.+)$/ || $message =~ /^[\\\/]n (.+)$/)) {
                           system::add_chat_message( { msg_type => 'f', faction => 3, channel_id => $q->{s}, nick_id => $nick_id, message => $1, ip => $ENV{REMOTE_ADDR} } );;
                           $main::add_history_chat->execute('c',$q->{s},$nick_id,$message,$ENV{REMOTE_ADDR});
                           if ($vars->{hold_me_frak} == 1) {
                              $q->{prepend} = 6;
                           }


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

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



                        } elsif ($message =~ /^[\\\/]guild (.+)$/ || $message =~ /^[\\\/]g (.+)$/) {
                           $main::get_guild_id_by_channel_and_nick_id->execute($nick_id,$q->{s});
                           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 => $nick_id, channel_id => $q->{s}, guild_id => $guild_id, message => $1, ip => $ENV{REMOTE_ADDR}, channel_id => $q->{s}, } );
                           }
                        }

                        $main::set_chat_messages_count->execute($q->{s});
                     } else {
                        $main::get_nick_id->execute($q->{to_nick});
                        if ($main::get_nick_id->rows == 1) {
                           my $to_nick_id = $main::get_nick_id->fetchrow();
                           $main::get_ignored->execute($to_nick_id,$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);
                           }
                           $main::get_ignored->finish();
                           $main::add_private->execute($nick_id,$to_nick_id,$message,$ENV{REMOTE_ADDR},0,$deleted);
                           my $msg_id = $main::add_private->{mysql_insertid};
                           $main::add_history_private->execute($msg_id,$nick_id,$to_nick_id,$message,$ENV{REMOTE_ADDR},$deleted);
                        } else {
                           $q->{to_nick} = '?????';
                        }
                        $main::get_nick_id->finish();
                     }
                     $main::set_last_action->execute($nick_id);
#                     $q->{afk} = 0;
#                     $vars->{doafk} = 0;

                  }
#                  $main::move_unshowed_private->finish();

=cut

                  if ($q->{save} eq '1') {
                     $set_cookie  = 'Set-Cookie: l='.$q->{nick_login}.'; domain=wow.mine.sk; path=/chat; expires=Fri, 01-Jan-2015 00:00:00 GMT'."\n";
                     if (defined($q->{response}) && $q->{response} =~ /^.{64}$/) {
                        $set_cookie .= 'Set-Cookie: r='.$q->{response}.'; domain=wow.mine.sk; path=/chat; expires=Fri, 01-Jan-2016 00:00:00 GMT'."\n";
                     } else {
                        $set_cookie .= 'Set-Cookie: p='.$q->{nick_password}.'; domain=wow.mine.sk; path=/chat; expires=Fri, 01-Jan-2016 00:00:00 GMT'."\n";
                     }
                  }


                  if (!defined($c->{a}) || $c->{a} eq '') {
                     my $ret_create_new_identifier = system::create_new_identifier( { login => $q->{nick_login} }, );
                     my $identifier = $ret_create_new_identifier->{identifier};
                     my $identifier_id = $ret_create_new_identifier->{identifier_id};

                     system::add_identifier_to_nick( { nick_id => $nick_id, identifier_id => $identifier_id, }, );
                     $set_cookie .= 'Set-Cookie: a='.$identifier.'; domain=wow.mine.sk; path=/chat; expires=Fri, 01-Jan-2016 00:00:00 GMT'."\n";
                  } else {
                     system::add_identifier_to_nick( { nick_id => $nick_id, identifier => $c->{a}, }, );
                  }



               } else {
                  $location = $globals::init_script.'?page=frame&ban=1&nick_id='.$nick_id.'&sid='.$q->{sid}.'&s='.$channel_id.'&hold_to_nick='.$q->{hold_to_nick};
               }
            } else {
               $location = $globals::init_script.'?page=frame&sid='.$q->{sid}.'&s='.$channel_id;
            }

         } elsif ($q->{what} eq 'join') {

            system::add_session_to_channel( { session_id => $vars->{session_id}, channel_id => $q->{channel_id}, }, );
            $location = $globals::init_script.'?page=frame&sid='.$q->{sid}.'&s='.$q->{channel_id};


         } elsif ($q->{what} eq 'send') {

            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}, }, );

               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 $message;

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


                  $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;
                  $message =~ s/sid=$q->{sid}/sid=%S/gs;

#               $message =~ s/(http\:\/\/).+?myminicity\.com/-myminicity sux-/gsi;
                 $message =~ s/\s+ulin\.net/xn--ulin-f6a.net/gsi;


if ($vars->{nick_id} == 1) {
warn $message;
} 

                  $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/(http\:\/\/)?www\.youtube\.com\/.*?v=([a-zA-Z0-9\_\-]+).*/) {
                     my $youtube_hash = $2;
                     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);
                        my $yt_id = $main::add_youtube_info->{mysql_insertid};

                        $message =~ s/(http\:\/\/)?www\.youtube\.com\/.*?v=([a-zA-Z0-9\_\-]+).*/[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)(.*)$/) {

                              &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;
                  
                     }

#                  } elsif ($q->{to_nick} =~ /^#(\d+)$/) {
#                     my $text = $converter->convert($message);
#                     my $ret_reply = pokec::reply_rp($vars->{pokec_i9},$vars->{pokec_channel},$1,$text);
#                     if ($ret_reply->{rv} == 1) {
#
#                        my $azet_id;
#                        $main::get_pokec_azet_id->execute($ret_reply->{to_nick});
#                        if ($main::get_pokec_azet_id->rows() == 1) {
#                           $azet_id = $main::get_pokec_azet_id->fetchrow();
#                        } else {
#                           my $tmp_azet_id = pokec::get_azet_id_by_nick($vars->{pokec_i9},$vars->{pokec_channel},$ret_reply->{to_nick});
#                           if (1 == 1) {
#                              $azet_id = $tmp_azet_id->{azet_id};
#                              $main::add_pokec_azet_id->execute($azet_id,$ret_reply->{to_nick});
#                           }
#                        }
#
#                        $main::add_pokec_private_reply->execute($vars->{nick_id},$azet_id,$text);
#                        $q->{to_nick} = '';
#                     } else {
#                        $q->{to_nick} = '%23%3f%3f%3f%3f%3f%3f%3f';
#                     }
#                     $sla = 1;
                  } else {
                     $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)$/) {
  
                           &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}, }, );
   
                        } else {

                           $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, }, );
                                                   
                           }

                        }

                        if ($vars->{hold_to_nick} == 1 && $q->{hold_to_nick} == 0 && $vars->{privates_type} == 0) {
                           $q->{to_nick} = '';
                        }
                     } else {
                        $q->{to_nick} = '%3f%3f%3f%3f';
                        $q->{hold_to_nick} = 0;
                     }
                     $main::get_nick_id->finish();
                  }

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

#               $q->{afk} = '0';
#               $vars->{doafk} = 0;

               } else {
                  $q->{nick_login} = $c->{l};
                  $q->{nick_password} = $c->{p};
                  $vars->{is_punished} = $ret_punish->{is_punished};

               }

               if (!defined($q->{where}) || $q->{where} eq '') {
                  $location = $globals::init_script.'?page=send&to_nick='.$q->{to_nick}.'&sid='.$q->{sid}.'&prepend='.$q->{prepend}.'&s='.$q->{s}.'&hold_to_nick='.$q->{hold_to_nick};
                  if ($vars->{nick_id} == 0) {
                     $location .= '&message='.$q->{message};
                  }
               } elsif (defined($q->{where}) && $q->{where} eq '1') {
                  $location = $globals::misc_script.'?page=new_privates&action=new&type='.$q->{type}.'&to_nick='.$q->{to_nick}.'&sid='.$q->{sid}.'&hold_to_nick='.$q->{hold_to_nick};
               }
            }
         } elsif ($q->{what} 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->{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});


         }


      } elsif ($q->{page} eq 'send') {
         $page = 'send';
         $hf = 1;
         $location = '';
         $vars->{doctype} = 1;
         $vars->{title} = 2;
         $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();
            $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 'nicks') {
         $page = 'nicks';
         $hf = 1;
         $location = '';
         $vars->{title} = 3;


         $vars->{refresh} = 1;
         $vars->{refresh_time} = 60;
         $vars->{doctype} = 1;
         $vars->{title} = 3;
         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{lite};

         $main::get_logged_in->execute();
         $vars->{logged_in} = $main::get_logged_in->fetchrow();
         $main::get_logged_in->finish();

         $main::get_all_users->execute();
         $vars->{logged_all} = $main::get_all_users->fetchrow();
         $main::get_all_users->finish();

         $main::get_channel_info->execute($q->{s});
         my $data = $main::get_channel_info->fetchrow_hashref();
         $vars->{data} = $data;

         $vars->{post_title} = $data->{channel_name};


         $vars->{channels} = $channels;

         if (defined($q->{action}) && $q->{action} eq 'ch_channel') {

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

               my $ret_change_session_channel = system::change_session_channel( { new_channel_id => $q->{channel}, session_id => $vars->{session_id}, old_channel_id => $q->{'s'}, nick_id => $vars->{nick_id}, }, );
               if ($ret_change_session_channel->{rv} == 1) {
                  $main::set_channel->execute($q->{channel},$q->{channel},$vars->{nick_id});
                  $vars->{force_reload} = 1;
                  $vars->{channel_id} = $q->{channel};
                  $q->{s} = $q->{channel};
               }
            }
         }


         if ($vars->{logged} == 0) {
            $vars->{channel_id} = $q->{s};
         }

         $main::get_nick_friends_on_channel->execute($vars->{nick_id},$q->{s});
         my $friendlist = $main::get_nick_friends_on_channel->fetchall_arrayref({});
         $main::get_nick_friends_on_channel->finish();
         $vars->{friendlist} = $friendlist;

         $main::get_nicks->execute($q->{s},$q->{s});
         my $nicks = $main::get_nicks->fetchall_arrayref({});
         $main::get_nicks->finish();

         $main::get_armory_server_id->execute($q->{s});
         my $armory_server_id = $main::get_armory_server_id->fetchrow();
         $main::get_armory_server_id->finish();
         $vars->{armory_server_id} = $armory_server_id;

         $vars->{on_channel} = scalar(@{$nicks});

#         if ($ret_session->{show_guild} == 1) {
            my ($noguild,$g,$gma,$guild_num,$globs);
            foreach my $nick (@{$nicks}) {
               if ($nick->{global_level} > 0) {
                  if ($nick->{level} > 1) {
                     push @{$gma}, $nick;
                  } else {
                     push @{$globs}, $nick;
                  }
               } else {
                  if ($nick->{level} == 0) {
                     if ($nick->{guild_id} == 0) {
                        push @{$noguild}, $nick;
                     } else {
                        push @{$g->{$nick->{guild_id}}}, $nick;
                        ++$guild_num;
                     }
#                     my $ret_online_nick_characters = system::get_online_nick_characters( { nick_id => $nick->{nick_id}, } );
#                     $nick->{num_chars} = $ret_online_nick_characters->{num_chars};
                     $nick->{num_chars} = 0;
                  } else {
                     if ($nick->{nick_id} == 24912) {
                        push @{$globs}, $nick;
                     } else {
                        push @{$gma}, $nick;
                     }
                  }
               }

            }
            $vars->{noguild} = $noguild;
            $vars->{g} = $g;
            $vars->{gma} = $gma;
            $vars->{globs} = $globs;
            $vars->{guild_num} = $guild_num;
#         } else {
            $vars->{nicks} = $nicks;
#         }


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

         if (defined($q->{'devel'}) && $q->{'devel'} == 1) {
            $hf = 0;
            $location = $globals::ajax_script.'?page=channel&devel=1&s='.$q->{'s'}.'&sid='.$q->{sid}.'&debug='.$q->{'debug'};

         } else {
            $page = 'frame';
            $hf = 0;
            $location = '';
            $vars->{title} = 4;
         }

      } elsif ($q->{page} eq 'frame2') {
         $page = 'frame2';
         $hf = 0;
         $location = '';
         $vars->{title} = 5;


=CUT
      } elsif ($q->{page} eq 'tiny') {
         $page = 'tiny';
         $hf = 1;
         $location = '';
         $vars->{doctype} = 1;
         $vars->{title} = 6;

         if (!defined($q->{s}) || $q->{s} !~ /^\d+$/) {$q->{s} = 0;}


         $main::get_channel_info->execute($q->{s});
         my $data = $main::get_channel_info->fetchrow_hashref();
         $vars->{data} = $data;

         $vars->{post_title} = $data->{channel_name};


         if ($last_state == 1) {
            $main::get_gms->execute($q->{s},$gm_plevel);
            my $online_gms = $main::get_gms->fetchall_arrayref({});
            $main::get_gms->finish();
            $vars->{online_gms} = $online_gms;
         }

         $vars->{last_state} = $last_state;
         $vars->{theme_id} = 0;
         $vars->{chat_font} = 1;

         $main::get_chat_not_logged->execute($q->{s},$q->{s},20);
         my $lines = $main::get_chat_not_logged->fetchall_arrayref({});

         if (defined($q->{r})) {@{$lines} = reverse(@{$lines})}

         $vars->{lines} = $lines;
         $main::get_chat_not_logged->finish();

         foreach my $x (@{$lines}) {
            if ($x->{message} =~ m/\[item=(\d+)\]/) {
               $x->{message} =~ s/\[item=(\d+)\]/&rewrite_item($1)/egs;
               $x->{item} = 1;
            }
            $x->{message} = &substitutions($x->{message});
            if ($vars->{logged} == 1 && $vars->{mark_messages} == 1) {
               if ($x->{message} =~ /\b$vars->{nick}\b/i) {
                  $x->{mark} = 1;
               }
            }
         }

=cut


      } elsif ($q->{page} eq 'refresh') {
         $hf = 1;
         $location = '';
         $vars->{doctype} = 1;
         $vars->{title} = 7;
#         $vars->{background} = 'images/winter.jpg';
#         $vars->{bgproperties} = 'fixed';

#background-image: url('images/xmas-party-anime-wallpaper.jpg'); background-repeat: no-repeat;}


         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{basic};

         system::prolong_session_on_channel( { session_id => $vars->{session_id}, channel_id => $q->{s}, }, );

         $main::get_channel_info->execute($q->{s});
         my $data = $main::get_channel_info->fetchrow_hashref();
         $vars->{data} = $data;

         $vars->{post_title} = $data->{channel_name};


         if ($q->{s} == 0) {

            $page = 'refresh_channels';

            $vars->{refresh} = 1;
            $vars->{refresh_id} = 1;
            $vars->{refresh_time} = $refreshs->{$vars->{refresh_id}};
            $vars->{channels} = $channels;

            my $stats;
            $main::get_channels_stats->execute();
            foreach (@{$main::get_channels_stats->fetchall_arrayref({})}) {
               if ($_->{level} ne '') {
                  ++$stats->{$_->{channel_id}}->{admins};
               } else {
                  ++$stats->{$_->{channel_id}}->{users};
               }

               if ($_->{afk} == 0) {
                  ++$stats->{$_->{channel_id}}->{noafks};
               } else {
                  ++$stats->{$_->{channel_id}}->{afks};
               }
            }
            $main::get_channels_stats->finish();

            $vars->{stats} = $stats;

            my $friends;
            if ($vars->{logged} != 0) {
               $main::get_nick_friends_online->execute($vars->{nick_id});
               foreach (@{$main::get_nick_friends_online->fetchall_arrayref({})}) {
                  push @{$friends->{$_->{channel_id}}}, $_;
               }
               $main::get_nick_friends_online->finish();
            }
            $vars->{friends} = $friends;

            $main::get_channels_last_messages->execute();
            foreach (@{$main::get_channels_last_messages->fetchall_arrayref({})}) {
               $stats->{$_->{channel_id}}->{last_message} = $_->{dstamp};
            }
            $main::get_channels_last_messages->finish();



         } else {
=CUT
            $page = 'refresh';



            if ($q->{s} < 999) {

               $vars->{room_type} = 1;

               if ($q->{last_state} ne $last_state) {
                  if ($last_state eq '0') {
                     $vars->{direction} = 'down';
                  } elsif($last_state eq '1') {
                     $vars->{direction} = 'up';
                  } else {
                     $vars->{direction} = 'frozen';
                  } 
                  $vars->{focus} = '1';
               }

               if ($vars->{logged} == 0) {
                  if (defined($q->{s}) && $q->{s} =~ /^\d+$/) {
                     $vars->{channel_id} = $q->{s};
                  } else {
                     $vars->{channel_id} = 0;
                  }
                  $vars->{graph_id} = 21;
                  $vars->{lines_id} = 2;
                  $vars->{show_graph} = 1;
                  $vars->{show_chat} = 1;
                  $vars->{show_info} = 1;
                  $vars->{chat_font} = 1;
                  $vars->{ding_change} = 0;
                  $vars->{incline_colors} = 0;
                  $vars->{incline_chat} = 0;
                  $vars->{active_nicks} = 0;
                  $vars->{theme_id} = 0;
                  $vars->{privates_type} = 0;
                  $vars->{wowchat_new_mail} = 0;
               }

               if ($last_state == 1) {
                  $main::get_gms->execute($q->{s},$gm_plevel);
                  my $online_gms = $main::get_gms->fetchall_arrayref({});
                  $main::get_gms->finish();
                  $vars->{online_gms} = $online_gms;
               }

            } else {

               $vars->{room_type} = 2;

               if ($vars->{logged} == 0) {
                  if (defined($q->{s}) && $q->{s} =~ /^\d+$/) {
                     $vars->{channel_id} = $q->{s};
                  } else {
                     $vars->{channel_id} = 0;
                  }
                  $vars->{lines_id} = 2;
                  $vars->{show_graph} = 1;
                  $vars->{show_chat} = 1;
                  $vars->{show_info} = 1;
                  $vars->{chat_font} = 1;
                  $vars->{ding_change} = 0;
                  $vars->{incline_colors} = 0;
                  $vars->{incline_chat} = 0;
                  $vars->{active_nicks} = 0;
                  $vars->{theme_id} = 0;
                  $vars->{privates_type} = 0;
                  $vars->{wowchat_new_mail} = 0;
               }
            }


            $vars->{refresh} = 1;
#            if ($vars->{logged} == 0) {
               $vars->{refresh_id} = 2;
               $main::get_session_action->execute($q->{sid});
               my $session_action = $main::get_session_action->fetchrow_hashref();
               $vars->{announce} = $session_action;
               if ($main::get_session_action->rows > 0) {
                  $main::del_session_action->execute($session_action->{id});
               }
               $main::get_session_action->finish();
#            }
            $vars->{refresh_time} = $refreshs->{$vars->{refresh_id}};


            my $ret_punish;
#            if ($vars->{show_info} == 1) {

               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};

                  }
               }
#            }

            $vars->{gcount} = 0;

            if ($vars->{show_chat} == 1 && $q->{s} != 25) {

               my $limit = int($lines->{$vars->{lines_id}}) + 0;

               my $lines;

               if ($vars->{logged} == 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}, }, );
                  $vars->{quizz_state} = $ret_session_quizz_state_by_session_id->{quizz_state};
                  if ($vars->{guilds_type} == 1) {
                     my $ret_guild_chat_messages_count = system::get_guild_chat_messages_count( { nick_id => $vars->{nick_id}, }, );
                     $vars->{gcount} = $ret_guild_chat_messages_count->{count};
                  }
               }

               if ($vars->{privates_type} == 0 && $vars->{guilds_type} == 0 && $vars->{logged} == 0) {
                  $main::get_chat_lite->execute($q->{s},$q->{s},$vars->{nick_id},$limit);
                  if ($vars->{reverse_chat} == 1) {
                     my $tmp_lines = $main::get_chat_lite->fetchall_arrayref({});
                     my @all_tmp = reverse @{$tmp_lines};
                     $lines = \@all_tmp;
                  } else {
                     $lines = $main::get_chat_lite->fetchall_arrayref({});
                  }
                  $vars->{lines} = $lines;
                  $main::get_chat_lite->finish();

               } elsif ($vars->{privates_type} == 1 && ($vars->{guilds_type} == 1 || $vars->{guilds_type} == 0) && $vars->{logged} == 1) {

                  my $tmp_lines;
                  if ($vars->{guilds_type} == 0) {
                  
                                    
                     $main::get_chat_all_in_one_p1_g0->execute($q->{s},$vars->{nick_id},$q->{s},$q->{s},$q->{s},$q->{s},$q->{s},$q->{s},$vars->{nick_id},$vars->{nick_id},$limit);
                     $tmp_lines = $main::get_chat_all_in_one_p1_g0->fetchall_arrayref({});
                     $main::get_chat_all_in_one_p1_g0->finish();
#warn "!!!!!!!! 1";
                  } else {
                     $main::get_chat_lite->execute($q->{s},$q->{s},$vars->{nick_id},$limit);
                     $tmp_lines = $main::get_chat_lite->fetchall_arrayref({});
                     $main::get_chat_lite->finish();
#warn "!!!!!!!! 2";
                  }

                  if ($vars->{reverse_chat} == 1) {
                     my @all_tmp = reverse @{$tmp_lines};
                     $lines = \@all_tmp;
                  } else {
                     $lines = $tmp_lines
                  }
                  $vars->{lines} = $lines;

                  $main::get_chat_pms_count->execute($vars->{nick_id},$vars->{nick_id});
                  my $count = $main::get_chat_pms_count->fetchrow();
                  $vars->{count} = $count;

                  if ($vars->{logged} == 1 && scalar(@{$lines}) > 1) {

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

                           $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();
                           $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});

                           system::add_action( { action => 16, nick_id => $vars->{'nick_id'}, value => 1, }, );
                           

                           system::del_bind_sessions_aways( { nick_id => $vars->{nick_id}, }, );

#                           system::ranks_afk_check( session_id => $q->{session_id}


                        }
                        $main::set_past_action->execute($vars->{nick_id});
#                     } elsif (($vars->{afk} == 1 && $q->{set_afk} == 0 && defined($q->{set_afk})) || ($vars->{afk} == 1 && $vars->{doafk} == 0)) {
                     } elsif ($vars->{afk} == 1 && $vars->{doafk} == 0) {
                        $main::set_no_afk->execute($vars->{nick_id});
                        $main::set_last_action->execute($vars->{nick_id});
                        
                        system::add_action( { action => 16, nick_id => $vars->{'nick_id'}, value => 0, }, );
                                                   
                        
#                     } elsif ($vars->{afk} == 0 && $q->{set_afk} == 0) {
#warn "TERAZ 1";
#                        sessions::logout_nick_from_session( $dbh, { nick_id => $vars->{nick_id}, }, );
                     }

                     if ($vars->{afk} == 0) {
                        my $last_message_id;
                        if ($vars->{reverse_chat} == 1) {
                           $last_message_id = $lines->[scalar(@{$lines})-1]->{id};
                        } else {
                           $last_message_id = $lines->[0]->{id};
                        }
                        $main::set_last_message_id->execute($last_message_id,$vars->{nick_id});
                     }
                  }

               } elsif ((($vars->{privates_type} == 0 && $vars->{guilds_type} == 0) || ($vars->{privates_type} == 0 && $vars->{guilds_type} == 1)) && $vars->{logged} == 1) {

#warn "vars->{privates_type} == $vars->{privates_type} && vars->{guilds_type} == $vars->{guilds_type}";


                  my $tmp_lines;
                  if ($vars->{privates_type} == 0 && $vars->{guilds_type} == 1) {
                     $main::get_chat_all_in_one_p0_g1->execute($q->{s},$q->{s},$q->{s},$q->{s},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$limit);
                     $tmp_lines = $main::get_chat_all_in_one_p0_g1->fetchall_arrayref({});
                     $main::get_chat_all_in_one_p0_g1->finish();
                  } elsif ($vars->{privates_type} == 0 && $vars->{guilds_type} == 0) {
                     $main::get_chat_all_in_one_p0_g0->execute($q->{s},$vars->{nick_id},$q->{s},$q->{s},$q->{s},$q->{s},$q->{s},$q->{s},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$limit);
#warn "execute($q->{s},$vars->{nick_id},$q->{s},$q->{s},$q->{s},$q->{s},$q->{s},$q->{s},$vars->{nick_id},$vars->{nick_id},$vars->{nick_id},$limit);";
                     $tmp_lines = $main::get_chat_all_in_one_p0_g0->fetchall_arrayref({});
                     $main::get_chat_all_in_one_p0_g0->finish();
                  }

                  if ($vars->{reverse_chat} == 1) {
                     my @all_tmp = reverse @{$tmp_lines};
                     $lines = \@all_tmp;
                  } else {
                     $lines = $tmp_lines;
                  }


                  $vars->{lines} = $lines;

                  if ($vars->{logged} == 1 && scalar(@{$lines}) > 1) {
                     if (($vars->{afk} == 0 && $q->{set_afk} == 1) || ($vars->{afk} == 0 && $vars->{doafk} == 1)) {
                        $main::set_afk->execute($vars->{nick_id});
                        if ($ret_punish->{is_punished} == 0 || ($ret_punish->{is_punished} == 1 && $ret_punish->{stop} != 1)) {

                           system::add_action( { action => 16, nick_id => $vars->{'nick_id'}, value => 1, }, );

                           $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();
                           $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});
                        }
                        $main::set_past_action->execute($vars->{nick_id});
#                     } elsif (($vars->{afk} == 1 && $q->{set_afk} == 0 && defined($q->{set_afk})) || ($vars->{afk} == 1 && $vars->{doafk} == 0)) {
                     } elsif ($vars->{afk} == 1 && $vars->{doafk} == 0) {
                        my $lst_id = $lines->[scalar(@{$lines})-1]->{id};
                        $main::get_not_showed->execute($lst_id,$vars->{nick_id});
                        my $now_showed = $main::get_not_showed->fetchall_arrayref({});
                        foreach my $ns (@{$now_showed}) {
                           $main::set_showed_history->execute($ns->{id});
                        }

                        system::add_action( { action => 16, nick_id => $vars->{'nick_id'}, value => 0, }, );
                           

                        $main::set_no_afk->execute($vars->{nick_id});
                        $main::move_unshowed_private->execute($vars->{nick_id});
                        $main::set_last_action->execute($vars->{nick_id});
#                     } elsif ($vars->{afk} == 0 && $q->{set_afk} == 0) {
#warn "TERAZ 2";
#                        sessions::logout_nick_from_session( $dbh, { nick_id => $vars->{nick_id}, }, );
                     }

                     if ($vars->{afk} == 0) {
                        my $last_message_id;
                        if ($vars->{reverse_chat} == 1) {
                           $last_message_id = $lines->[scalar(@{$lines})-1]->{id};
                        } else {
                           $last_message_id = $lines->[0]->{id};
                        }
                        $main::set_last_message_id->execute($last_message_id,$vars->{nick_id});
                     }

#                     if ($vars->{afk} == 0 || ($vars->{afk} == 1 && $q->{set_afk} == 0 && defined($q->{set_afk})) || ($vars->{afk} == 1 && $vars->{doafk} == 0)) {
                     if ($vars->{afk} == 0 || ($vars->{afk} == 1 && $vars->{doafk} == 0)) {
                        my $lst_id = $lines->[scalar(@{$lines})-1]->{id};
                        $main::get_not_showed->execute($lst_id,$vars->{nick_id});
                        my $now_showed = $main::get_not_showed->fetchall_arrayref({});
                        foreach my $ns (@{$now_showed}) {
                           if ($vars->{nick_id} == 1) {
#                              warn "main::set_showed_chat->execute($ns->{id}) main::set_showed_chat->execute($ns->{id}) main::set_showed_chat->execute($ns->{id}) main::set_showed_history->execute($ns->{id}) main::set_showed_history->execute($ns->{id}) main::set_showed_history->execute($ns->{id})";
                           }
                           $main::set_showed_chat->execute($ns->{id});
                           $main::set_showed_history->execute($ns->{id});
                        }
                     }
                  }
               }
               
               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();
                                          

               foreach my $x (@{$lines}) {

                  my $blabla = 0;
                  if ($x->{msg_type} eq 'f' && ((((!defined($vars->{level}) || $vars->{level} == 0) && ($vars->{global_level} == 0))
                   && $vars->{incline} != $x->{faction_id}) || $vars->{logged} == 0)) {
                     if ($vars->{hide_blabla} == 1) {$x->{message} = ''; next;}
                     $blabla = 1;
                  }


                  if ($x->{message} =~ m/\[item=(\d+)\]/) {
                     if ($blabla == 0) {
                        $x->{message} =~ s/\[item=(\d+)\]/&rewrite_item($1)/egs;
                        $x->{item} = 1;
                     } else {
                        $x->{message} =~ s/\[item=(\d+)\]/XYZ/gs;
                     }
                  }
                  if ($x->{message} =~ m/\[album=(\d+),(\d+)\]/) {
                     $x->{message} =~ s/\[album=(\d+),(\d+)\]/&rewrite_photoalbum($1,$2)/egs;
                     $x->{item} = 1;
                  }


                  if ($x->{msg_type} ne 'f') {
                     $x->{message} = &substitutions($x->{message});
                  } else {
                     $x->{message} = &substitutions_lite($x->{message});
                  }

                  if ($vars->{logged} == 1 && $vars->{mark_messages} == 1) {
                     if ($x->{message} =~ /\b$vars->{nick}\b/i) {
                        $x->{mark} = 1;
                     } elsif ($x->{message} =~ /\bGM\b/) {
                        $main::admin_get_server_permissions->execute($q->{'s'},$vars->{nick_id});
                        my $perm = $main::admin_get_server_permissions->fetchrow_hashref();
                        if ($perm->{level} == 3 || $perm->{level} == 4) {
                            $x->{mark} = 1;
                        }
                        $main::admin_get_server_permissions->finish();
                     }
                  }

                  
                  if ($x->{message} =~ m/\[player=(\d+),(\d+)\]/) {
                     $x->{message} =~ s/\[player=(\d+),(\d+)\]/&system::rewrite_player($1,$2)/egs;
                     $x->{item} = 1;
                  }

                  $x->{message} =~ s/%S/$q->{sid}/gs;


#                  if ($x->{message} =~ m/\[miscpage=(.+?),&s=(\d+)\]/<a href="$globals::misc_path?page=$1&s=$2&sid=$q->{sid}">$global::map_miscpages->{$1}<\/a>/egs;
#                     $x->{item} = 1;
#                  }



#                     $message =~ s/$globals::misc_path\?page=game_account&s=(\d+)/



                  if ($blabla == 1) {
                     $x->{message} = system::htmlrefilter($x->{message});
                     if ($x->{faction_id} == 1) {
                        $x->{message} = system::translate_h($x->{message});
                     } elsif ($x->{faction_id} == 2) {
                        $x->{message} = system::translate_a($x->{message});
                     } else {
                        $x->{message} = system::translate_g($x->{message});
                     }
                     $x->{message} = system::htmlfilter($x->{message});
                     $x->{mark} = 0;
                  } else {
                     if ($x->{level} == 0 && $ignorelist->{$x->{nick_id}} == 1) {
                        $x->{ignore} = 1;
                     }
                  }


               }



               if ($vars->{global_level} > 0 && ($vars->{nick_id} == 1 || $vars->{nick_id} == 64 || $vars->{nick_id} == 4228 )) {
                  $main::get_not_activated_count->execute();
                  $vars->{not_activated_count} = $main::get_not_activated_count->fetchrow();
                  $main::get_not_activated_count->finish();
               } else {
                  $vars->{not_activated_count} = 0;
               }
                                                      
                                                      

               if ($vars->{wowchat_new_mail} != 0) {

                  $vars->{wowchat_email} =~ m/^(.+?)@(.+?)$/;
                  my $email_login = $1;
                  my $email_domain = $2;
                  $email_domain =~ s/\./-/gs;

                  my $dots;
                  opendir(DIR, '/var/qmail/popboxes/'.$email_domain.'/'.$email_login.'/Maildir/new') || warn "can't opendir";
                  @{$dots} = grep { !/^\./ && -f '/var/qmail/popboxes/'.$email_domain.'/'.$email_login.'/Maildir/new/'.$_ } readdir(DIR);
                  closedir DIR;

                  if (scalar(@{$dots}) != $vars->{wowchat_new_mail}) {
                     $main::set_nick_wowchat_new_mail->execute(scalar(@{$dots}),$vars->{nick_id});
                  }
               }
            }
=cut
         }

      } elsif ($q->{page} eq 'gradient') {
         $page = 'gradient';
         $hf = 1;
         $location = '';
         $vars->{doctype} = 1;

         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{lite};
         if ($q->{left} == 1) {
            $vars->{background} = 'images/lgradient'.$vars->{theme_id}.'.gif';
         } else {
            $vars->{background} = 'images/gradient'.$vars->{theme_id}.'.gif';
         }


      } elsif ($q->{page} eq 'panel') {
         $page = 'panel';
         $hf = 1;
         $location = '';
         $vars->{doctype} = 1;
         $vars->{title} = 8;

         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{lite};


      } elsif ($q->{page} eq 'panel_static') {
         $page = 'panel_static';
         $hf = 1;
         $location = '';
         $vars->{doctype} = 2;
         $vars->{title} = 9;

         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{lite};


      } elsif ($q->{page} eq 'join_channels') {
         $page = 'join_channels';
         $hf = 1;
         $location = '';
         $vars->{doctype} = 2;
         $vars->{title} = 10;

         $vars->{bgcolor} = $map_backgrounds->{$vars->{theme_id}}->{lite};

         $main::get_logged_in->execute();
         $vars->{logged_in} = $main::get_logged_in->fetchrow();
         $main::get_logged_in->finish();

         $main::get_all_users->execute();
         $vars->{logged_all} = $main::get_all_users->fetchrow();
         $main::get_all_users->finish();

         $vars->{channels} = $channels;

         my $ret_get_channels_on_nick_id_is = system::get_channels_on_nick_id_is ( { nick_id => $vars->{nick_id}, } );
         my $is_on;
         foreach (@{$ret_get_channels_on_nick_id_is->{channels}}) {
            $is_on->{$_->{channel_id}} = 1;
         }

         $vars->{is_on} = $is_on;


      } 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};
                                          

      }




      if ($location eq '' && -f $globals::datadir."/templates/".$page.".tt2") {
         $vars->{elapsed} = &tv_interval($t0);;
         $vars->{utime} = $t0->[0];
         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 ($hf == 1) {$template->process('footer.tt2', $vars, \$html) || warn $template->error();}
         if ($usegzip) {$html = Compress::Zlib::memGzip( $html );}
         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';
      }
   }

   $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 htmlfilter($) {
   my ($message) = @_;
   $message =~ s/&/&amp;/gs;
   $message =~ s/</&lt;/gs;
   $message =~ s/>/&gt;/gs;
   return $message;
}

sub htmlrefilter($) {
   my ($message) = @_;
   $message =~ s/&amp;/&/gs;
   $message =~ s/&lt;/</gs;
   $message =~ s/&gt;/>/gs;
   return $message;
}




sub wrapper($) {
   my ($line) = @_;

#   my $out;
#   while ($line =~ m/(.{0,80})/gs) {
#      my $l = $1;
#      if ($l !~ m/^(.{60,80})\s(.*)$/) {
#         $l .= ' ';
#      }
#      $out .= $l;
#   }

   return $line;
}



sub rewrite_item($) {
   my ($item_id) = @_;
   $main::get_item_lite->execute($item_id);
   my $item = $main::get_item_lite->fetchrow_hashref();
   $main::get_item_lite->finish();

   return '<span class="t1xt'.$map_qualities->{$item->{quality}}.'"><a href="javascript:void(0)" onclick="ai(\''.$item_id.'\')">+</a><a href="javascript:void(0)" onclick="si(\''.$item_id.'\')">Item: ['.$item->{name1}.']</a></span>';
}



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);
}


sub substitute($) {
   my ($to_substitute) = @_;
   foreach my $subst (@{$substitutions}) {
      $to_substitute =~ s/(\b)$subst->{shortcut}(\b)/$1S&$subst->{id}&$2/gsi;
   }
   return $to_substitute;
}


sub substitutions($) {
   my ($to_substitute) = @_;
   $to_substitute =~ s/S&(\d+)&/<font title="$substitutions_id->{$1}->{value}" style="cursor:help">$substitutions_id->{$1}->{shortcut}<\/font>/g;
   return $to_substitute;
}


sub substitutions_lite($) {
   my ($to_substitute) = @_;
   $to_substitute =~ s/S&(\d+)&/$substitutions_id->{$1}->{shortcut}/g;
   return $to_substitute;
}

sub rewrite_profile($) {

# http://wow.mine.sk/chat/misc.fcgi?page=show_profile&sid=eokq0kfddlp8&nick_id=1

}

sub rewrite_photoalbum($) {
   my ($nick_id,$album_id) = @_;

   my $ret_photoalbum_by_id_and_owner = system::get_photoalbum_by_id_and_owner( { album_id => $album_id, nick_id => $nick_id, }, );
   if ($ret_photoalbum_by_id_and_owner->{rows} == 1) {
      return '{ Album: <a target="_blank" href="misc.fcgi?album_id='.$album_id.'&nick_id='.$nick_id.'&page=show_album">'.$ret_photoalbum_by_id_and_owner->{album}->{album_name}.'</a> }';
   } else {
      return '{ Neznamy album }';
   }
# http://wow.mine.sk/chat/misc.fcgi?album_id=6&nick_id=1&page=show_album&sid=eokq0kfddlp8

}













sub emote($) {
   my ($params) = @_;
   
   my $message;
   my $to_nick_id = 0;

   if (defined($params->{target_id}) && $params->{target_id} ne '') {
      $to_nick_id = $params->{target_id};
   }

#warn "params->{suffix} = $params->{suffix} ... $to_nick_id";
   
   if (defined($params->{suffix}) && $params->{suffix} =~ /^ (.+)$/ && $to_nick_id == 0) {
      $params->{target} = $1;
#warn "params->{target} = $params->{target}";
      $main::get_nick_id->execute($params->{target});
      if ($main::get_nick_id->rows == 1) {
         $to_nick_id = $main::get_nick_id->fetchrow();
#warn "to_nick_id = $to_nick_id";
      }
      $main::get_nick_id->finish();
   }
   
   if ($to_nick_id != 0) {


      if ($params->{emote} =~ /^cry$/) {
         $message = 'cries on '.$params->{target}.'\'s shoulder.';
      } elsif ($params->{emote} =~ /^applaud$/) {
         $message = 'applauds at '.$params->{target}.'. Bravo!';
      } elsif ($params->{emote} =~ /^fart$/) {
         $message = 'brushes up against '.$params->{target}.' and fart loudly.';
      } elsif ($params->{emote} =~ /^rofl$/) {
         $message = 'rolls on the floor laughing at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^rude$/) {
         $message = 'makes a rude gesture at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^salute$/) {
         $message = 'salutes '.$params->{target}.' with respect.';
      } elsif ($params->{emote} =~ /^scare$/) {
         $message = 'is scared of '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^scratch$/) {
         $message = 'scratches '.$params->{target}.'. How catty!';
      } elsif ($params->{emote} =~ /^spit$/) {
         $message = 'spits on '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^surprised$/) {
         $message = 'is surprised by '.$params->{target}.'\'s actions.';
      } elsif ($params->{emote} =~ /^excited$/) {
         $message = 'talks excitedly with '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^tired$/) {
         $message = 'lets '.$params->{target}.' know that he is tired.';
      } elsif ($params->{emote} =~ /^wave$/) {
         $message = 'waves at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^jk$/) {
         $message = 'lets '.$params->{target}.'know that she was just kidding!';
      } elsif ($params->{emote} =~ /^lick$/) {
         $message = 'licks '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^listen$/) {
         $message = 'listens intently to '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^kiss$/ || $params->{emote} =~ /^blow$/) {
         $message = 'blows '.$params->{target}.' a kiss.';
      } elsif ($params->{emote} =~ /^kneel$/) {
         $message = 'kneels before '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^sexy$/) {
         $message = 'thinks '.$params->{target}.' is a sexy devil.';
      } elsif ($params->{emote} =~ /^smell$/) {
         $message = 'smells '.$params->{target}.'. Wow, someone stinks!';
      } elsif ($params->{emote} =~ /^apologize$/) {
         $message = 'apologizes to '.$params->{target}.'. Sorry!';
      } elsif ($params->{emote} =~ /^bite$/) {
         $message = 'bites '.$params->{target}.'. Ouch!';
      } elsif ($params->{emote} =~ /^bye$/) {
         $message = 'waves goodbye to '.$params->{target}.'. Farewell!';
      } elsif ($params->{emote} =~ /^congrats$/ || $params->{emote} =~ /^cong$/) {
         $message = 'congratulates '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^flex$/) {
         $message = 'flexes at '.$params->{target}.'. Oooooh so strong!';
      } elsif ($params->{emote} =~ /^hello$/ || $params->{emote} =~ /^hi$/) {
         $message = 'greets '.$params->{target}.' with a hearty hello!';
      } elsif ($params->{emote} =~ /^hug$/) {
         $message = 'hugs '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^hungry$/) {
         $message = 'is hungry. Maybe '.$params->{target}.' has some food...';
      } elsif ($params->{emote} =~ /^laugh$/) {
         $message = 'laughs at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^massage$/) {
         $message = 'massages '.$params->{target}.'\'s shoulders.';
      } elsif ($params->{emote} =~ /^shy$/) {
         $message = 'smiles shyly at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^bark$/) {
         $message = 'barks at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^smile$/) {
         $message = 'smiles at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^chicken$/) {
         $message = 'struts around '.$params->{target}.' with arms flapping. Cluck, Cluck, Chicken!';
      } elsif ($params->{emote} =~ /^hail$/) {
         $message = 'hails '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^love$/) {
         $message = 'loves '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^no$/) {
         $message = 'tells '.$params->{target}.' NO. Not going to happen.';
      } elsif ($params->{emote} =~ /^greet$/) {
         $message = 'greets '.$params->{target}.' warmly.';
      } elsif ($params->{emote} =~ /^taunt$/) {
         $message = 'makes a taunting gesture at '.$params->{target}.'. Bring it!';
      } elsif ($params->{emote} =~ /^dance$/) {
         $message = 'dances with '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^thirsty$/) {
         $message = 'lets '.$params->{target}.' know he is thirsty. Spare a drink?';
      } elsif ($params->{emote} =~ /^pray$/) {
         $message = 'says a prayer for '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^thanks$/) {
         $message = 'thanks '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^slap$/) {
         $message = 'slaps '.$params->{target}.' across the face. Ouch!';
      } elsif ($params->{emote} =~ /^wink$/) {
         $message = 'winks slyly at '.$params->{target}.'.';
      } elsif ($params->{emote} =~ /^cheer$/) {
         $message = 'cheers at '.$params->{target}.'!';
      } elsif ($params->{emote} =~ /^bored$/) {
         $message = 'is terribly bored with '.$params->{target}.'.';
      }

   
   
   } else {

      if ($params->{emote} =~ /^cry$/) {
         $message = 'cries.';
      } elsif ($params->{emote} =~ /^applaud$/) {
         $message = 'applauds. Bravo!';
      } elsif ($params->{emote} =~ /^fart$/) {
         $message = 'farts loudly. Whew...what stinks?';
      } elsif ($params->{emote} =~ /^rofl$/) {
         $message = 'rolls on the floor laughing.';
      } elsif ($params->{emote} =~ /^rude$/) {
         $message = 'makes a rude gesture.';
      } elsif ($params->{emote} =~ /^salute$/) {
         $message = 'salutes you with respect.';
      } elsif ($params->{emote} =~ /^scare$/) {
         $message = 'is scared!';
      } elsif ($params->{emote} =~ /^scratch$/) {
         my $who;
         if ($params->{sex} eq '') {$who = 'it';} elsif ($params->{sex} eq '1') {$who = 'him';} elsif ($params->{sex} eq '2') {$who = 'her';}
         $message = 'scratches '.$who.'self. Ah, much better!';
      } elsif ($params->{emote} =~ /^sleep$/) {
         $message = 'falls asleep. Zzzzzzz.';
      } elsif ($params->{emote} =~ /^spit$/) {
         $message = 'spits on the ground.';
      } elsif ($params->{emote} =~ /^surprised$/) {
         $message = 'is so surprised!';
      } elsif ($params->{emote} =~ /^excited$/) {
         $message = 'talks excitedly with everyone.';
      } elsif ($params->{emote} =~ /^tired$/) {
         my $who;
         if ($params->{sex} eq '') {$who = 'it';} elsif ($params->{sex} eq '1') {$who = 'he';} elsif ($params->{sex} eq '2') {$who = 'she';}
         $message = 'lets everyone know that '.$who.' is tired.';
      } elsif ($params->{emote} =~ /^wave$/) {
         $message = 'waves';
      } elsif ($params->{emote} =~ /^jk$/) {
         $message = 'was just kidding!';
      } elsif ($params->{emote} =~ /^lick$/) {
         my $who;
         if ($params->{sex} eq '') {$who = 'its';} elsif ($params->{sex} eq '1') {$who = 'his';} elsif ($params->{sex} eq '2') {$who = 'her';}
         $message = 'licks '.$who.' lips.';
      } elsif ($params->{emote} =~ /^listen$/) {
         $message = 'is listening!';
      } elsif ($params->{emote} =~ /^kiss$/ || $params->{emote} =~ /^blow$/) {
         $message = 'blows a kiss into the wind.';
      } elsif ($params->{emote} =~ /^kneel$/) {
         $message = 'kneels down.';
      } elsif ($params->{emote} =~ /^sexy$/) {
         $message = 'is too sexy for his tunic...so sexy it hurts.';
      } elsif ($params->{emote} =~ /^smell$/) {
         my $who;
         if ($params->{sex} eq '') {$who = 'it';} elsif ($params->{sex} eq '1') {$who = 'him';} elsif ($params->{sex} eq '2') {$who = 'her';}
         $message = 'smells the air around '.$who.'. Wow, someone stinks!';
      } elsif ($params->{emote} =~ /^apologize$/) {
         $message = 'apologizes to everyone.  Sorry!';
      } elsif ($params->{emote} =~ /^bite$/) {
         $message = 'looks around for someone to bite.';
      } elsif ($params->{emote} =~ /^bye$/) {
         $message = 'waves goodbye to everyone. Farewell!';
      } elsif ($params->{emote} =~ /^congrats$/ || $params->{emote} =~ /^cong$/) {
         $message = 'congratulates everyone.';
      } elsif ($params->{emote} =~ /^flex$/) {
         my $who;
         if ($params->{sex} eq '') {$who = 'its';} elsif ($params->{sex} eq '1') {$who = 'his';} elsif ($params->{sex} eq '2') {$who = 'her';}
         $message = 'flexes '.$who.' muscles. Oooooh so strong!';
      } elsif ($params->{emote} =~ /^hi$/ || $params->{emote} =~ /^hello$/) {
         $message = 'greets everyone with a hearty hello!';
      } elsif ($params->{emote} =~ /^hug$/) {
         $message = 'needs a hug!';
      } elsif ($params->{emote} =~ /^hungry$/) {
         $message = 'is hungry!';
      } elsif ($params->{emote} =~ /^laugh$/) {
         $message = 'laughs.';
      } elsif ($params->{emote} =~ /^massage$/) {
         $message = 'needs a massage!';
      } elsif ($params->{emote} =~ /^shy$/) {
         $message = 'smiles shyly.';
      } elsif ($params->{emote} =~ /^bark$/) {
         $message = 'barks. Woof woof!';
      } elsif ($params->{emote} =~ /^smile$/) {
         $message = 'smiles.';
      } elsif ($params->{emote} =~ /^chicken$/) {
         $message = 'struts around with arms flapping. Cluck, Cluck, Chicken!';
      } elsif ($params->{emote} =~ /^hail$/) {
         my $who;
         if ($params->{sex} eq '') {$who = 'it';} elsif ($params->{sex} eq '1') {$who = 'him';} elsif ($params->{sex} eq '2') {$who = 'her';}
         $message = 'hails everyone around '.$who.'.';
      } elsif ($params->{emote} =~ /^love$/) {
         $message = 'feels the love.';
      } elsif ($params->{emote} =~ /^no$/) {
         $message = 'clearly states, NO.';
      } elsif ($params->{emote} =~ /^greet$/) {
         $message = 'greets everyone warmly.';
      } elsif ($params->{emote} =~ /^taunt$/) {
         my $who;
         if ($params->{sex} eq '') {$who = 'it';} elsif ($params->{sex} eq '1') {$who = 'him';} elsif ($params->{sex} eq '2') {$who = 'her';}
         $message = 'taunts everyone around '.$who.'. Bring it fools!';
      } elsif ($params->{emote} =~ /^dance$/) {
         $message = 'bursts into dance.';
      } elsif ($params->{emote} =~ /^thirsty$/) {
         $message = 'is so thirsty. Can anyone spare a drink?';
      } elsif ($params->{emote} =~ /^pray$/) {
         $message = 'prays to the Gods.';
      } elsif ($params->{emote} =~ /^thanks$/) {
         $message = 'thanks everyone.';
      } elsif ($params->{emote} =~ /^slap$/) {
         $message = 'slaps himself across the face. Ouch!';
      } elsif ($params->{emote} =~ /^wink$/) {
         $message = 'winks slyly.';
      } elsif ($params->{emote} =~ /^cheer$/) {
         $message = 'cheers!';
      } elsif ($params->{emote} =~ /^bored$/) {
         $message = 'is overcome with boredom. Oh the drudgery!';
      }
   }

   my $ret_message = system::add_chat_message( { msg_type => 'm', channel_id => $params->{channel_id}, nick_id => $params->{nick_id}, message => $message, ip => $params->{ip}, }, );
   system::add_action( { action => 1, channel_id => $params->{channel_id}, message_id => $ret_message->{message_id}, }, );
                           

}


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