#!/usr/bin/perl
# This Script and the readme may only be given away "as is", unmodified
# and complete. The Script is Freeware.
# Created and Copyright by Ralf Gueldemeister <ralfg@bigfoot.com>
# on 25.12.98

require config; 

# HTML Part
#
########################


#REGISTER.HTML - Printed when user registers new nick
sub register_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Регистрация нового ника</TITLE></HEAD>
$html_bodytag
<CENTER>
<H1><I>Регистрация нового ника</I></H1>
<FORM METHOD=POST ACTION="$script2_name">
<INPUT TYPE=HIDDEN NAME="action" VALUE="create_nick">
<TABLE><TR><TD>
<B>new Ник: </B></TD><TD><INPUT NAME="name"><BR></TD></TR>
<TR><TD><B>Пароль:</B> </TD><TD><INPUT TYPE=PASSWORD NAME="password"><BR></TD></TR>
<TR><TD><B>Ещё раз пароль:</B> </TD><TD><INPUT TYPE=PASSWORD NAME="password2"><BR></TD></TR>
<TR><TD><B>eMail:<BR> (Только для администрации)</B> </TD><TD><INPUT NAME="email"><BR>
</TD></TR></TABLE>
<INPUT TYPE=SUBMIT VALUE="Регистрация">
</FORM>
</CENTER>
</BODY>
</HTML>
[END]
}

#BANNER.HTML - Баннер вверху - можете изменить или удалить!
sub banner_html {
    print <<"[END]";
<HTML>$html_bodytag

<A HREF="$banner_link" TARGET="_blank"><IMG SRC="$banner_picture" BORDER=0></A>

</BODY></HTML>
[END]
}

#OPTIONS.HTML - the options page
sub options_html {
    print <<"[END]";
<HTML><HEAD><TITLE>$html_title - Опции</TITLE></HEAD>
$html_bodytag
<CENTER>
<H1><I>Опции</I></H1>
<FORM METHOD=POST ACTION="$script2_name">
<INPUT TYPE=HIDDEN NAME="action" VALUE="setoptions">
<INPUT TYPE=HIDDEN NAME="name" VALUE="$query{'name'}">
<INPUT TYPE=HIDDEN NAME="password" VALUE="$query{'password'}">
<TABLE>
<TR><TD>Время обновления (сек): </TD><TD><INPUT SIZE="10" NAME="updatefrequency" VALUE=$query{'updatefrequency'}></TD></TR>
<TR><TD>Цвет шрифта:</TD><TD><SELECT NAME="color">
<OPTION SELECTED VALUE="$query{'color'}">текущий</OPTION>
<OPTION VALUE="standard">стандартный</OPTION>
<OPTION VALUE="standard">--------</OPTION>
<OPTION VALUE="0000FF">синий</OPTION>
<OPTION VALUE="008000">зелёный</OPTION>
<OPTION VALUE="FF0000">красный</OPTION>
<OPTION VALUE="000000">чёрный</OPTION>
<OPTION VALUE="FFFFFF">белый</OPTION>
<OPTION VALUE="800000">марон</OPTION>
<OPTION VALUE="808000">маслина</OPTION>
<OPTION VALUE="000080">тёмно синий</OPTION>
<OPTION VALUE="800080">фиолетовый</OPTION>
<OPTION VALUE="808080">серый</OPTION>
<OPTION VALUE="C0C0C0">серебро</OPTION>
<OPTION VALUE="00FF00">салатный</OPTION>
<OPTION VALUE="FFFF00">жёлтый</OPTION>
<OPTION VALUE="FF00FF">сиреневый</OPTION>
<OPTION VALUE="00FFFF">голубой</OPTION>
<OPTION VALUE="008080">Рабочий стол</OPTION>
</SELECT></TD></TR>
<TR><TD>Порядок сообщений</TD><TD><SELECT NAME="new_msg_on_top">
<OPTION VALUE="$query{'new_msg_on_top'}" SELECTED>Текущий</OPTION>
<OPTION VALUE="1">новые вверху</OPTION>
<OPTION VALUE="0">новые внизу</OPTION>
</SELECT></TD></TR>
<TR><TD><H3>Изменить пароль</H3></TR></TD>
<TR><TD>Старый пароль: </TD><TD><INPUT TYPE=PASSWORD NAME="change_pwd_old"></TD></TR>
<TR><TD>Новый пароль: </TD><TD><INPUT TYPE=PASSWORD NAME="change_pwd_new"></TD></TR>
<TR><TD>Новый пароль: </TD><TD><INPUT TYPE=PASSWORD NAME="change_pwd_new2"></TD></TR>
</TABLE>
<INPUT TYPE=SUBMIT VALUE="Запомнить">
</FORM>
</CENTER></BODY></HTML>
[END]
}


#USERINFO.HTML - informations about the users, click on user in online list
sub userinfo_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Информация пользователя</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Информация пользователя</I></H1>
[END]

    print "<TABLE><TR><TD VALIGN=top><IMG SRC=\"$userinfo{'photo_url'}\"></TD><TD VALIGN=top>" if ($userinfo{'photo_url'} ne "");
    print "<TABLE>";
    print "<TR><TD><B>Ник</B>:</TD><TD>$query{'infoabout'}</TD></TR>";
    print "<TR><TD><B>Имя</B>:</TD><TD>$userinfo{'realname'}</TD></TR>";
    print "<TR><TD><B>email</B>:</TD><TD><A HREF=\"mailto:$userinfo{'email'}\">$userinfo{'email'}</A></TD></TR>";
    print "<TR><TD><B>Возраст</B>:</TD><TD>$userinfo{'age'}</TD></TR>";
    print "<TR><TD><B>Город</B>:</TD><TD>$userinfo{'city'}</TD></TR>";
    print "<TR><TD><B>Страна</B>:</TD><TD>$userinfo{'country'}</TD></TR>";
    print "<TR><TD><B>Домашняя страничка</B>:</TD><TD><A HREF=\"$userinfo{'url'}\">$userinfo{'url'}</A></TD></TR>";
    print "<TR><TD><B>ICQ номер</B>:</TD><TD>$userinfo{'icq_uin'}</TD></TR>";
    print "<TR><TD VALIGN=top><B>Другая инфа</B>:</TD><TD>$userinfo{'stuff'}</TD></TR>";
    print "</TABLE>";
    print "</TD></TR></TABLE>" if ($userinfo{'photo_url'} ne "");

    print <<"[END]";
</CENTER>
</BODY>
</HTML>
[END]
}

#CHANGEUSERINFO.HTML - change user informations
sub changeuserinfo_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Изменение информации пользователя</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Изменение информации пользователя</I></H1>
<TABLE>
<FORM METHOD=POST ACTION="$script2_name">
<INPUT TYPE=hidden NAME="action" VALUE="setuserinfo">
<INPUT TYPE=HIDDEN NAME="name" VALUE="$query{'name'}">
<INPUT TYPE=HIDDEN NAME="password" VALUE="$query{'password'}">
<INPUT TYPE=HIDDEN NAME="color" VALUE="$query{'color'}">
<INPUT TYPE=HIDDEN NAME="new_msg_on_top" VALUE="$query{'new_msg_on_top'}">
<INPUT TYPE=HIDDEN NAME="updatefrequency" VALUE="$query{'updatefrequency'}">
<TR><TD><B>Имя</B>:</TD><TD><INPUT NAME="realname" VALUE="$userinfo{'realname'}"></TD></TR>
<TR><TD><B>email</B>:</TD><TD><INPUT NAME="email" VALUE="$userinfo{'email'}"></TD></TR>
<TR><TD><B>Страна</B>:</TD><TD><INPUT NAME="country" VALUE="$userinfo{'country'}"></TD></TR>
<TR><TD><B>Город</B>:</TD><TD><INPUT NAME="city" VALUE="$userinfo{'city'}"></TD></TR>
<TR><TD><B>Возраст</B>:</TD><TD><INPUT NAME="age" VALUE="$userinfo{'age'}"></TD></TR>
<TR><TD><B>Домашняя страница (URL)</B>:</TD><TD><INPUT NAME="url" VALUE="$userinfo{'url'}"></TD></TR>
<TR><TD><B>Фото (URL)</B>:</TD><TD><INPUT NAME="photo_url" VALUE="$userinfo{'photo_url'}"></TD></TR>
<TR><TD><B>ICQ номер</B>:</TD><TD><INPUT NAME="icq_uin" VALUE="$userinfo{'icq_uin'}"></TD></TR>
<TR><TD VALIGN=top><B>Другая инфа</B>:</TD><TD><TEXTAREA ROWS=10 COLS=50 NAME="stuff">$userinfo{'stuff'}</TEXTAREA></A></TD></TR>
</TABLE>
<INPUT TYPE=SUBMIT VALUE="Записать"></FORM>
</CENTER>
</BODY>
</HTML>
[END]
}

#SCRIPTLINKS.HTML - Links to other chatscripts
sub scriptlinks_html {
    print <<"[END]";
<HTML>$html_bodytag
<A HREF="chat2.cgi?action=login&name=$query{'name'}&password=$query{'password'}" TARGET="_parent">chat 2</A>
</BODY></HTML>
[END]
}

#ILLEGAL_NICK.HTML - when nick containing illegal characters is created
sub illegal_nick_html {
    print <<"[END]";
<HTML><HEAD><TITLE>Недопустимый ник</TITLE></HEAD>
$html_bodytag
<CENTER>
<H1><I>Недопустимый ник</I></H1>
<B>Ваш ник "$query{'name'}" содержит недопустимые символы <BR>Ник может содержать только буквы цифры и символ подчёркивания "_".</B>
<BR><B><A HREF="$script2_name?action=register">Повтор</A></B>
</CENTER></BODY></HTML>
[END]
}

#ILLEGAL_PASS.HTML - when nick with password containing illegal characters is created
sub illegal_pass_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Недопустимый пароль</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Недопустимый пароль</I></H1>
<B>Пароль не может содержать ";"</B><BR>
<B><A HREF="$script2_name?action=register">Повтор</A></B>
</CENTER>
</BODY>
</HTML>
[END]
}

#PASS_CHECK_FAILED_HTML - when password is different from password 2
sub pass_check_failed_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Ошибка проверки паролей</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Ошибка проверки паролей</I></H1>
<B>Пароли которые Вы ввели не одинаковы</B><BR>
<B><A HREF="$script2_name?action=register">Повтор</A></B>
</CENTER>
</BODY>
</HTML>
[END]
}

#EXISTINGNICK.HTML - Nick already exists
sub existingnick_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Ник уже существует</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Ник уже существует</I></H1>
<A HREF="$script2_name?action=register"><B>попробуйте другой ник</B></A>
</CENTER>
</BODY>
</HTML>
[END]
}

#NICKCREATED.HTML - after nick is registered
sub nickcreated_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Ваш ник зарегистрирован</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Ваш ник зарегистрирован</I></H1>
<B><A HREF="$script_name">Вход</A></B>
</CENTER>
</BODY>
</HTML>
[END]
}

#CHATFRAMES.HTML
sub chatframes_html {
	print "<HTML><HEAD><TITLE>$html_title</TITLE></HEAD>\n";
	if ($banner_picture) {
		print " <FRAMESET ROWS=\"65,*,60\" BORDER=0 FRAMEBORDER=0 FRAMESPACING=0>\n"
	} else {
		print " <FRAMESET ROWS=\"*,60\" BORDER=0 FRAMEBORDER=0 FRAMESPACING=0>\n"
	}
	print "  <FRAME SRC=\"$script2_name?action=banner\" SCROLLING=NO>\n" if ($banner_picture);
	print "  <FRAMESET COLS=\"*,150\" BORDER=0 FRAMEBORDER=0 FRAMESPACING=0>\n";
	print "   <FRAME NAME=\"main\" SRC=\"$script_name?action=chat&name=$query{'name'}&password=$query{'password'}&updatefrequency=$query{'updatefrequency'}&color=$query{'color'}&new_msg_on_top=$query{'new_msg_on_top'}#end\">  \n";
#	print "	   <FRAMESET ROWS=\"*,100\" BORDER=0 FRAMEBORDER=0 FRAMESPACING=0> \n"; #UNCOMMENT IF YOU WANT MULTIPLE SCRIPT SUPPORT
	print "    <FRAME SRC=\"$script_name?action=stillalive&name=$query{'name'}&password=$query{'password'}&updatefrequency=$query{'updatefrequency'}&color=$query{'color'}&new_msg_on_top=$query{'new_msg_on_top'}\">    \n";
#	print "    <FRAME SRC=\"$script2_name?action=scriptlinks&name=$query{'name'}&password=$query{'password'}\" scrolling=auto>\n"; #UNCOMMENT IF YOU WANT MULTIPLE SCRIPT SUPPORT
	print "   </FRAMESET>\n";
#	print "  </FRAMESET>\n"; #UNCOMMENT IF YOU WANT MULTIPLE SCRIPT SUPPORT
	print "  <FRAME SRC=\"$script_name?action=chatinput_html&name=$query{'name'}&password=$query{'password'}&updatefrequency=$query{'updatefrequency'}&color=$query{'color'}&new_msg_on_top=$query{'new_msg_on_top'}\" scrolling=no>\n";
	print "</FRAMESET>\n";
	print "</HTML>\n";
}

#CHAT_IS_FULL.HTML - when chat room is full
sub chat_is_full_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - чат полон</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Чат переполнен</I></H1>
Жаль, но чат переполнен. Попробуйте зайти попозже.

<BR><A HREF="$script_name">Назад</A></B>
</CENTER>
</BODY>
</HTML>
[END]
}

sub send_pwd_html {
    print <<"[END]";
<HTML>
<HEAD><TITLE>$html_title - Забытый пароль</TITLE>
</HEAD>
$html_bodytag
<CENTER>
<H1><I>Отправка пароля</I></H1>
Пароль был послан Вам на ($query{'email'}).<BR>
<BR><A HREF="$script_name">Назад</A></B>
</CENTER>
</BODY>
</HTML>
[END]
}

# Main Part - DON'T CHANGE ANYTHING HERE!
#
#######################



&action;    # Fuehrt je nach action variable gegebene sub aus
	    # action im FORM definieren!

exit;

sub action {
    if ($qs eq "") { # Wenn query_string leer sprung zum
    	&error("Надо использовать не этот файл, а файл chat.cgi ");
    } 
    elsif ($query{'action'} eq "register") {
        &header;
        &register_html;
    }
    elsif ($query{'action'} eq "login") {
    	&login;
    }
    elsif ($query{'action'} eq "create_nick") {
    	&create_nick;
    }
    elsif ($query{'action'} eq "banner") {
        &header;
        &banner_html;
    }
    elsif ($query{'action'} eq "options_html") {
        &header;
        &options_html;
    }
    elsif ($query{'action'} eq "setoptions") {
        &setoptions;
    }
    elsif ($query{'action'} eq "gotourl") {
        &gotourl;
    }
    elsif ($query{'action'} eq "userinfo") {
        &userinfo;
    }
    elsif ($query{'action'} eq "changeuserinfo") {
        &changeuserinfo;
    }
    elsif ($query{'action'} eq "setuserinfo") {
        &setuserinfo;
    }
    elsif ($query{'action'} eq "show_users") {
        &show_users;
    }
    elsif ($query{'action'} eq "scriptlinks") {
        &header;
        &scriptlinks_html;
    }
    elsif ($query{'action'} eq "send_pwd") {
        &send_pwd;
    }
    else {
    	&error;
    } 
}


sub login { # Loginprozedur 
    # check login name+password
    if (-e "$data_dir/$data_nicks_file") {  # wenn nickfile existiert dann oeffnen
    	open (NICKFILE, "<$data_dir/$data_nicks_file") || &error("::Невозможно открыть $data_dir/$data_nicks_file ::");
    } 
    else {  # sonst nonick_html
    	&header;
    	&nonick_html;
        exit;
    }

    # check if ip is banned
    open (BANFILE, "<$data_dir/$data_banned_file");
    my $banfile = <BANFILE>;
    my @banfiletemp = split(/;;/, $banfile);
    for (@banfiletemp) {
        if ("ip:".$ENV{'REMOTE_ADDR'} eq $_) {
            &header;
            &banned_html;
	    exit;
    	}
    }

    &max_user_limit; # check if chat is full

    my @nickfile = <NICKFILE>; # Daten aus nickfile an @nickfile uebergeben
    close NICKFILE; # nickfile schliessen
    
	my @nickfile_matrix = ();

	for (my $i = 0; $i <= $#nickfile; $i++) {
		chomp($nickfile[$i]);
		push(@nickfile_matrix, [split(/;;/, $nickfile[$i])]);
	}

    
    for (my $i=0; $i<=$#nickfile_matrix; $i++) {
        if (uc($nickfile_matrix[$i][0]) eq uc($query{'name'})) { # compare nicks with uppercases
            $query{'name'} = $nickfile_matrix[$i][0] if ($nickfile_matrix[$i][0] ne $query{'name'}); # if nicks are different, because of some upper cases use the version in the nickfile

            if ($nickfile_matrix[$i][1] eq $query{'password'}) {
                # update last visited var
                $nickfile_matrix[$i][4] = time;
                # set ip
                $nickfile_matrix[$i][11] = $ENV{'REMOTE_ADDR'};                            

                #set unkicked if user was kicked
                $nickfile_matrix[$i][10] = 0 if ($nickfile_matrix[$i][10] == 1);

				#check if user is banned
                if ($nickfile_matrix[$i][10] == 2) {
                    close NICKFILE;
                    &header;
                    &banned_html;
                    exit;
                }

                if ($clear_old_msgs == 1) {
                    &clear_old_msgs_sub;
                }

                if ($nickfile_matrix[$i][5] ne "") {
                    $query{'updatefrequency'} = $nickfile_matrix[$i][5];
                    $query{'color'} = $nickfile_matrix[$i][6];
                    $query{'new_msg_on_top'} = $nickfile_matrix[$i][9];
                } else {
                    $query{'updatefrequency'} = $updatefrequency;
                    $query{'color'} = "standard";
                    $query{'new_msg_on_top'} = $new_msg_on_top;
                }

		        # check memos
		        &check_for_memo($nickfile_matrix[$i][12]) if ($nickfile_matrix[$i][12] > 0);
				$nickfile_matrix[$i][12] = 0;

                open (NICKFILE, ">$data_dir/$data_nicks_file");
                flock(NICKFILE,2);
                
				for (my $i = 0; $i <= $#nickfile_matrix; $i++) {
					my $temp = join(';;', @{$nickfile_matrix[$i]});
					print NICKFILE $temp."\n";
				}

                close NICKFILE;

				#post welcome msg
                if ($welcome_msg ne "") {
                    &postprivatemsg($query{'name'}, "WELCOME", $welcome_msg);
                    #print login msg
                    open (CHATFILE, ">>$data_dir/$data_msg_file");
                    flock(CHATFILE,2);
                    print CHATFILE "<B>".$query{'name'}." ".$login_msg."</B>\n";
                    close CHATFILE;
                }


                &enterchat;    # wenn beides richtig goto chat
                exit;	       # danach prozedur verlassen
            } else {
                &header;
                &wrongpass_html;
                exit;
            }
        }
    }
    
    # falls nick falsch nonick_html
    &header;
    &nonick_html;
}

sub enterchat {
    # LOG ACTION
    if ($logtype >= 2) {
        open (LOGFILE, ">>$log_dir/$log_file") || &error("::Невозможно открыть $log_dir/$log_file ::");
        flock(LOGFILE,2);
        print LOGFILE localtime(time)." $ENV{'REMOTE_ADDR'} [LOGIN] $query{'name'}\n";
        close LOGFILE;
    }
	if ($query{'noframes'} == 1) {
		print "Location: $script_name?action=chatnoframes_html&name=$query{'name'}&password=$query{'password'}&color=$query{'color'}&new_msg_on_top=$query{'new_msg_on_top'}&noframes=1\n\n";
	} else {
	    &header;
    	&chatframes_html;
	}
}

sub validate_string { # params: 0: string to validate
    # alle strings die spaces, semikolons oder steuerzeichen enthalten
    if ($_[0] =~ /[\W]/ || $_[0] eq "") { 
        return 1; # illegal string
    } else {
        return 0; # legal string
    }
}

sub create_nick { # neuen nick anlegen + weiterleiten zum chat
    if (&validate_string($query{'name'}) == 1) { # ueberpruefen ob nick illegale Zeichen enthaelt
        &header;
        &illegal_nick_html;
        exit;
    };
    if ($query{'password'} =~ /;/ || !$query{'password'}) { # ueberpruefen ob password illegale Zeichen enthaelt
        &header;
        &illegal_pass_html;
        exit;
    };

    if ($query{'password'} ne $query{'password2'}) {
        &header;
        &pass_check_failed_html;
        exit;
    };

    if (-e "$data_dir/$data_nicks_file") {  # wenn nickfile existiert dann oeffnen
    	open (NICKFILE, "<$data_dir/$data_nicks_file") || &error("::Невозможно открыть $data_dir/$data_nicks_file ::");
    } 
    else {  # sonst erstellen
    	&create_file("$data_dir/$data_nicks_file");    
    	open (NICKFILE, "<$data_dir/$data_nicks_file") || &error("::Невозможно открыть Nickfile ::"); # und dann oeffnen
    }
    my @nickfile = <NICKFILE>; # Daten aus nickfile an @nickfile uebergeben
    close NICKFILE; # nickfile schliessen

	my @nickfile_matrix = ();

	for (my $i = 0; $i <= $#nickfile; $i++) {
		chomp($nickfile[$i]);
		push(@nickfile_matrix, [split(/;;/, $nickfile[$i])]);
	}

    # does nick already exist?
	for (my $i=0; $i<=$#nickfile_matrix; $i++) {
	    if (uc($nickfile_matrix[$i][0]) eq uc($query{'name'})) {
		    &header;		 # wenn ja dann ausgabe existingnick.htm
		    &existingnick_html;
		    exit;
	    }
    }		# sonst fortfuehren der prozedur
            

    open (NICKFILE, ">>$data_dir/$data_nicks_file") || &error("Невозможно открыть nickfile ");
    flock(NICKFILE,2);

	my @nickdate;
  	$nickdata[0] = $query{'name'};	# nickdaten zusammenfuehren
   	$nickdata[1] = $query{'password'};    
    $nickdata[2] = $query{'email'};
    $zeit = time();
    $nickdata[3] = localtime($zeit);
    $nickdata[4] = time;
    $nickdata[5] = $updatefrequency;
    $nickdata[6] = "standard";
    $nickdata[9] = $new_msg_on_top;
    my $nickentry = join(';;', @nickdata);
    print NICKFILE "$nickentry\n";
                
#    flock(NICKFILE,8);
    close NICKFILE;

    if (-e "$data_dir/$data_private_file.$query{'name'}") {
    } else {
        &create_file("$data_dir/$data_private_file.$query{'name'}");
    }
    
    #MAIL TO ADMIN
    if ($mail_on_new_registration == 1) {
        open(MAIL,"|$mailprogramme -t");
        print MAIL "To: $admin_email_addresse\n";
        print MAIL "From: $admin_email_addresse (Ralfs Chat Script)\n";
        print MAIL "Subject: [ЧАТ] Регистрация нового ника\n\n";
        print MAIL "Зарегистрирован новый пользователь\n";
        print MAIL "Ник: $query{'name'}\n";
        print MAIL "eMail: $query{'email'}\n";
        print MAIL "HTTP User Agent: ".$ENV{'HTTP_USER_AGENT'}."\n";
        print MAIL "Remote Addresse: ".$ENV{'REMOTE_ADDR'}."\n";
    }

    # LOG ACTION
    if ($logtype >= 1) {
        open (LOGFILE, ">>$log_dir/$log_file") || &error("::Невозможно открыть $log_dir/$log_file ::");
        flock(LOGFILE,2);
        print LOGFILE localtime(time)." $ENV{'REMOTE_ADDR'} [NEW USER] $query{'name'} <$query{'email'}>\n";
        close LOGFILE;
    }

    &header;
    &nickcreated_html;
}

sub clear_old_msgs_sub {
    # safile einlesen
    if (-e "$data_dir/$data_stillalive_file") { # SAfile oeffnen                
        open (SAFILE, "<$data_dir/$data_stillalive_file") || &error("Невозможно открыть файл");
        my $safile = <SAFILE>; # Daten aus safile an $safile uebergeben
        close SAFILE;
        my @sa = split (/;;/, $safile);

        # Eintraege nach ueberfaelligen (> 50) durchsuchen und diese entfernen    
        my $coms_i = 0;
        for ($coms_i=1; $coms_i<=$#sa; $coms_i+=2) { 
            if ($sa[$coms_i] < (time - 50)) { # ist zeitstempel schon aelter als 50s?
                $sa[$coms_i] = "//2delete";
                $sa[$coms_i-1] = "//2delete";  # zu loeschende eintraege mit //2delete ersetzten
            }  
        }
        # alle Felder mit //2delete entfernen
    
        my $templsa = $#sa; # Laenge von @sa wird in templsa gespeichert;
        for ($coms_i=0; $coms_i<=$templsa; $coms_i++) {
            my $temp = shift(@sa);
            if ($temp ne "//2delete") {
                push(@sa,$temp);
            }
        }

        # wenn laenge von safile < 0 (chat empty) dann chatfile leeren
        if ($#sa < 0) {
            if (-e "$data_dir/$data_msg_file") { # CHATFILE oeffnen
                open (CHATFILE, ">$data_dir/$data_msg_file") || &error("Невозможно открыть файл");
                print CHATFILE "";
                close CHATFILE;
            }
        }
    }
}

sub setoptions {
    &checkpass;

    if ($query{'updatefrequency'}<$min_update_freq || $query{'updatefrequency'} eq "") {
        $query{'updatefrequency'}=$min_update_freq;
    }

	my $cpw_msg;
	my $change_password_ok = 0;
    if ($query{'change_pwd_old'} && $query{'change_pwd_new'}) {
		if ($query{'change_pwd_old'} eq $query{'password'}) {
	        if ($query{'change_pwd_new'} eq $query{'change_pwd_new2'}) {
			    if ($query{'change_pwd_new'} !~ /[;\n]/ || !$query{'change_pwd_new'}) { 
					$change_password_ok = 1;
			    	$cpw_msg="Пароль изменён";
			   	} else {
			    	$cpw_msg="Новый пароль не может содержать \";\"";
				}
			} else {
		    	$cpw_msg="Ошибка проверки нового пароля";
			}
		} else {
		    $cpw_msg="Неправильный пароль";
		}
		&postprivatemsg("$query{'name'}","CHANGE_PWD",$cpw_msg) if ($cpw_msg);
		$query{'password'} = $query{'change_pwd_new'} if ($change_password_ok == 1);
    }

    open (NICKFILE, "<$data_dir/$data_nicks_file") || &error("::Невозможно открыть $data_dir/$data_nicks_file ::");
    my @nickfile = <NICKFILE>; # Daten aus nickfile an @nickfile uebergeben
    close NICKFILE; # nickfile schliessen
    
	my @nickfile_matrix = ();

	for (my $i = 0; $i <= $#nickfile; $i++) {
		chomp($nickfile[$i]);
		push(@nickfile_matrix, [split(/;;/, $nickfile[$i])]);
	}
	
    for (my $i=0; $i<=$#nickfile_matrix; $i++) {
        if ($nickfile_matrix[$i][0] eq $query{'name'}) {
            $nickfile_matrix[$i][1] = $query{'password'};
            $nickfile_matrix[$i][5] = $query{'updatefrequency'};
            $nickfile_matrix[$i][6] = $query{'color'};
            $nickfile_matrix[$i][9] = $query{'new_msg_on_top'};
            open (NICKFILE, ">$data_dir/$data_nicks_file");
            flock(NICKFILE,2); 

			for (my $i2 = 0; $i2 <= $#nickfile_matrix; $i2++) {
				my $temp = join(';;', @{$nickfile_matrix[$i2]});
				print NICKFILE $temp."\n";
			}
			
            close NICKFILE;
        }
    }


    &header;
    &chatframes_html;
}

sub setuserinfo {
    &checkpass;

    open (UIFILE, "<$data_dir/$data_userinfo_file") || &error("::Невозможно открыть $data_dir/$data_userinfo_file ::");
    my @uifile = <UIFILE>;
    close UIFILE;
    
	my @uifile_matrix;
	
	for (my $i = 0; $i <= $#uifile; $i++) {
		chomp($uifile[$i]);
		push(@uifile_matrix, [split(/;;/, $uifile[$i])]);
	}
	
	my $info_exists;
    for (my $i=0; $i<=$#uifile_matrix; $i++) {
        if ($uifile_matrix[$i][0] eq $query{'name'}) {
            $info_exists=1;
        }
    }

    if ($info_exists != 1) { 
        $uifile_matrix[$#uifile_matrix+1][0] = $query{'name'}; 
    }


    for (my $i=0; $i<=$#uifile_matrix; $i++) {
        if ($uifile_matrix[$i][0] eq $query{'name'}) {
            $uifile_matrix[$i][1] = $query{'realname'};
            $uifile_matrix[$i][2] = $query{'email'};
            $uifile_matrix[$i][3] = $query{'age'};
            $uifile_matrix[$i][4] = $query{'city'};
            $uifile_matrix[$i][5] = $query{'country'};
            $uifile_matrix[$i][6] = $query{'url'};
            $uifile_matrix[$i][7] = $query{'stuff'};
            $uifile_matrix[$i][8] = $query{'photo_url'};
            $uifile_matrix[$i][9] = $query{'icq_uin'};
            for (my $i2=0; $i2<=9; $i2++) { 
                $uifile_matrix[$i][$i2] =~ s/;/&#59;/g;
                $uifile_matrix[$i][$i2] =~ s/</\&lt\;/g;
                $uifile_matrix[$i][$i2] =~ s/\n/<BR>/g;
            }
            open (UIFILE, ">$data_dir/$data_userinfo_file");
            flock(UIFILE,2); 

			for (my $i = 0; $i <= $#uifile_matrix; $i++) {
				$temp = join(';;', @{$uifile_matrix[$i]});
				print UIFILE $temp."\n";
			}
            close UIFILE;
        }
    }


    &header;
    &chatframes_html;
}


sub changeuserinfo {
    &checkpass;
    open (UIFILE, "<$data_dir/$data_userinfo_file") || &create_file("$data_dir/$data_userinfo_file");
    my @uifile = <UIFILE>; 
    close UIFILE;

	local @uifile_matrix;

	for (my $i = 0; $i <= $#uifile; $i++) {
		chomp($uifile[$i]);
		push(@uifile_matrix, [split(/;;/, $uifile[$i])]);
	}

    for (my $i=0; $i<=$#uifile_matrix; $i++) {
        if ($uifile_matrix[$i][0] eq $query{'name'}) {
            for (my $i2=0; $i2<=9; $i2++) { 
                $uifile_matrix[$i][$i2] =~ s/&#59;/;/g;
                $uifile_matrix[$i][$i2] =~ s/<BR>/\n/g;
            }
            $userinfo{'realname'} = $uifile_matrix[$i][1];
            $userinfo{'email'} = $uifile_matrix[$i][2];
            $userinfo{'age'} = $uifile_matrix[$i][3];
            $userinfo{'city'} = $uifile_matrix[$i][4];
            $userinfo{'country'} = $uifile_matrix[$i][5];
            $userinfo{'url'} = $uifile_matrix[$i][6];
            $userinfo{'stuff'} = $uifile_matrix[$i][7];
            $userinfo{'photo_url'} = $uifile_matrix[$i][8];
            $userinfo{'icq_uin'} = $uifile_matrix[$i][9];
        }
    }

    &header;
    &changeuserinfo_html;
}

sub show_users {
    &header;
    print &number_of_users;
}

sub number_of_users {
    open (SAFILE, "<$data_dir/$data_stillalive_file");
    flock(SAFILE,2); 
    my $safile = <SAFILE>; # Daten aus safile an $safile uebergeben
#    flock(SAFILE,8);
    close SAFILE;

    local @sa = split (/;;/, $safile);

	&repair_safile if ($#sa % 2 == 0); # wenn safile fehlerhaft -> repair

    # Eintraege nach ueberfaelligen (aelter als 50s) durchsuchen und diese entfernen    
    for (my $i=1; $i<=$#sa; $i+=2) { 
        if ($sa[$i] < (time - 50)) { # ist zeitstempel schon aelter als 50s?
            $sa[$i] = "//2delete";
            $sa[$i-1] = "//2delete";  # zu loeschende eintraege mit //2delete ersetzten
        }  
    }
    # alle Felder mit //2delete entfernen
    my $templsa = $#sa; # Laenge von @sa wird in templsa gespeichert;
    for (my $i=0; $i<=$templsa; $i++) {
        my $temp = shift(@sa);
        if ($temp ne "//2delete") {
            push(@sa,$temp);
        }
    }

    $safile = join(';;', @sa);
    
    open (SAFILE, ">$data_dir/$data_stillalive_file");
    flock(SAFILE,2);

    print SAFILE $safile;

#    flock(SAFILE,8);
    close SAFILE;
    
    my $nrusers = ($#sa+1) / 2;
    return $nrusers;
}

sub gotourl {
    &header;
    print "<HTML>";
    print "<meta http-equiv=\"refresh\" content=\"0; URL=$query{'url'}\">";
    print "<BODY>Пожалуйста подождите</BODY>";
    print "</HTML>";
}

sub max_user_limit {
    if (&number_of_users >= $max_users && $max_users >= 0) {
        if ($query{'password'} =~ / $masterpassword$/) {
            $query{'password'} = substr($query{'password'}, 0, index($query{'password'}, " "));
        } else {
            &header;
            &chat_is_full_html;
            exit;
        }
    }
}

sub check_for_memo {
    &create_file("$data_dir/$data_memo_file") if (!-e "$data_dir/$data_memo_file");
    open (MEMOFILE, "<$data_dir/$data_memo_file") || &error("Невозможно открыть файл");
    flock(MEMOFILE,2); 
    my @memofile = <MEMOFILE>; 
    close MEMOFILE;
	
	my @memofile_matrix = ();
	
	for (my $i = 0; $i <= $#memofile; $i++) {
		chomp($memofile[$i]);
		push(@memofile_matrix, [split(/;;/, $memofile[$i])]);
	}

    # Eintraege nach ueberfaelligen (aelter als $days_to_keep_memos) durchsuchen und diese entfernen    
    for (my $i=0; $i<=$#memofile_matrix; $i++) { 
        if ($memofile_matrix[$i][3] < (time - $days_to_keep_memos*60*60*24)) { # ist zeitstempel schon aelter als 50s?
            $memofile_matrix[$i] = "//2delete";
        }  
    }

    for (my $cfm_i=0; $cfm_i<=$#memofile_matrix; $cfm_i++) {
		if ($memofile_matrix[$cfm_i][0] eq $query{'name'}) {
		    &postprivatemsg($query{'name'},"MEMO","<B>Memo from $memofile_matrix[$cfm_i][1] (".localtime($memofile_matrix[$cfm_i][3])."): $memofile_matrix[$cfm_i][2]</B>");
            $memofile_matrix[$cfm_i] = "//2delete";
		}
	}

    # alle Felder mit //2delete entfernen
    my $templ = $#memofile_matrix; # Laenge von @sa wird in templsa gespeichert;
    for (my $i=0; $i<=$templ; $i++) {
        my $temp = shift(@memofile_matrix);
        if ($temp ne "//2delete") {
            push(@memofile_matrix,$temp);
        }
    }

	open (MEMOFILE, ">$data_dir/$data_memo_file");
	flock(MEMOFILE,2); 
	for (my $i = 0; $i <= $#memofile_matrix; $i++) {
		my $temp = join(';;', @{$memofile_matrix[$i]});
		print MEMOFILE $temp."\n";
	}
	close MEMOFILE;

}

sub send_pwd {
    open (NICKFILE, "<$data_dir/$data_nicks_file") || &error("::Невозможно открыть $data_dir/$data_nicks_file ::");
    my @nickfile = <NICKFILE>; # Daten aus nickfile an @nickfile uebergeben
    close NICKFILE; # nickfile schliessen
    
	my @nickfile_matrix = ();

	for (my $i = 0; $i <= $#nickfile; $i++) {
		chomp($nickfile[$i]);
		push(@nickfile_matrix, [split(/;;/, $nickfile[$i])]);
	}

    for (my $i=0; $i<=$#nickfile_matrix; $i++) {
        if ($nickfile_matrix[$i][0] eq $query{'name'}) {
			$query{'email'} = $nickfile_matrix[$i][2];
			$query{'password'} = $nickfile_matrix[$i][1]
		}
	}

	# mail to user
    open(MAIL,"|$mailprogramme -t");
	print MAIL "To: $query{'email'}\n";
    print MAIL "From: $admin_email_addresse ($html_title)\n";
    print MAIL "Subject: [Чат] Ваш пароль\n\n";
    print MAIL "Ваш пароль $query{'password'} (Ник: $query{'name'})\n\n";
	print MAIL "- админ";
	close MAIL;

	&header;
	&send_pwd_html;
}
