<?php
/* MySQL-Counter from murb.com
 * Version 2.0
 *
 * Website: http://www.murb.com
 * Further information and help: http://www.murb.com/forum/viewtopic.php?t=2485
 *
 * This script is freeware.
 */

#### MySQL-Database access data ####

$db_sqlc_host "localhost"// database host (IP); standard "localhost"
$db_sqlc_name "database"// database name
$db_sqlc_user "username"// username
$db_sqlc_pwd "password"// password

#### Tables ####

$db_sqlc_counter "sqlc_counter"// table for counter data (today counts, yesterday counts,...)
$db_sqlc_iplog "sqlc_iplog"// table for IPs and timestamps

#### Settings ####

$sqlc_splitter "&nbsp;&nbsp;|&nbsp;&nbsp;"// chars to split counter data
$sqlc_ip_time 900// time (in seconds) of IP matters as unique user
$sqlc_online_time 300// time (in seconds) of IP matters as unique user beeing online
$sqlc_log_amount 500// amount of loggs (ip, timestamp) saved in database; should be at least: 3 * [expected visitors within [ip_time] seconds]
$sqlc_show_output true// determines to show output or not

/* layout of counter output; modify style-tag of div to fit output;
 * do NOT remove or change the placeholder "[sqlc_counter_output]"!
 */
$sqlc_output_layout "<div style=\"padding: 2px\">[sqlc_counter_output]</div>";

/* output of counter data; modify output labels;
 * do NOT remove or change placeholders [~] (except for [sqlc_spliter])!
 */
$sqlc_output  "Online: [sqlc_online][sqlc_splitter]";
$sqlc_output .= "Onlinerekord: [sqlc_online_record][sqlc_splitter]";
$sqlc_output .= "Heute: [sqlc_today][sqlc_splitter]";
$sqlc_output .= "Gestern: [sqlc_yesterday][sqlc_splitter]";
$sqlc_output .= "Tagesrekord: [sqlc_day_record][sqlc_splitter]";
$sqlc_output .= "Gesamt: [sqlc_total][sqlc_splitter]";
$sqlc_output .= "Seitenaufrufe: [sqlc_hits]";

##################

/* Do not modify the code below if you don't know what you're doing! :-) */

function connectToDatabase($db_host$db_user$db_pwd) {
  return @
mysql_connect($db_host$db_user$db_pwd);
}

function 
selectDatabase($database_sqlc$db_sqlc_name) {
  return @
mysql_select_db($db_sqlc_name$database_sqlc);
}

function 
GetIP() {
  if (
getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
    
$ip getenv("HTTP_CLIENT_IP");
  else if (
getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
    
$ip getenv("HTTP_X_FORWARDED_FOR");
  else if (
getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
    
$ip getenv("REMOTE_ADDR");
  else if (isset(
$_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
    
$ip $_SERVER['REMOTE_ADDR'];
  else
    
$ip "unknown";
  return(
$ip);
}

$database_sqlc connectToDatabase($db_sqlc_host$db_sqlc_user$db_sqlc_pwd);
if (!
$database_sqlc) {
  echo 
"Error: Cannot connect to database!<br>";
}
if (!
selectDatabase($database_sqlc$db_sqlc_name))    {
  echo 
"Error: Cannot access required table!<br>";
}

// installation process
if (isset($_GET['action']) && $_GET['action'] == "install") {
  
$install_error false;
  
$table_check_1 = @mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'");
  if (@
mysql_num_rows($table_check_1) != 0) {
    
$install_error true;
    echo 
"The table &quot;".$db_sqlc_counter."&quot; already exists.<br>";
  }
  
$table_check_2 = @mysql_query("SELECT * FROM ".$db_sqlc_iplog);
  if (@
mysql_num_rows($table_check_2) != 0) {
    
$install_error true;
    echo 
"The table &quot;".$db_sqlc_iplog."&quot; already exists.";
  }
  if (
$install_error) {
    exit; 
// shit happens
  
}
  else {
    
mysql_query("CREATE TABLE ".$db_sqlc_counter." (
                 id int(10) NOT NULL default '0',
                 online_record int(20) NOT NULL default '0',
                 today int(20) NOT NULL default '0',
                 yesterday int(20) NOT NULL default '0',
                 day_record int(20) NOT NULL default '0',
                 total int(20) NOT NULL default '0',
                 pages_total int(20) NOT NULL default '0',
                 date int(20) NOT NULL default '0',
                 PRIMARY KEY (id)) TYPE=MyISAM"
$database_sqlc) or die (mysql_error() . ": " mysql_error() . "\n");
  
    
mysql_query("INSERT INTO ".$db_sqlc_counter." SET id = '1'"$database_sqlc);
  
    
mysql_query("CREATE TABLE ".$db_sqlc_iplog." (
                 id int(10) NOT NULL auto_increment,
                 ip varchar(254) NOT NULL default '',
                 timestamp int(20) NOT NULL default '0',
                 PRIMARY KEY (id)) TYPE=MyISAM"
$database_sqlc) or die (mysql_error() . ": " mysql_error() . "\n");
  
    echo 
"Installation successful!";
    exit;
  }
}

// check the correctness of tables
$table_check_1 = @mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'"$database_sqlc);
$table_check_2 = @mysql_query("SELECT * FROM ".$db_sqlc_iplog$database_sqlc);
if (@
mysql_num_rows($table_check_1) == 0) {
  @
mysql_query("INSERT INTO ".$db_sqlc_counter." SET id = '1'"$database_sqlc);
}
if (@
mysql_num_rows($table_check_2) == 0) {
  @
mysql_query("INSERT INTO ".$db_sqlc_iplog." SET ip = '127.0.0.0'"$database_sqlc);
}
$table_check_3 = @mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'"$database_sqlc);
$table_check_4 = @mysql_query("SELECT * FROM ".$db_sqlc_iplog$database_sqlc);
if (@
mysql_num_rows($table_check_3) == || @mysql_num_rows($table_check_4) == 0) {
  echo 
"Error: Tables are not installed correctly.<br>";
  exit;
}

// counter process starts here
// counter script has to be included; otherwise print log data
if (substr(strrchr($_SERVER['SCRIPT_NAME'],"/"),1) != substr(strrchr(str_replace('\\''/'__FILE__),"/"),1)) {
  
$current_ip GetIP();
  
$fetch_current mysql_fetch_array(mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'"$database_sqlc));
  
  
// in case of "day-change"
  
if (date("d",time()) != $fetch_current['date']) {
    
mysql_query("UPDATE ".$db_sqlc_counter." SET date = '".date("d",time())."', yesterday = '".$fetch_current['today']."', today = '0' WHERE id = '1'"$database_sqlc);
    
$fetch_current mysql_fetch_array(mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'"$database_sqlc));
  }
  
  
$user_still_logged mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM ".$db_sqlc_iplog." WHERE ((".time()." - timestamp) <= ".$sqlc_ip_time.") AND ip = '".mysql_real_escape_string($current_ip)."'"$database_sqlc));
  
/* possibilities in case of count == 0:
   *  - IP is not logged
   *  - more than [ip_time] seconds passed
   *  => user counts as new visitor
   */
  
if ($user_still_logged['count'] == 0) {
  
    
mysql_query("DELETE FROM ".$db_sqlc_iplog." WHERE ip = '".mysql_real_escape_string($current_ip)."'"$database_sqlc);
    
mysql_query("INSERT INTO ".$db_sqlc_iplog." SET ip = '".mysql_real_escape_string($current_ip)."', timestamp = '".time()."'"$database_sqlc);
  
    if ((
$fetch_current['today'] + 1) > $fetch_current['day_record']) {
      
mysql_query("UPDATE ".$db_sqlc_counter." SET day_record = '".($fetch_current['today'] + 1)."' WHERE id = '1'"$database_sqlc);
    }
    
mysql_query("UPDATE ".$db_sqlc_counter." SET today = today+1, total = total+1 WHERE id = '1'"$database_sqlc);
  }
  else {
    
// update time of user
    
mysql_query("UPDATE ".$db_sqlc_iplog." SET timestamp = '".time()."' WHERE ip = '".mysql_real_escape_string($current_ip)."'"$database_sqlc);
  }
  
  
mysql_query("UPDATE ".$db_sqlc_counter." SET pages_total = pages_total+1 WHERE id = '1'"$database_sqlc);
  
  
$fetch_online_users mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM ".$db_sqlc_iplog." WHERE ((".time()." - timestamp) < ".$sqlc_online_time.")"$database_sqlc));
  
  if (
$fetch_online_users['count'] > $fetch_current['online_record']) {
    
mysql_query("UPDATE ".$db_sqlc_counter." SET online_record = '".$fetch_online_users['count']."' WHERE id = '1'"$database_sqlc);
  }
  
  
// delete [10% of [log_amount]] logs if total amount of logs exceeds [log_amount]
  // notice: 10% deletions at once to avoid frequent deletions
  
$check_log_amount mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM ".$db_sqlc_iplog$database_sqlc));
  if (
$check_log_amount['count'] > $sqlc_log_amount) {
     
mysql_query("DELETE FROM ".$db_sqlc_iplog." ORDER BY id ASC LIMIT ".ceil($sqlc_log_amount 0.1), $database_sqlc);
  }
  
  
// print output?
  
if ($sqlc_show_output) {
    
$fetch_counter_data mysql_fetch_array(mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'"$database_sqlc));
  
    
$sqlc_output str_replace("[sqlc_online]"$fetch_online_users['count'], $sqlc_output);
    
$sqlc_output str_replace("[sqlc_online_record]"$fetch_counter_data['online_record'], $sqlc_output);
    
$sqlc_output str_replace("[sqlc_today]"$fetch_counter_data['today'], $sqlc_output);
    
$sqlc_output str_replace("[sqlc_yesterday]"$fetch_counter_data['yesterday'], $sqlc_output);
    
$sqlc_output str_replace("[sqlc_day_record]"$fetch_counter_data['day_record'], $sqlc_output);
    
$sqlc_output str_replace("[sqlc_total]"$fetch_counter_data['total'], $sqlc_output);
    
$sqlc_output str_replace("[sqlc_hits]"$fetch_counter_data['pages_total'], $sqlc_output);
    
$sqlc_output str_replace("[sqlc_splitter]"$sqlc_splitter$sqlc_output);
  
    echo 
str_replace("[sqlc_counter_output]"$sqlc_output$sqlc_output_layout);
  }
}

// show counter data and logs
else {
  
$sqlc_log_splitter "&nbsp;&nbsp;|&nbsp;&nbsp;";
  
$fetch_counter_data mysql_fetch_array(mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'"$database_sqlc));
  
$fetch_online_users mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM ".$db_sqlc_iplog." WHERE ((".time()." - timestamp) < ".$sqlc_online_time.")"$database_sqlc));

  
// in case of "day-change"
  
if (date("d",time()) != $fetch_counter_data['date']) {
    
mysql_query("UPDATE ".$db_sqlc_counter." SET date = '".date("d",time())."', yesterday = '".$fetch_counter_data['today']."', today = '0' WHERE id = '1'"$database_sqlc);
    
$fetch_counter_data mysql_fetch_array(mysql_query("SELECT * FROM ".$db_sqlc_counter." WHERE id = '1'"$database_sqlc));
  }

  
$sqlc_output str_replace("[sqlc_online]"$fetch_online_users['count'], $sqlc_output);
  
$sqlc_output str_replace("[sqlc_online_record]"$fetch_counter_data['online_record'], $sqlc_output);
  
$sqlc_output str_replace("[sqlc_today]"$fetch_counter_data['today'], $sqlc_output);
  
$sqlc_output str_replace("[sqlc_yesterday]"$fetch_counter_data['yesterday'], $sqlc_output);
  
$sqlc_output str_replace("[sqlc_day_record]"$fetch_counter_data['day_record'], $sqlc_output);
  
$sqlc_output str_replace("[sqlc_total]"$fetch_counter_data['total'], $sqlc_output);
  
$sqlc_output str_replace("[sqlc_hits]"$fetch_counter_data['pages_total'], $sqlc_output);
  
$sqlc_output str_replace("[sqlc_splitter]"$sqlc_log_splitter$sqlc_output);

  echo 
"<center>\n";
  echo 
"<span style=\"font-family: Arial; font-size: 14px; font-weight: bold\">Counter Log-Informationen</span>\n";
  echo 
"<div style=\"padding: 5px; width: 640px; border: 1px solid #000000; margin-top: 30px; font-family: Arial; font-size: 11px\">".$sqlc_output."</div>\n";

  
$check_log_amount mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM ".$db_sqlc_iplog." WHERE ip != '127.0.0.0'"$database_sqlc));
  echo 
"<table width=\"650\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin-top: 20px; border: 1px solid #000000; font-family: Arial; font-size: 11px\">\n
  <tr>\n
    <td colspan=\"3\" align=\"center\" valign=\"top\" style=\"padding: 5px\">Die letzten "
.$check_log_amount['count']." gespeicherten IP-Adressen</td>\n
  </tr>\n"
;
  if (
$check_log_amount['count'] > 0) {
    echo 
"  <tr bgcolor=\"#E5E5E5\">\n
    <td width=\"25%\" align=\"left\" valign=\"top\" style=\"padding: 5px; font-weight: bold\">IP</td>\n
    <td width=\"25%\" align=\"left\" valign=\"top\" style=\"padding: 5px; font-weight: bold\">Datum</td>\n
    <td width=\"50%\" align=\"left\" valign=\"top\" style=\"padding: 5px; font-weight: bold\">Hostname</td>\n
  </tr>\n"
;
    
$get_ip_logs mysql_query("SELECT * FROM ".$db_sqlc_iplog." WHERE ip != '127.0.0.0' ORDER BY timestamp DESC"$database_sqlc);
    
$i 0;
    while (
$g_ip_logs mysql_fetch_array($get_ip_logs)) {
      
$color_flag "";
      if ((
$i 2) != 0) {
        
$color_flag " bgcolor=\"#F5F5F5\"";
      }
      
$i++;
      echo 
"  <tr".$color_flag.">\n
    <td width=\"25%\" align=\"left\" valign=\"top\" style=\"padding: 5px\">"
.$g_ip_logs['ip']."</td>\n
    <td width=\"25%\" align=\"left\" valign=\"top\" style=\"padding: 5px\">"
.date("d.m.Y, H:i:s"$g_ip_logs['timestamp'])."</td>\n
    <td width=\"50%\" align=\"left\" valign=\"top\" style=\"padding: 5px\"><a href=\"http://whois.domaintools.com/"
.$g_ip_logs['ip']."\" target=\"_blank\" style=\"color: #000000\">".gethostbyaddr($g_ip_logs['ip'])."</a></td>\n
  </tr>\n"
;
    }
  }
  else {
    echo 
"  <tr>\n
    <td colspan=\"3\" align=\"center\" valign=\"top\" style=\"padding: 10px\"><i>Keine IP-Adressen vorhanden.</i></td>
  </tr>\n"
;
  }
  echo 
"</table>";
  echo 
"</center>";
}

mysql_close($database_sqlc);
?>