#!/usr/bin/speedy
use CGI qw(:standard);
use Image::Magick;
use DBI;
use Time::HiRes  qw(gettimeofday tv_interval);
use Data::Dumper;


$SERVER = "veda.lead2se.com"; 

$DB = "DBI:mysql:hcdownload:$SERVER";
$USER = "hcd";
$PASS = "pringles+";

### Get info from the query.


$commands = new CGI;
$data{'URL'}=$commands->param('URL');

### Strip any but the legal characters for domain names to prevent sql injection. 
#The only valid characters for a domain name are letters, numbers, hyphen, underscore and tilde.

$data{'URL'} =~ s/[^A-Za-z0-9\-._~%@\:\/]//g;
$temp = $data{'URL'};
$ENV{'HTTP_REFERER'} =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
$ip = $ENV{'REMOTE_ADDR'};

$good_id = goodID($temp);

if($good_id){
	$dbh = DBI->connect($DB,$USER,$PASS) or die "Unable to contact database!";

	$query = "SELECT SQL_NO_CACHE * FROM counters WHERE URL = '" . $data{'URL'} . "' LIMIT 1;";
	$sth = $dbh->prepare($query);
	$sth->execute() or die "query $query failed\n";
	(@fields) = $sth->fetchrow_array();
	($URL, $email, $count, $style, $inc, @others) = @fields;
	if ($URL && $data{'URL'}){ # good url
		if ($inc ne "visits"){
			incCounter($URL);
			$count++;
		} else {
			$result = isUnique($URL,$ip);
			if($result == 1){
				incCounter($URL);
				$count++;
			}
		}
		genCounterImage($count, $style);
		updateRef($URL,$ENV{'HTTP_REFERER'});
	} else { 
		$temp =~ s/([^A-Za-z0-9\_.])/sprintf("%%%02X", ord($1))/seg;
		$query = "SELECT SQL_NO_CACHE * FROM counters WHERE URL = '" . $temp . "' LIMIT 1;";
		$sth = $dbh->prepare($query);
		$sth->execute() or die "query $query failed\n";
		(@fields) = $sth->fetchrow_array();
		($URL, $email, $count, $style, $inc, @others) = @fields;
		if ($URL && $data{'URL'}){ # good url
			if ($inc ne "visits"){
				incCounter($URL);
				$count++;
			} else {
				$result = isUnique($URL,$ip);
				if($result == 1){
					incCounter($URL);
					$count++;
				} 
			}
			genCounterImage($count, $style);
			updateRef($URL,$ENV{'HTTP_REFERER'});
		} else {
			print "Content-type: text/html\r\n\r\n";
	 	}
	}

	$sth->finish;
	$dbh->disconnect;
} else {
   #gen image
	  $image_new=Image::Magick->new;
	  #$image_new->Read("/srv/hcdownload/html/images/gray-1.png");
	  $image_new->Read("/home/hitcount/public_html/images/gray-1.png");
	  $image_new = $image_new->Append(stack=>false);
	#compile the images
	  $image_out=Image::Magick->new;
	  $image_out->Set(size=>$image_new->Get('width')."x".($image_new->Get('height')));
	  $image_out->Read("NULL:black");
	  $image_out->Composite(image => $image_new, compose => 'over');
	#print compiled image
	  print "Content-type: image/png\r\n\r\n";
	  binmode STDOUT;
	  my $blob = $image_out->ImageToBlob(magick => 'png');
          print $blob;

}

sub goodID(){
	($counter_id) = @_;
	if($counter_id eq '65224-6341'){
		$isGood = 0;
	} elsif ($counter_id eq 'www.trgokkoy1.org'){
		$isGood = 0;
	} else {
		$isGood = 1;
	}
	
	return $isGood;
}
sub isUnique(){
  ($URL, $IP) = @_;
  $query = "select SQL_NO_CACHE * from hitlog where ip='" . $IP . "'AND hitdate=curdate()AND url='" . $URL . "';";
  my $sth = $dbh->prepare($query);
  $sth->execute() or die "query $query failed\n"; 
  my (@fields) = $sth->fetchrow_array;
  ($uid, @others) = @fields;

  if($uid > 0){
    $unique=0;
  } else {
    $unique=1;
    $query = "insert into hitlog (ip, url, hitdate) values ('" . $IP . "' , '". $URL . "', curdate());";
    my $sth = $dbh->prepare($query);
    $sth->execute() or die "query $query failed\n";
  }
  $sth->finish;
  return($unique);
}


sub updateRef(){
   ($URL, $REF) = @_;
   if ($REF) {
    $query = "update counters set ref = '" . $REF . "' where URL = '" . $URL . "'";
    my $sth = $dbh->prepare($query);
    $sth->execute() or die "query $query failed\n";
    $sth->finish;
   }
}

sub incCounter(){
   ($URL) = @_;
   $query = "update counters set count = count + 1, time = curdate()  where URL = '" . $URL . "'";
   my $sth = $dbh->prepare($query);
   $sth->execute() or die "query $query failed\n";
   $sth->finish;
}

sub genCounterImage(){
	($count, $numImage, @other) = @_;
	#make Sure that there are 6 digits.
	$pre = "";
	if($count < 10){$pre .= "0";}
	if($count < 100){$pre .= "0";}
	if($count < 1000){$pre .= "0";}
	if($count < 10000){$pre .= "0";}
	if($count < 100000){$pre .= "0";}
	$count = $pre.$count;
	#gen image count;
		$num_image=Image::Magick->new;
		(@hld)=split("\|",$count);
		foreach $_ (@hld){
			#$num_image->Read("/srv/hcdownload/html/images/".$numImage."-".$_.".png");# 
			$num_image->Read("/home/hitcount/public_html/images/".$numImage."-".$_.".png");# 
		}
		$num_image = $num_image->Append(stack=>false);
	#compile the images
		$image_out=Image::Magick->new;
		$image_out->Set(size=>$num_image->Get('width')."x".($num_image->Get('height')));
		$image_out->Read("NULL:black");
		$image_out->Composite(image => $num_image, compose => 'over');
	#print compiled image
		print "Content-type: image/png\r\n\r\n";
		binmode STDOUT;
		my $blob = $image_out->ImageToBlob(magick => 'png');
                print $blob;
}
