<?php
/*
Plugin Name: FeedStats (de)
Plugin URI: http://www.anieto2k.com
Description: Simple sistema de estadisticas de Feeds (<a href="http://bueltge.de">de: bueltge.de</a>)
Author: Andres Nieto Porras
Version: 1.1
Author URI: http://www.anieto2k.com
*/

$fs_user_level = get_option('fs_user_level');
$fs_tr = array (
'Visits' => 'Besuche',
'Day' => 'Tag',
'Today' => 'heute',
'First Day' => 'Erster Tag',
'Stats' => 'Statistik',
'Average' => 'Durchschnitt',
'Max' => 'Maximum',
'Total' => 'Gesamt',
'Max Online' => 'Maximum online',
'Last N Referers' => 'Letzte N Referer',
'Reset Stats' => 'Statistik zur&uuml;cksetzen',
'You are about to delete all data and reset stats. OK to delete, Cancel to stop'
=> 'Du m&ouml;chtest alle Statistikdaten l&ouml;schen. OK zum l&ouml;schen, Cancel f&uuml;r Stop'
);
// How many days do you want to show in the table of visits and hits
$fs_days = get_option('fs_days');
// How many seconds do you want your session to last (this is the appropiate time, so don't change it if you are not sure of what you're doing)
$fs_session_timeout = get_option('fs_session_timeout');
// How many seconds do you want your visits to be considered online (this is the appropiate time, so don't change it if you are not sure of what you're doing)
$fs_visits_online = get_option('fs_visits_online');
// How many referers do you want to be shown
$fs_num_referers = get_option('fs_num_referers');

// How many search terms do you want to be shown
$fs_num_search_terms = get_option('fs_num_search_terms');

// Type the IPs that you don't want to track (like yours). Example: $fs_ifs_not_tracked = array('156.45.689.23','197.469.934.574');
$fs_ifs_not_tracked = array();
// Config End (stop editing)

define('fs_DAY',60*60*24);

// Installation functions
function fs_generateDB() {
	global $wpdb,$table_prefix,$fs_visits_table,$fs_data_table;
	
	$fs_data_table = $table_prefix."fs_data";
	$fs_visits_table = $table_prefix."fs_visits";
	$fs_data_query = "CREATE TABLE ".$fs_data_table." (
					time_install int(11) NOT NULL default '0',
					max_visits mediumint(8) unsigned NOT NULL default '0',
					max_visits_time int(11) NOT NULL default '0',
					max_online mediumint(8) unsigned NOT NULL default '0',
					max_online_time int(11) NOT NULL default '0'
				) TYPE=MyISAM;";
	$fs_visits_query = "CREATE TABLE ".$fs_visits_table." (
					visit_id mediumint(8) unsigned NOT NULL auto_increment,
					ip varchar(20) NOT NULL default '',
					url varchar(255) NOT NULL default '',
					time_begin int(11) NOT NULL default '0',
					time_last int(11) NOT NULL default '0',
					PRIMARY KEY (visit_id)
				) TYPE=MyISAM;";
	include_once (ABSPATH.'/wp-admin/upgrade-functions.php');
	maybe_create_table($fs_data_table,$fs_data_query);
	maybe_create_table($fs_visits_table,$fs_visits_query);
	$time = time();
	
	$count_data = $wpdb->get_var("SELECT count(*) FROM ".$fs_data_table);
	if ($count_data==0)
		$wpdb->query("INSERT INTO ".$fs_data_table." (time_install,max_visits,max_visits_time) VALUES (".$time.",0,".$time.")");
}
//

// Upgrade functions
function fs_versionControl() {
	global $wpdb,$fs_visits_table,$fs_data_table;
	
	// Version 1.6.0 to 1.7.0
	// Added 4 more fields to visits table: referer, platform, browser and version
	$create_dll = "ALTER TABLE ".$fs_visits_table." ADD referer varchar(255) NOT NULL default '' AFTER ip";
	maybe_add_column($fs_visits_table,'referer',$create_dll);
	$create_dll = "ALTER TABLE ".$fs_visits_table." ADD platform varchar(50) NOT NULL default '' AFTER referer";
	maybe_add_column($fs_visits_table,'platform',$create_dll);
	$create_dll = "ALTER TABLE ".$fs_visits_table." ADD browser varchar(50) NOT NULL default '' AFTER platform";
	maybe_add_column($fs_visits_table,'browser',$create_dll);
	$create_dll = "ALTER TABLE ".$fs_visits_table." ADD version varchar(15) NOT NULL default '' AFTER browser";
	maybe_add_column($fs_visits_table,'version',$create_dll);
	// Added 2 more fields to data table: max_online and max_online_time
	$create_dll = "ALTER TABLE ".$fs_data_table." ADD max_online mediumint(8) unsigned NOT NULL default '0' AFTER max_hits_time";
	maybe_add_column($fs_data_table,'max_online',$create_dll);
	$create_dll = "ALTER TABLE ".$fs_data_table." ADD max_online_time int(11) NOT NULL default '0' AFTER max_online";
	maybe_add_column($fs_data_table,'max_online_time',$create_dll);
	
	// Version 1.7.0 to 1.7.1
	// Fixed search engine user agent which should return no version
	$wpdb->query("UPDATE ".$fs_visits_table." SET version='' WHERE browser='Crawler/Search Engine'");
	// Added 1 more field to visits table: search_terms
	$create_dll = "ALTER TABLE ".$fs_visits_table." ADD search_terms varchar(255) NOT NULL default '' AFTER version";
	maybe_add_column($fs_visits_table,'search_terms',$create_dll);
	
	// Version 1.7.4 to 1.8.0
	// Added 1 more field to visits table: url
	$create_dll = "ALTER TABLE ".$fs_visits_table." ADD url varchar(255) NOT NULL default '' AFTER ip";
	maybe_add_column($fs_visits_table,'url',$create_dll);
}
//

// Global set of functions
function fs_tr($s) {
	global $fs_tr;
	$return = ($fs_tr[$s]!='') ? $fs_tr[$s] : $s;
	if (get_bloginfo('charset') == 'UTF-8')
		{
			$return = utf8_encode($return);
		}
	return $return;
}

function fs_resetDB() {
	global $wpdb,$fs_visits_table,$fs_data_table;
	
	$wpdb->get_var("DROP TABLE ".$fs_visits_table.",".$fs_data_table);
	fs_generateDB();
}

function fs_getIP() {
	global $_SERVER;
	
	if (isset($_SERVER['HTTP_CLIENT_IP']))
		return($_SERVER['HTTP_CLIENT_IP']);
	else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		return($_SERVER['HTTP_X_FORWARDED_FOR']);
	else if (isset($_SERVER['REMOTE_ADDR']))
		return($_SERVER['REMOTE_ADDR']);
	else
		return($_SERVER['REMOTE_HOST']);
}


function fs_getMidnight($time) {
	return date('U',mktime(0,0,0,1,date('z',$time)+1,date('y',$time)));
}
//

// Main/System functions
function fs_track($title = '') {
	global $wpdb,$fs_visits_table,$fs_data_table,$fs_days,$fs_session_timeout,$fs_visits_online,$fs_ifs_not_tracked,$_SERVER;

	$time = time();
		$url = $_SERVER['REQUEST_URI'];
		if ($url == get_bloginfo('rdf_url')) $url = "RDF";
		else if ($url == get_bloginfo('rss_url')) $url = "RSS";
		else if ($url == get_bloginfo('rss2_url')) $url = "RSS2";
		else if ($url == get_bloginfo('atom_url')) $url = "ATOM";
		else if ($url == get_bloginfo('comments_rss2_url')) $url = "COMMENT RSS";

	$time_delete = fs_getMidnight($time-(fs_DAY*$fs_days));	
	$wpdb->query("DELETE FROM ".$fs_visits_table." WHERE time_begin < ".$time_delete);
	
	if(in_array(fs_getIP(),$fs_ifs_not_tracked))
		return;
		
	$time_insert_visit = $time - $fs_session_timeout;
	
	if($wpdb->is_admin || strstr($_SERVER['PHP_SELF'],'wp-admin/')) {
		$sessions = $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table." WHERE ip='".fs_getIP()."' AND time_last > ".$time_insert_visit);
		if ($sessions>0) {
			$wpdb->query("UPDATE ".$fs_visits_table." SET time_last=".$time.",url='".$url."' WHERE ip='".fs_getIP()."' AND time_last > ".$time_insert_visit);
		}
		return;
	}
	$ip_time_query = $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table." WHERE ip='".fs_getIP()."' AND time_last > ".$time_insert_visit);
	if ($ip_time_query==0) {

		$wpdb->query("INSERT INTO ".$fs_visits_table." (ip,url,time_begin,time_last) VALUES ('".fs_getIP()."','".$url."',".$time.",".$time.")");
	}
	else {
		$wpdb->query("UPDATE ".$fs_visits_table." SET time_last=".$time.",url='".$url."' WHERE ip='".fs_getIP()."' AND time_last > ".$time_insert_visit);
	}
	
	$time_start = fs_getMidnight($time);
	$time_end = $time_start + fs_DAY;
	
	$count_visits_day = $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table." WHERE time_begin >= ".$time_start." AND time_begin < ".$time_end);
	$max_visits = $wpdb->get_var("SELECT max_visits FROM ".$fs_data_table);
	if ($count_visits_day>=$max_visits)
		$wpdb->query("UPDATE ".$fs_data_table." SET max_visits = ".$count_visits_day.",max_visits_time = ".$time);		

	$time_visits_online = $time - $fs_visits_online;
	$count_online = $wpdb->get_var("SELECT COUNT(*) FROM ".$fs_visits_table." WHERE time_last > ".$time_visits_online);
	$max_online = $wpdb->get_var("SELECT max_online FROM ".$fs_data_table);
	if ($count_online>=$max_online)
		$wpdb->query("UPDATE ".$fs_data_table." SET max_online = ".$count_online.",max_online_time = ".$time);
	return $title;
}

function fs_displayStats() {
	global $wpdb,$fs_visits_table,$fs_data_table,$fs_days,$fs_visits_online,$fs_num_referers,$fs_num_search_terms;

	if ($_GET['fs_action']=='reset')
		fs_resetDB();
		
	$time = time();
	
	$time_begin = fs_getMidnight($wpdb->get_var("SELECT time_install FROM ".$fs_data_table));
	$num_days = ceil(($time-$time_begin)/fs_DAY);
	if ($num_days>$fs_days)
		$num_days = $fs_days + 1;
	
	$visits = array();
	$count_visits_total  = 0;
	
	for ($i=0; $i<$num_days; $i++) {
		$day_time = $time - ($i * fs_DAY);
		$time_start = fs_getMidnight($day_time);
		$time_end = $time_start + fs_DAY;
		$count_visits_day = $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table." WHERE time_begin >= ".$time_start." AND time_begin < ".$time_end);
		$visits[$day_time] = $count_visits_day;
		if ($i!=0 && $time_start!=$time_begin) {
			$count_visits_total += $count_visits_day;
		}
	}
	$total_visits = $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table);
	$average_visits = ($num_days) ? round($total_visits/($num_days)) : '0';

	$max_visits = $wpdb->get_var("SELECT max_visits FROM ".$fs_data_table);
	$max_visits_time = date('d.m.y',$wpdb->get_var("SELECT max_visits_time FROM ".$fs_data_table));
	
	$total_visits = $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table);
	
	$max_online = $wpdb->get_var("SELECT max_online FROM ".$fs_data_table);
	$max_online_time = date('d.m.y H:i',$wpdb->get_var("SELECT max_online_time FROM ".$fs_data_table));

	$referers_query = $wpdb->get_results("SELECT DISTINCT url FROM ".$fs_visits_table." WHERE url NOT LIKE '%".get_settings('home')."%' AND url <> '' ORDER BY url DESC");
	$referers = array();
	if ($referers_query) {
		foreach ($referers_query as $r) {
			$refer['cont'] =  $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table." WHERE url = '".$r->url."';");
			$refer['title'] = $r->url;
			array_push($referers,$refer);
		}
	}

	$time_visits_online = $time - $fs_visits_online;
	$online_query = $wpdb->get_results("SELECT ip,url FROM ".$fs_visits_table." WHERE time_last > ".$time_visits_online);
	$online = array();
	if ($online_query) {
		foreach ($online_query as $visit) {
			$o['ip'] = $visit->ip;
			$o['url'] = $visit->url;
			array_push($online,$o);
		}
	}
	$people_online = count($online);	
	
?>
	
	<div class="wrap">
	<h2>FeedStats</h2>
	<!-- Graphic -->
    
  <table width="100%"  border="0" cellspacing="0" cellpadding="0" >
    <tr> 
      <td width="6%" rowspan="2" valign="top"><table cellpadding="3" cellspacing="3">
        <tr>
          <th scope="col" width="100"><?php echo fs_tr('Day'); ?></th>
          <th scope="col" width="110"><?php echo fs_tr('Visits'); ?></th>
        </tr>
        <?php
	krsort($visits);
	$class = '';
	foreach ($visits as $day=>$num) {
		$class = ($class=='alternate') ? '' : 'alternate';
		if (date('d.m.y',$day)==date('d.m.y',time()))
			$day_s = fs_tr('Today');
		else if (date('d.m.y',$day)==date('d.m.y',$time_begin))
			$day_s = fs_tr('First Day');
		else
			$day_s = date('d.m.y',$day);
?>
        <tr class="<?php echo $class; ?>">
          <td align="center"><strong><?php echo $day_s; ?></strong></td>
          <td align="center"><?php echo $num; ?></td>
        </tr>
        <?php
	}
?>
      </table> 
        <!-- VISITAS -->        <!-- VISITAS -->
      </td>
      <td colspan="3" align="right" valign="top" style="border-bottom:1px #CCC solid; border-left:1px #CCC solid; " height="160px"><table align="center" cellpadding="1" cellspacing="0" style="height: 140px; border-left: 1px solid #CCC; border-bottom: 1px solid #CCC; border-right: 1px solid #CCC;">
          <tr>
            <td colspan="<?=count($visits);?>" align="center">
              <?=fs_tr('Visits');?>
            </td>
          </tr>
          <?php ksort($visits); foreach ($visits as $day=>$num) { ?>
    <td align="center" style="padding-left: 5px; font-size: 10px; color:#A3A3A3;">
        <?=$num?>
      </td>
        <? } ?>
        <td align="center" style="padding-left: 5px; font-size: 10px; color: #CCC">
          <?=$average_visits?>
        </td>
        <td align="center" style="padding-left: 5px; font-size: 10px; color:#FF0000">
          <?=$max_visits?>
        </td>
    </tr>
    <tr>
      <?php foreach ($visits as $day=>$num) { ?>
      <td valign="bottom"><div title="<?php echo date('j M',$day).": ".$num; ?>" style="width: 16px; height: <?php echo round(100*($num/$max_visits)); ?>px; background-color: #A3A3A3; border-bottom: 1px solid #A3A3A3;">&nbsp;</div></td>
      <?php } ?>
      <td valign="bottom" style="padding-left: 5px;"><div title="<?php echo fs_tr('Average').": ".$average_visits; ?>" style="width: 16px; height: <?php echo round(100*($average_visits/$max_visits)); ?>px; background-color: #CCC; border-bottom: 1px solid #CCC;">&nbsp;</div></td>
      <td valign="bottom" style="padding-left: 5px;"><div title="<?php echo fs_tr('Max').": ".$max_visits; ?>" style="width: 16px; height: <?php echo round(100*($max_visits/$max_visits)); ?>px; background-color:#FFCC66; border-bottom: 1px solid #CCC;">&nbsp;</div></td>
    </tr>
    <tr>
      <?php foreach ($visits as $day=>$num) { ?>
      <td align="center" style="font-size: 10px;"><?php echo date('j',$day); ?></td>
      <?php } ?>
      <td align="center" style="padding-left: 5px; font-size: 10px;">&Oslash;</td>
      <td align="center" style="padding-left: 5px; font-size: 10px; color:#FF0000">Max</td>
    </tr>
                  </table></td>
    </tr>
    <tr> 
      <td width="45%" align="right" valign="top" style="border-right:1px #CCC solid;"><table align="center" cellpadding="3" cellspacing="3" style="margin-top: 30px;">
          <tr> 
            <th width="278" colspan="2" scope="col"><?php echo str_replace('N',$fs_num_referers,fs_tr('Last N Referers')); ?></th>
          </tr>
          <?php
		  
	if ($referers) {
	arsort($referers);
		$class = '';
		foreach ($referers as $r) {
			$class = ($class=='alternate') ? '' : 'alternate';
?>
          <tr class="<?php echo $class; ?>"> 
            <td><? echo $r['cont'];?></td>
            <td><?php echo (strlen($r['title'])>80) ? substr_replace($r['title'],"...",80) : $r['title']; ?></td>
          </tr>
          <?php
		}
	}
?>
        </table></td>
      <td width="35%" align="right" valign="top" style="border-right:1px #CCC solid; "><table cellpadding="3" cellspacing="3">
          <tr> 
            <th scope="col" width="100"><?php echo fs_tr('Stats'); ?></th>
            <th scope="col" width="110"><?php echo fs_tr('Visits'); ?></th>
          </tr>
          <tr class="alternate"> 
            <td align="center"><strong><?php echo fs_tr('Average'); ?></strong></td>
            <td align="center"><?php echo ($average_visits!=0) ? $average_visits : '-' ?></td>
          </tr>
          <tr class="alternate"> 
            <td align="center"><strong><?php echo fs_tr('Max'); ?></strong></td>
            <td align="center"><?php echo $max_visits ?><br />
              (<?php echo $max_visits_time ?>)</td>
          </tr>
          <tr class="alternate"> 
            <td align="center"><strong><?php echo fs_tr('Total'); ?></strong><br />
              (<?php echo str_replace('N',$num_days,fs_tr('Letzen N Tage')); ?>)</td>
            <td align="center"><?php echo $total_visits ?></td>
          </tr>
          <tr class="alternate"> 
            <td align="center"><strong><?php echo fs_tr('Max Online'); ?></strong></td>
            <td align="center" colspan="2"><?php echo $max_online ?><br />
              (<?php echo $max_online_time ?>)</td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
    <!-- End Graphic -->
    <!-- Data -->
	<!-- End Data -->
<p align="center" style="margin-top: 50px;"><a href="index.php?page=<?php echo basename(__FILE__); ?>&fs_action=reset" onclick="return confirm('<?php echo fs_tr('You are about to delete all data and reset stats. OK to delete, Cancel to stop'); ?>');">&gt;&gt; <?php echo fs_tr('Reset Stats'); ?> &lt;&lt;</a></p>
		
	</div>

<?php
}
function fs_addAdminMenu() {
	global $fs_user_level;
		add_option("fs_days","30");	
		add_option("fs_user_level","1");	
		add_option("fs_session_timeout","300");	
		add_option("fs_visits_online","300");	
	add_submenu_page('index.php','FeedStats','FeedStats',get_option('fs_user_level'),__FILE__,'fs_displayStats');
	add_options_page('Configura tus estadisticas', 'FeedStats', 9, 'admin-feedstats.php');
}

function fs_getfeeds()
{
	global $wpdb,$fs_visits_table,$fs_data_table,$fs_days;
		
	$total_visits = $wpdb->get_var("SELECT count(*) FROM ".$fs_visits_table);

	$time = time();
	$time_begin = fs_getMidnight($wpdb->get_var("SELECT time_install FROM ".$fs_data_table));
	$num_days = ceil(($time-$time_begin)/fs_DAY);
	if ($num_days>$fs_days)
		$num_days = $fs_days + 1;
		
	$average_visits = ($num_days) ? round($total_visits/($num_days)) : '0';
	$max_visits = $wpdb->get_var("SELECT max_visits FROM ".$fs_data_table);
	$max_visits_time = date('d.m.y',$wpdb->get_var("SELECT max_visits_time FROM ".$fs_data_table));
	?>
<div id="feeds_readers">
	<h2>Leser der Feeds</h2>
	<ul><li>Gesamt: <?=$total_visits?></li>
		<li>Maximum: <?=$max_visits?> [<?=$max_visits_time?>]</li>
		<li>Durchschnitt: <?=$average_visits?></li>
		</ul></div>
	<?
}


// Program flow
fs_generateDB();
fs_versionControl();
add_action('the_title_rss','fs_track');
add_action('admin_menu','fs_addAdminMenu');
//
?>
