<?php
###### Counter ######
include("counter_conf.php.inc");

if($enable_log==TRUE){
  if(file_exists("log.txt")){
    $fd=fopen("log.txt","r");
    $line=fgets($fd,4097);
    fclose($fd);
    if((trim($line)+86400)<time()){
      $fd=fopen("log.txt","w");
      flock($fd,2);
      fputs($fd,time()."\n");
      flock($fd,3);
      fclose($fd);
    }
  }else{
    $fd=fopen("log.txt","w");
    flock($fd,2);
    fputs($fd,time()."\n");
    flock($fd,3);
    fclose($fd);
  }
  $fd=fopen("log.txt","r");
  while(!feof($fd)){
    $line=fgets($fd,4097);
    if(trim($line)==$_SERVER['REMOTE_ADDR']){
      $not_auth=1;
      break;
    }
  }
  fclose($fd);
  if($not_auth!=1){
    $auth=1;
    $fd=fopen("log.txt","a");
    flock($fd,2);
    fputs($fd,$_SERVER['REMOTE_ADDR'] + "\n");
    flock($fd,3);
    fclose($fd);
  }
}

if(file_exists("counts.txt")){     
  $fd=fopen("counts.txt","r");
  $visits=trim(fgets($fd,4097));
  fclose($fd);
  if($auth==1 || !$enable_log){ 
    $visits=$visits+1;
    $fd = fopen("counts.txt", "w");
    flock($fd,2);
    fputs($fd,$visits);
    flock($fd,3);
    fclose($fd);
  }
}else{
  $visits=1;
  if($auth==1 || !$enable_log){ 
    $fd=fopen("counts.txt","w");
    flock($fd,2); 
    fputs($fd,$visits); 
    flock($fd,3);
    fclose($fd); 
  }
}

if(file_exists("1.png") && file_exists("2.png") && file_exists("3.png") && file_exists("4.png") &&
file_exists("5.png") && file_exists("6.png") && file_exists("7.png") && file_exists("8.png") && file_exists("9.png")
&& file_exists("0.png")){
  header("Content-type:image/png");
  $size=getimagesize("1.png");
  $tmp_img=@imagecreatetruecolor( (strlen($visits)*$size[0]) , $size[1]);        
  if(!$tmp_img) $tmp_img=ImageCreate((strlen($visits)*$size[0]),$size[1]);
  for($i=0;$i<strlen($visits);$i++){
    $cc=substr($visits,$i,1);
    $img=ImageCreateFromPNG("$cc.png");
    ImageCopy($tmp_img,$img,$i*$size[0]+1,0,0,0,$size[0],$size[1]);
    ImageDestroy($img);
  }
  ImagePNG($tmp_img);
}else{
  header("Content-type:image/png");
  $im=@ImageCreate(6+(strlen($visits)*7),15);
  $background_color=ImageColorAllocate($im, 255, 255, 255);
  $text_color=ImageColorAllocate($im, 233, 14, 91);
  ImageString($im, 3, 3, 1, $visits, $text_color);
  ImagePNG($im);
}
?>
