#!/usr/bin/perl
#

use 5.006;
use CGI;
use DBI;
use lib qw(/mnt/sda/tmm/handlers/genc);
use TClubMD5;

my $n_recent = 25;

my $server = "127.0.0.1";
my $user = $primary_user;
my $passwd = $primary_passwd;
my $dbase = $primary_dbase;
my $port = $primary_port;


my $query = new CGI;

print "Content-Type: text/html; charset=UTF-8\n\n";

my $who = $query->param('who');
my $token = $query->param('token');
my $ru_en = $query->param('l');
my $language = $query->param('lang');
my $db = $query->param('db');
my $curr_sp = $query->param('cat');
my $sport_and = "(sport = '$curr_sp') and";
$sport_and = "true and" if ($curr_sp eq '0');

my $session = TClubMD5::md5_hex($who.$salt);
my $time_zone = "Europe/Moscow";
my $hourshift = '0 hours';

die("check_alert.pl: token is $token, session is $session!\n") if ($token ne $session);
die("psssooff!\n") if (in_list($who,$pssoff_guys_string));


($dbase,$server,$port,$user,$passwd,$hourshift) = TClubMD5::get_connect_req($ru_en);

$dbase = $db if ($db);

my $inviter = '';
my $when = '';
my $what = '';
my $myoid = 0;
my $r_user = $who;
my $n_counted = 0;
my $n_forum = 10;

my $at = 'Ð²';
$at = 'at' if ($language eq "english");
$at = 'Ã ' if ($language eq "french");

my $old_dbase = $dbase;
$dbase = 'clone' if ($dbase eq 'three' || $dbase eq 'rlx');#hack

$dbconn=DBI->connect("dbi:Pg:dbname=$dbase;port=$port;host=$server",$user, $passwd);

$comm = "select members.a_nkname, (mails.when_invited+'".$hourshift."')::time, mails.what_told, mails.oid from mails, members where mails.proj_code = '$who' and members.proj_code=mails.inviter and mails.status = 'f' and (current_timestamp - mails.when_invited) <= '2 min'";
&getTable;

if ($ntuples == 1) {
$inviter = ${${$listresult}[0]}[0];

$when = sprintf("%s",${${$listresult}[0]}[1]);
$when =~ /^(\d+):(\d+)(.*)/;
$when = $1.":".$2;

$what = ${${$listresult}[0]}[2];
$what =~ s/^\s+|\s+$//g;
$what= koitoutf8(wintokoi($what)) unless (is_utf($what));

$myoid = ${${$listresult}[0]}[3];

if (length($what)) {
print "invite:with_text".$what."\n".$inviter." ".$at." ".$when;
} else {
print "invite:".$inviter." ".$at." ".$when;
}

my $cmd = "update mails set status='t' where oid = $myoid";
my $result=$dbconn->prepare($cmd);
$result->execute;
} else {

$comm = "select count(distinct name) from wtagonliners where name != 'visitatore'";
&getTable;
my $n_in_kafe = ${${$listresult}[0]}[0];

if ($old_dbase ne $dbase) {
$dbconn->disconnect;
$dbconn=DBI->connect("dbi:Pg:dbname=$old_dbase;port=$port;host=$server",$user, $passwd);
}

my $n_found = &count_new_forum_msgs;

($n_new_comments, $n_new_matches) = &count_new_comments(0);

	($n_new_d_comments, $n_new_d_matches) = &count_new_comments(1);
	$n_new_matches += $n_new_d_matches;$n_new_comments += $n_new_d_comments;


my $n_new_lenta = &count_new_lenta;
($n_curr_active_cha,$n_curr_hashsum) = &count_cha_hashsum;
my $curr_cpu = &check_cpu;

#print STDERR "Here ac_cha is $n_curr_active_cha, curr_hash is $n_curr_hashsum!\n";

print $n_in_kafe."&".$n_found."&".$n_new_matches."&".$n_new_comments."&".$n_new_lenta."&".$n_curr_active_cha."&".$curr_cpu."&".$n_curr_hashsum;

};

$dbconn->disconnect;
$query->delete_all;
exit;

sub getTable {

	$result=$dbconn->prepare($comm);
    	$result->execute;
	&dBaseError($result, $comm."  (".$result->rows()." rows found)") if ($result->rows() ==
	-2);
	
	$listresult = $result->fetchall_arrayref;
	$ntuples = $result->rows();

};

sub dBaseError {

    my ($check, $message) = @_;
    print "<H4><FONT COLOR=BLACK><P>$message<BR>Error: ".$check->errstr."</FONT></H4>";
    die("Action failed on command:$message  Error_was:$DBI::errstr");
};

sub count_new_forum_msgs {

my $msk_ind; $msk_ind = ($ru_en eq 'ru') ? "msk_ind asc," : '';
$comm = "select oid from forum where $sport_and reply_to_num='reply_to_num' order by $msk_ind vremya_z desc limit $n_recent";
&getTable;
#print STDERR $comm."\n";
my $n_topics = $ntuples;

$n_topics = $n_forum if ($n_topics > $n_forum);

	for (my $i = 0; $i < $n_topics; $i++) {
		&check_if_there_is_new(${${$listresult}[$i]}[0]);

	}

return $n_counted;
}

sub check_if_there_is_new {

my $moid = shift;
my $search = "select is_replied, who_read, z_destination, author from forum where oid = '$moid'";
my $listResult=$dbconn->prepare($search);

$listResult->execute; 
&dBaseError($listResult, $search."  (".$listResult->rows()." rows found)") 
    if($listResult->rows() == -2);

my $listResult_data=$listResult->fetchall_arrayref;
my $is_replied = ${${$listResult_data}[0]}[0];
my $wr_string =  ${${$listResult_data}[0]}[1];
my $wr_auth =  ${${$listResult_data}[0]}[3];
my $zdest = ${${$listResult_data}[0]}[2];

my @privat = split(',',$zdest);

return if ($r_user ne $wr_auth && !in_array($r_user,@privat) && $zdest ne '' && $zdest ne 'z_destination');

$n_counted += ruser_is_not_in_wr_string($wr_string);

 if ($is_replied eq '0') {
	return;
 } else {
	$search = "select oid from forum where reply_to_num = '$moid'";
	$listResult=$dbconn->prepare($search);
	$listResult->execute; 
	&dBaseError($listResult, $search."  (".$listResult->rows()." rows found)") 
    		if($listResult->rows() == -2);
	$listResult_data1{$moid}=$listResult->fetchall_arrayref;
	$ntuples1{$moid}=$listResult->rows;

	for (my $j = 0; $j < $ntuples1{$moid}; $j++) {
		&check_if_there_is_new(${${$listResult_data1{$moid}}[$j]}[0]);

	}
 }

}

sub ruser_is_not_in_wr_string {
my $str = shift;

my @list = split(',',$str);
	foreach my $line (@list) {
		return 0 if ($r_user eq $line);
	}
return 1;
}

sub count_new_comments {

my $par = shift;

my $table = "matches"; $table = "doubles" if ($par);

my $n_counted_comments = 0;
my $n_counted_matches = 0;

if ($use_server && ($ru_en eq 'ru_BRL' || $db eq 'three')) {
$dbconn = DBI->connect("dbi:Pg:dbname='clone';port=$port;host=$server",$user, $passwd);
$dbconn->{LongReadLen} = 16384;
}

     my $and = "true";
     $and = $sport_and." ".$and;
     
     $and .= " and (a.e_masterst ~ '$opz' or a.e_masterst ~ '$opf' or a.e_masterst ~ '$tpz' or a.e_masterst ~ '$tpf' or a.e_masterst ~ '$hpz' or
     b.e_masterst ~ '$opz' or b.e_masterst ~ '$opf' or b.e_masterst ~ '$tpz' or b.e_masterst ~ '$tpf' or b.e_masterst ~ '$hpz') and m.participant1=a.proj_code and m.participant2=b.proj_code"
	if ($db eq 'three' && !$par);

$comm = "select oid, comments from $table where $sport_and match_date is not null and score is not null and score != '' order by match_date desc, tournir_id desc, oid desc limit $n_recent";
	
$comm = "select m.oid, m.comments from $table m, members a, members b where $and and m.match_date is not null 
and m.score is not null and m.score != '' 
order by m.match_date desc, m.tournir_id desc, m.oid desc limit $n_recent" if ($db eq 'three' && !$par);

#select m.oid, m.comments from matches m, members a, members b where (a.e_masterst = '1.0' or a.e_masterst = '1.5' or a.e_masterst = '2.0' or a.e_masterst = '2.5' or a.e_masterst = '3.0' or b.e_masterst = '1.0' or b.e_masterst = '1.5' or b.e_masterst = '2.0' or b.e_masterst = '2.5' or b.e_masterst = '3.0') and m.participant1=a.proj_code and m.participant2=b.proj_code and m.match_date is not null and m.score is not null and m.score !~ 'w/o' and m.score != '' order by m.match_date desc, m.tournir_id desc, m.oid desc limit 25;
#select m.tournir_id, m.round, m.score, m.participant1, m.participant2, m.winner, m.points_winner, m.points_loser, m.match_date, m.court_type, m.court_location, m.comments, m.oid, a.oid, b.oid from matches m, members a, members b where true and (a.e_masterst = '1.0' or a.e_masterst = '1.5' or a.e_masterst = '2.0' or a.e_masterst = '2.5' or a.e_masterst = '3.0' or b.e_masterst = '1.0' or b.e_masterst = '1.5' or b.e_masterst = '2.0' or b.e_masterst = '2.5' or b.e_masterst = '3.0')  and score is not null and score !~ 'w/o' and score != ''  and m.participant1=a.proj_code and m.participant2=b.proj_code order by m.match_date desc, m.tournir_id desc, m.oid desc limit 25 offset 0

#print STDERR "Here comm is $comm !\n";
&getTable;

if ($use_server && ($ru_en eq 'ru_BRL')) {
$dbconn = DBI->connect("dbi:Pg:dbname=$dbase;port=$port;host=$server",$user, $passwd);
$dbconn->{LongReadLen} = 16384;
}

for (my $i = 0; $i < $ntuples; $i++) {

		$n_counted_comments += &check_if_there_is_new_comments(${${$listresult}[$i]}[0]);
		$n_counted_matches += 1 unless (in_list($r_user,${${$listresult}[$i]}[1])); 
}

return ($n_counted_comments,$n_counted_matches);

}

sub check_if_there_is_new_comments {

my $moid = shift;

my $n_counted_comments = 0;

my $comm = "select who_read from comments where match_oid = '$moid'";
my $result=$dbconn->prepare($comm);
$result->execute;
&dBaseError($result, $comm."  (".$result->rows()." rows found)") if ($result->rows() == -2);
my $listresult = $result->fetchall_arrayref;
my $ntuples = $result->rows();
for (my $j = 0; $j < $ntuples; $j++) {
	$n_counted_comments++ unless(in_list($r_user,${${$listresult}[$j]}[0]));
}
return $n_counted_comments;
}

sub in_list {
my $guy = shift;
my $str = shift;

return 1 if ($str eq $guy || $str =~ /^$guy\#/ || $str =~ /\#$guy\#/ || $str =~ /\#$guy$/);
return 0;
}

sub count_new_lenta {

$comm = "select who_read from lenta order by p_vremya_z desc limit $n_recent";
&getTable;

my $n_topics = $ntuples;

$n_counted_lenta = 0;
	for (my $i = 0; $i < $n_topics; $i++) {
		$n_counted_lenta++ unless(in_list($r_user,${${$listresult}[$i]}[0]));

	}

return $n_counted_lenta;
}

#unused --ash
sub count_active_challenges {
     
my $_and = ''; my $o = $curr_sp.'_newb';
$_and .= " (members.e_masterst ~ '$opz' or members. e_masterst ~ '$opf' or members.e_masterst ~ '$tpz' or members.e_masterst ~ '$tpf' or members.e_masterst ~ '$hpz' or members.e_masterst ~ '$hpf' or members.e_masterst ~ '$o') and "	
if ($db eq 'three');

my $sel = "select count(challenges.id) from challenges, members where $_and $sport_and members.proj_code=challenges.owner and date_and_time > current_timestamp+'$hourshift'";
#print STDERR "Here sel is $sel!\n";
my $res = $dbconn->prepare($sel);
$res->execute;
&dBaseError($res, $sel."  (".$res->rows()." rows found)") if ($res->rows() == -2);

my $r = $res->fetchall_arrayref;

my $ret = (${${$r}[0]}[0] > 0) ? ${${$r}[0]}[0] : 0;

return $ret ;

}

sub count_cha_hashsum {
     
my $_and = ''; my $o = $curr_sp.'_newb';
$_and .= " (members.e_masterst ~ '$opz' or members. e_masterst ~ '$opf' or members.e_masterst ~ '$tpz' or members.e_masterst ~ '$tpf' or members.e_masterst ~ '$hpz' or members.e_masterst ~ '$hpf' or members.e_masterst ~ '$o') and "	
if ($db eq 'three');

my $sel = "select count(*), sum(hex_to_int(substr(md5(concat(partner,status::text,date_and_time::text)),0,3))) from challenges, members where $_and $sport_and members.proj_code=challenges.owner and date_and_time > current_timestamp+'$hourshift'";
#print STDERR "Here sel is $sel!\n";

my $res = $dbconn->prepare($sel);
$res->execute;
&dBaseError($res, $sel."  (".$res->rows()." rows found)") if ($res->rows() == -2);

my $r = $res->fetchall_arrayref;

my $ret = (${${$r}[0]}[0] > 0) ? ${${$r}[0]}[0] : 0;
my $ret1 = length(${${$r}[0]}[1]) ? ${${$r}[0]}[1] : 0;

return ($ret,$ret1) ;

}
sub wintokoi { 
my $pvdcoderwin=shift; 
$pvdcoderwin =~ tr/\xC0\xC1\xC2\xC3\xC4\xC5\xA8\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xB8\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF/\xE1\xE2\xF7\xE7\xE4\xE5\xB3\xF6\xFA\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF2\xF3\xF4\xF5\xE6\xE8\xE3\xFE\xFB\xFD\xFF\xF9\xF8\xFC\xE0\xF1\xC1\xC2\xD7\xC7\xC4\xC5\xA3\xD6\xDA\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD2\xD3\xD4\xD5\xC6\xC8\xC3\xDE\xDB\xDD\xDF\xD9\xD8\xDC\xC0\xD1/; 
return $pvdcoderwin; 
}

sub koitoutf8 {
my $pvdcoderwin=shift;
$pvdcoderwin=~ s/³/E/g;
$pvdcoderwin=~ s/£/e/g;
$pvdcoderwin=~ s/Ñ/Ñ�/g;
$pvdcoderwin=~ s/Ð/Ð¿/g;

$pvdcoderwin=~ s/á/Ð�/g;
$pvdcoderwin=~ s/â/Ð‘/g;
$pvdcoderwin=~ s/÷/Ð’/g;
$pvdcoderwin=~ s/ç/Ð“/g;
$pvdcoderwin=~ s/ä/Ð”/g;
$pvdcoderwin=~ s/å/Ð•/g;
$pvdcoderwin=~ s/ö/Ð–/g;
$pvdcoderwin=~ s/ú/Ð—/g;
$pvdcoderwin=~ s/é/Ð˜/g;
$pvdcoderwin=~ s/ê/Ð™/g;
$pvdcoderwin=~ s/ë/Ðš/g;
$pvdcoderwin=~ s/ì/Ð›/g;
$pvdcoderwin=~ s/í/Ðœ/g;
$pvdcoderwin=~ s/î/Ð�/g;
$pvdcoderwin=~ s/ï/Ðž/g;
$pvdcoderwin=~ s/ð/ÐŸ/g;
$pvdcoderwin=~ s/ò/Ð /g;
$pvdcoderwin=~ s/ó/Ð¡/g;
$pvdcoderwin=~ s/ô/Ð¢/g;
$pvdcoderwin=~ s/õ/Ð£/g;
$pvdcoderwin=~ s/æ/Ð¤/g;
$pvdcoderwin=~ s/è/Ð¥/g;
$pvdcoderwin=~ s/ã/Ð¦/g;
$pvdcoderwin=~ s/þ/Ð§/g;
$pvdcoderwin=~ s/û/Ð¨/g;
$pvdcoderwin=~ s/ý/Ð©/g;
$pvdcoderwin=~ s/ø/Ð¬/g;
$pvdcoderwin=~ s/ù/Ð«/g;
$pvdcoderwin=~ s/ÿ/Ðª/g;
$pvdcoderwin=~ s/ü/Ð­/g;
$pvdcoderwin=~ s/à/Ð®/g;
$pvdcoderwin=~ s/ñ/Ð¯/g;

$pvdcoderwin=~ s/Á/Ð°/g;
$pvdcoderwin=~ s/Â/Ð±/g;
$pvdcoderwin=~ s/×/Ð²/g;
$pvdcoderwin=~ s/Ç/Ð³/g;
$pvdcoderwin=~ s/Ä/Ð´/g;
$pvdcoderwin=~ s/Å/Ðµ/g;
$pvdcoderwin=~ s/Ö/Ð¶/g;
$pvdcoderwin=~ s/Ú/Ð·/g;
$pvdcoderwin=~ s/É/Ð¸/g;
$pvdcoderwin=~ s/Ê/Ð¹/g;
$pvdcoderwin=~ s/Ë/Ðº/g;
$pvdcoderwin=~ s/Ì/Ð»/g;
$pvdcoderwin=~ s/Í/Ð¼/g;
$pvdcoderwin=~ s/Î/Ð½/g;
$pvdcoderwin=~ s/Ï/Ð¾/g;
$pvdcoderwin=~ s/Ò/Ñ€/g;
$pvdcoderwin=~ s/Ó/Ñ�/g;
$pvdcoderwin=~ s/Ô/Ñ‚/g;
$pvdcoderwin=~ s/Õ/Ñƒ/g;
$pvdcoderwin=~ s/Æ/Ñ„/g;
$pvdcoderwin=~ s/È/Ñ…/g;
$pvdcoderwin=~ s/Ã/Ñ†/g;
$pvdcoderwin=~ s/Þ/Ñ‡/g;
$pvdcoderwin=~ s/Û/Ñˆ/g;
$pvdcoderwin=~ s/Ý/Ñ‰/g;
$pvdcoderwin=~ s/Ø/ÑŒ/g;
$pvdcoderwin=~ s/Ù/Ñ‹/g;
$pvdcoderwin=~ s/ß/ÑŠ/g;
$pvdcoderwin=~ s/Ü/Ñ�/g;
$pvdcoderwin=~ s/À/ÑŽ/g;
$pvdcoderwin=~ s/£/Ñ‘/g;
$pvdcoderwin=~ s/³/Ð�/g;

return $pvdcoderwin;
}

sub utf2koi {
my $pvdcoderwin=shift;

$pvdcoderwin=~ s/Ð�/á/g;
$pvdcoderwin=~ s/Ð‘/â/g;
$pvdcoderwin=~ s/Ð’/÷/g;
$pvdcoderwin=~ s/Ð“/ç/g;
$pvdcoderwin=~ s/Ð”/ä/g;
$pvdcoderwin=~ s/Ð•/å/g;
$pvdcoderwin=~ s/Ð–/ö/g;
$pvdcoderwin=~ s/Ð—/ú/g;
$pvdcoderwin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 s/Ñ�/Ó/g;
$pvdcoderwin=~ s/Ñ‚/Ô/g;
$pvdcoderwin=~ s/Ñƒ/Õ/g;
$pvdcoderwin=~ s/Ñ„/Æ/g;
$pvdcoderwin=~ s/Ñ…/È/g;
$pvdcoderwin=~ s/Ñ†/Ã/g;
$pvdcoderwin=~ s/Ñ‡/Þ/g;
$pvdcoderwin=~ s/Ñˆ/Û/g;
$pvdcoderwin=~ s/Ñ‰/Ý/g;
$pvdcoderwin=~ s/ÑŒ/Ø/g;
$pvdcoderwin=~ s/Ñ‹/Ù/g;
$pvdcoderwin=~ s/ÑŠ/ß/g;
$pvdcoderwin=~ s/Ñ�/Ü/g;
$pvdcoderwin=~ s/ÑŽ/À/g;
$pvdcoderwin=~ s/Ñ‘/£/g;
$pvdcoderwin=~ s/Ð�/³/g;

$pvdcoderwin=~ s/Ñ�/Ñ/g;
$pvdcoderwin=~ s/Ð¿/Ð/g;


return $pvdcoderwin;
}

sub is_utf {

my $var = shift;
my $buf = $var;
$buf = utf2koi($buf);

return 1 if ( (length($var) > length($buf) + 2) && (length($buf) > 0));
return 0;
}

sub check_cpu {

my $file = "/opt/nvme2/MY/tmm/average_log";
my $cmd = "tail $file -n 1";
open (IN, '-|', $cmd)
	or return 0;
my $av = 0;
while (!eof(IN)) {
	my $q = readline (*IN);
	$q =~ /AVERAGE CPU:\s*(\d+\.\d)/;
	$av = $1;
}
close (IN);
return $av;
};

sub in_array {
my $guy = shift;
my @l  = @_;
foreach my $line (@l) {
return 1 if ($guy eq $line);
}
return 0;
}
