#!/usr/bin/perl

use strict;
use DBI;
use FCGI;
use Time::Local;
use Cache::MemoryCache;

$| = 1;	

my $dsn = 'dbi:mysql:compteurgratuit-org:mysql.regiecpm.com:3306';

# set the user and password
my $user = 'compteurgratuit';
my $pass = "";

# id='+id+'&t='+type+'&d='+o_q['d']+'&n='+o_q['n']+'&s='+o_q['s']+'&ac='+ac+'&inc='+inc+'

# colonne pour les types de comptage
my $rh_type_col = {};
$rh_type_col->{1} = 'PAGES_VUES';
$rh_type_col->{2} = 'VISITES';
$rh_type_col->{3} = 'VISITEURS';

# Lien pour les distrib
my $rh_lng_url = {};
$rh_lng_url->{'FR'} = 'href="http://www.compteur-gratuit.org"';
#$rh_lng_url->{'EN'} = 'href="http://www.compteur-gratuit.org"';
$rh_lng_url->{'EN'} = 'href="http://www.my-free-counter.com"';

# Variables

my $headers = "Content-type: text/html\n\n";
my $base_path = "http://www.compteur-gratuit.org/digit/";

# now connect and get a database handle
my $dbh = DBI->connect($dsn, $user, $pass)
 or die "Cannot connect to the DB: $DBI::errstr\n";

my $rh_db = {};
$rh_db->{'BASE'}->{'compteur'} = '`compteurgratuit-org`';
$rh_db->{'TABLE'}->{'sites'} = $rh_db->{'BASE'}->{'compteur'}.'.sites';


# objet de temps
my $rh_time = {};

# ID MAX
my $id_max = 0;
my $sql = 'SELECT MAX(id)-20 FROM '.$rh_db->{'TABLE'}->{'sites'}.' ';
my $rqt = $dbh->prepare($sql);
$rqt->execute;
if (my @row = $rqt->fetchrow_array())
{
	$id_max = $row[0];
}

# Debut de la boucle FCGI
while (FCGI::accept() >= 0)
#if (1)
{
	print $headers;
    	#check_time($rh_time);
    	# Verification de la connection
    	$dbh = DBI->connect($dsn, $user, $pass) if (!$dbh->ping);

	#$ENV{'QUERY_STRING'} = 'id=2&t=3&d=21&n=4&s=0&inc=1'; 

	# Traitement de la query string --------------------------------------#
	my $rh_valeurs = &traite_query($ENV{'QUERY_STRING'});

	# recuperation du type de compteur
	my $type = 0 + $rh_valeurs->{'t'};
	$type = 1 if (!defined $rh_type_col->{$type});

	# id du site
	my $id = 0 + $rh_valeurs->{'id'};

	# selection de la valeur
	my $value = 0;
	my $sql = 'SELECT '.$rh_type_col->{$type}.' FROM '.$rh_db->{'TABLE'}->{'sites'}.' WHERE id="'.$id.'"';
	my $rqt = $dbh->prepare($sql);
	$rqt->execute;
	if (my @row = $rqt->fetchrow_array())
	{
	    $value = $row[0];
        }
	# incrementer la valeur
	my $inc = 0 + $rh_valeurs->{'inc'};
	# verrou pour le type 1 d incrementation
	my $ac = 0 + $rh_valeurs->{'ac'};
	$inc = 0 if ($ac == 0);
	$inc = 1 if ($type == 1);
	++$value if ($inc == 1); # increment de la valeur
	
	# nb a afficher
	# decalage
	my $start = 0 + $rh_valeurs->{'s'};
	# nb dec
	my $nb_dec = 0 + $rh_valeurs->{'n'};
	$nb_dec = 4 if ($nb_dec <= 0 || $nb_dec > 9);
	my $nbfilled = sprintf("%0".$nb_dec."d", $value + $start);

	# selection de la langue pour le lien
	my $lng = 'EN';
	$lng = 'FR' if ($ENV{'HTTP_ACCEPT_LANGUAGE'} =~ /fr/i);

	# chemin des images
	my $digit = 0 + $rh_valeurs->{'d'};
	$digit = 1 if ($digit < 1 || $digit > 50);
	my $path = $base_path.$digit.'/';
	# === ecriture du compteur
	print 'document.write(\'<a '.$rh_lng_url->{$lng}.' target="_blank">\');';
	while ($nbfilled =~ /^(.)(.*)$/)
	{
		my $i = $1;
		$nbfilled = $2;
		my $img	= '<img src=\''.$path.$i.'.gif\' border=0>';
		print 'document.write("'.$img.'");';
	}
	print 'document.write("</a>");';
	# === fin d ecriture du compteur

	# === ecriture pub
	#if ($id < $id_max)
	if (0)
	{
		print 'wintext_id=214587;
		wintext_url=escape(document.location);
		wintext_js=\'http://wintext.weborama.fr/fast/w-in-text.fcgi?idsite=\';
		wintext_js+=wintext_id+\'&url=\'+wintext_url;
		document.write(\'<scri\'+\'pt src="\'+wintext_js+\'"></scri\'+\'pt>\');';
# <script type="text/javascript" src="http://fr.clickintext.net/?v=3.0&a=1706&s[c]=0000FF&s[co]=0000FF&t[cit]=1&t[top]=1"></script>
	}

	# mise a jour de la valeur
	if ($inc == 1)
	{
		my $sql = 'UPDATE '.$rh_db->{'TABLE'}->{'sites'}.' SET '.$rh_type_col->{$type}.'="'.$value.'" WHERE id="'.$id.'"';	
		$dbh->do($sql);
	}
	

} # Fin de la boucle FCGI

exit; 

# Fonctions

# traite la query string par division sur les & puis =
sub traite_query($)
{
        my $myquery = shift;
        my @arg = split(/&/, $myquery);
        my ($nom, $valeur);
        my %h_query;

        foreach (@arg)
    	{
        	($nom, $valeur) = split(/=/, $_);
        	# on decode la valeur
        	$valeur =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
        	$h_query{$nom} = $valeur;
    	}
    return \%h_query;
}

sub check_time($)
{
        my ($rh_time) = @_;

        my $now = time();
        my ($sec,$min,$heure,$mjour,$mois,$annee,$sjour,$ajour,$isdst) = gmtime($now);

        $rh_time->{'yyyymmdd_hh'} = sprintf("%04d%02d%02d_%02d", $annee+1900, $mois+1, $mjour, $heure);
        $rh_time->{'now'} = $now;
        $rh_time->{'minute'} = $min;

}


1;
