<?php
/*
 Plugin Name: Counterize
 Plugin URI: http://www.gabsoftware.com/products/scripts/counterize/
 Description: Complete counter and statistics plugin for Wordpress with no external libs. See Readme for more details.
 Version: 3.0.33
 Author: Gabriel Hautclocq
 Author URI: http://www.gabsoftware.com/
 License: ISC
*/

//error_reporting( E_ALL );

// security check
if( !defined( 'WP_PLUGIN_DIR' ) )
{
	die( 'There is nothing to see here!' );
}

/* constants */
define( 'COUNTERIZE_TD', 'counterize' );

/* global variables */
$counterize_plugin_dir = WP_PLUGIN_DIR . '/' . plugin_basename( dirname( __FILE__ ) );
if( counterize_is_ssl() )
{
	$counterize_plugin_url = str_replace( 'http://', 'https://', WP_PLUGIN_URL ) . '/' . plugin_basename( dirname( __FILE__ ) );
}
else
{
	$counterize_plugin_url = WP_PLUGIN_URL . '/' . plugin_basename( dirname( __FILE__ ) );
}
$counterize_dashboard_capability = 'manage_options';

$counterize_MajorVersion	= 3;
$counterize_MinorVersion	= 0;
$counterize_Revision		= 33;

require_once( "{$counterize_plugin_dir}/counterize_browsniff.php" );
require_once( "{$counterize_plugin_dir}/counterize_iptocountry.php" );
require_once( "{$counterize_plugin_dir}/counterize_feed.php" );
require_once( "{$counterize_plugin_dir}/counterize_widget.php" );
require_once( "{$counterize_plugin_dir}/counterize_deprecated.php" );

// Counterize Tables
function counterize_agentsTable()
{
	global $wpdb;
	return $wpdb->prefix . "Counterize_UserAgents";
}

function counterize_logTable()
{
	global $wpdb;
	return $wpdb->prefix . "Counterize";
}

function counterize_pageTable()
{
	global $wpdb;
	return $wpdb->prefix . "Counterize_Pages";
}

function counterize_refererTable()
{
	global $wpdb;
	return $wpdb->prefix . "Counterize_Referers";
}

function counterize_keywordTable()
{
	global $wpdb;
	return $wpdb->prefix . "Counterize_Keywords";
}

function counterize_countryTable()
{
	global $wpdb;
	return $wpdb->prefix . "Counterize_Countries";
}

// Returns the value of the specified option
function counterize_get_option( $name )
{
	$options = get_option( 'counterize_options' );
	if( isset( $options[$name] ) )
	{
		return $options[$name];
	}
	else
	{
		return FALSE;
	}
}

// Sets the value of the specified option
function counterize_set_option( $name, $value )
{
	$options = get_option( 'counterize_options' );
	$options[$name] = $value;

	return update_option( 'counterize_options', $options );
}

function counterize_get_version( $what = 'all' )
{
	$version =  get_option( 'counterize_version' );
	if( $version === FALSE )
	{
		//The option was not found. We are certainly installing Counterize for the first time.
		// We return a default version.
		//$version = "{$counterize_MajorVersion}.{$counterize_MinorVersion}.{$counterize_Revision}";
		//update_option( $version );
		$version = "1.0.0";
	}

	switch( $what )
	{
		case 'all':
			return $version;
			break;
		case 'major':
			$version_array = explode( '.', $version );
			return $version_array[0];
			break;
		case 'minor':
			$version_array = explode( '.', $version );
			return $version_array[1];
			break;
		case 'revision':
			$version_array = explode( '.', $version );
			return $version_array[2];
			break;
		default:
			return $version;
	}
}

//return true if the connection uses SSL
function counterize_is_ssl()
{
	if( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] != 'off' )
	{
		return true;
	}
	elseif( $_SERVER['SERVER_PORT'] == 443 )
	{
		return true;
	}
	else
	{
		return false;
	}
}

// seed with microseconds
function counterize_make_seed()
{
  list( $usec, $sec ) = explode( ' ', microtime() );
  return (float) $sec + ( (float) $usec * 100000 );
}

function counterize_get_random_number( $min, $max )
{
	mt_srand( counterize_make_seed() );
	return mt_rand( $min, $max );
}

// Returns how many entries there are in the DB.
// if $only_this_month is set to true, return the number of hits since the beginning of the current month
// else if $since > 0, return the number of hits since $since seconds
function counterize_getamount( $only_this_month = false, $since = 0 )
{
	global $wpdb;
	$since = intval( $since );
	$sql = 'SELECT COUNT( 1 ) '
		. ' FROM `' . counterize_logTable() . '` ';
	if( $only_this_month )
	{
		$sql .= $wpdb->prepare( ' WHERE `timestamp` >= %s ', date( "Y-m-01" ) );
	}
	elseif( $since > 0 )
	{
		$sincedate = date( 'Y-m-d', time() - $since );
		$sql .= $wpdb->prepare( ' WHERE `timestamp` >= %s ', $sincedate );
	}
	return $wpdb->get_var( $sql );
}

// Returns how many key-words there are in the DB.
function counterize_getkeywordamount()
{
	global $wpdb;
	$sql = "SELECT SUM( `count` ) "
		. " FROM `" . counterize_keywordTable() . "`"
		. " WHERE `keywordID` <> 1";
	return $wpdb->get_var( $sql );
}

// Return how many unique entries there are in the DB. After $interval seconds, a new entry with the same haship will be counted as new.
// Example: Get the unique visitors, with same haship counted as new after one hour:
// SELECT COUNT( DISTINCT haship, 3600 * ROUND( UNIX_TIMESTAMP( timestamp ) / 3600 ) ) AS NB
function counterize_getuniqueamount( $since = 0, $interval = 0 )
{
	global $wpdb;
	$interval = intval( $interval );
	$since = intval( $since );
	if( $interval == 0 )
	{
		$sql = 'SELECT COUNT( DISTINCT `haship` ) ';
	}
	else
	{
		$sql = $wpdb->prepare( 'SELECT COUNT( DISTINCT `haship`, %d * ROUND( UNIX_TIMESTAMP( `timestamp` ) / %d ) ) ', $interval, $interval );
	}
	$sql .= ' FROM `' . counterize_logTable() . '` ';
	if( $since > 0 )
	{
		$sincedate = date( 'Y-m-d', time() - $since );
		$sql .= $wpdb->prepare( 'WHERE `timestamp` >= %s ', $sincedate );
	}
	return $wpdb->get_var( $sql );
}


// Return how many unique entries there are in the DB.
/*
function counterize_getuniqueamount()
{
	global $wpdb;
	$sql = "SELECT COUNT( DISTINCT `haship` ) "
		. " FROM `" . counterize_logTable() . "`";
	return $wpdb->get_var( $sql );
}
*/

// Return how many countries there are in the DB.
function counterize_getcountriesamount()
{
	global $wpdb;
	$sql = "SELECT COUNT( DISTINCT `countryID` ) "
		. " FROM `" . counterize_logTable() . "`";
	return $wpdb->get_var( $sql );
}

// Return how many pages have been visited.
function counterize_getpagesamount( $since = 0 )
{
	global $wpdb;
	$since = intval( $since );
	$sql = 'SELECT COUNT( 1 ) '
		. ' FROM `' . counterize_logTable() . '` L, `' . counterize_pageTable() . '` P '
		. ' WHERE L.`pageID` = P.`pageID` '
		. ' AND P.`postID` > 0 ';
	if( $since > 0 )
	{
		$sincedate = date( 'Y-m-d', time() - $since );
		$sql .= $wpdb->prepare( 'AND `timestamp` >= %s ', $sincedate );
	}
	return $wpdb->get_var( $sql );
}

// Returns amount of entries in the DB matching the visiting IP-address.
function counterize_getfromcurrentip()
{
	global $wpdb;
	$sql = "SELECT COUNT( 1 ) "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `IP` = '" . $_SERVER['REMOTE_ADDR'] . "'";
	return $wpdb->get_var( $sql );
}

// Returns amount of hits today.
function counterize_gethitstoday()
{
	global $wpdb;
	$today = date( 'Y-m-d' );
	$sql = "SELECT COUNT( 1 ) "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `timestamp` >= '{$today}'";
	return $wpdb->get_var( $sql );
}

// Returns amount of hits during the last 7 days.
function counterize_getlatest7days()
{
	global $wpdb;
	$sevendaysago = date( 'Y-m-d', time() - 604800 ); //604800 = 86400 * 7
	$sql = "SELECT COUNT( 1 ) "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `timestamp` >= '{$sevendaysago}'";
	return $wpdb->get_var( $sql );
}

// From Curtis(http://www.graymattersonline.net/)
// Returns amount of unique IP's in the last 7 days
function counterize_getuniquelatest7days()
{
	global $wpdb;
	$sevendaysago = date( 'Y-m-d', time() - 604800 ); //604800 = 86400 * 7
	$sql = "SELECT COUNT( DISTINCT `haship` ) "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `timestamp` >= '{$sevendaysago}'";
	return $wpdb->get_var( $sql );
}

// Returns the number of currently online users
// A user is considered online if its visit is less than 5 minutes old
function counterize_get_online_users()
{
	global $wpdb;
	$timestamp = gmdate( 'Y-m-d H:i:s', time() + ( get_option( 'gmt_offset' ) * 3600 ) ); //3600 = 60 * 60
	$sql = "SELECT COUNT( DISTINCT `haship` ) "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `timestamp` > DATE_SUB( '{$timestamp}', INTERVAL 5 MINUTE )";
	return $wpdb->get_var( $sql );
}

// Returns amount of unique referer-URl's
function counterize_getuniquereferers()
{
	global $wpdb;
	$sql = "SELECT COUNT( DISTINCT `refererID` ) "
		. " FROM `" . counterize_logTable() . "`";
	return $wpdb->get_var( $sql );
}

// Returns amount of unique browser-strings in DB.
function counterize_getuniquebrowsers()
{
	global $wpdb;
	$sql = "SELECT COUNT( 1 ) "
		. " FROM `". counterize_agentsTable() . "`";
	return $wpdb->get_var( $sql );
}

// Returns amount on current article
function counterize_getHitsOnCurrentArticle()
{
	global $wpdb;
	if( $_SERVER['REQUEST_URI'] )
	{
		$requesturl = $wpdb->prepare( $_SERVER['REQUEST_URI'] );
		$sql = "SELECT `count` "
			. " FROM `" . counterize_pageTable() . "`"
			. " WHERE `url` = '{$requesturl}'";
		return $wpdb->get_var( $sql );
	}
	return 0;
}

//get number of hits on current post/page
//( Thanks to Greg Froese )
function counterize_current_post_hits()
{
	//don't show anything if more than one post on the page
	if( is_single() || is_page() )
	{
		global $wp_query, $wpdb;
		$thePostID = $wp_query->post->ID;
		$sql = "SELECT `count` "
		. " FROM `" . counterize_pageTable() . "` "
		. " WHERE `postID` = %d";
		$result = $wpdb->get_var( $wpdb->prepare( $sql, $thePostID ) );
		if( ! $result )
		{
			$result = 0;
		}
		return $result;
	}
	return false;
}

// Returns amount of unique URl's
function counterize_getuniqueurl()
{
	global $wpdb;
	$sql = "SELECT COUNT( 1 ) "
		. " FROM `" . counterize_refererTable() . "`";
	return $wpdb->get_var( $sql );
}

function counterize_return_first_hit( $dateformat = "j/n-Y" )
{
	global $wpdb;
	$sql = "SELECT MIN(`timestamp`) "
		. " FROM `" . counterize_logTable() . "`";
	$t = $wpdb->get_var( $sql );
	return date( $dateformat, strtotime( $t ) );
}










// get the most requested urls data feed
function counterize_feed_most_requested_urls( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT `count` , `url` AS url, `url` AS label "
		. " FROM `" . counterize_pageTable() . "`"
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most requested URLs', COUNTERIZE_TD ), __( 'URL', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_3( $row->count, $row->label, $row->url );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most requested urls data feed
function counterize_render_most_requested_urls( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_requested_urls( $number );
	$feed->render_feed_vertical( $width, false, '100%', true, true, false, $print_header );
}











// get the most requested urls data feed for the last 24 hours
function counterize_feed_most_requested_urls24hrs( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$onedayago = date( 'Y-m-d H:i:s', time() - 86400 );
	$sql = "SELECT COUNT( m.`id` ) AS `count`, p.`url` AS url, p.`url` AS label "
		. " FROM `" . counterize_logTable() . "` m, `" . counterize_pageTable() . "` p "
		. " WHERE m.`pageID` = p.`pageID`"
		. " AND m.`timestamp` >= '{$onedayago}'"
		. " GROUP BY p.`url` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most requested URLs ‪of the last 24 hours', COUNTERIZE_TD ), __( 'URL', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_3( $row->count, $row->label, $row->url );
	}
	unset( $rows, $sql, $number, $onedayago );
	$feed->refresh_percentages();

	return $feed;
}

// render the most requested urls data feed for the last 24 hours
function counterize_render_most_requested_urls24hrs( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_requested_urls24hrs( $number, $width );
	$feed->render_feed_vertical( $width, false, '100%', true, true, false, $print_header );
}














// get the most popular posts/pages data feed
function counterize_feed_most_popular_posts( $number = 10, $tn_width = 50, $tn_height = 50 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT c.`postID`, SUM( c.`count`) AS `count`, c.`url`, w.`post_title` AS label "
		. " FROM `" . counterize_pageTable() . "` c, `" . $wpdb->posts . "` w "
		. " WHERE c.`postID` = w.`ID` "
		. " GROUP BY c.`postID` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most popular posts/pages', COUNTERIZE_TD ), __( 'Posts/pages', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$label = trim( stripslashes( $row->label ) );
		if( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( $row->postID ) )
		{
			$thumbnail_id = get_post_thumbnail_id( $post->ID );
			$thumbnail_arr = wp_get_attachment_image_src( $thumbnail_id, Array( $tn_width, $tn_height ) );
			$thumbnail_src = $thumbnail_arr[0];

			$img = new CounterizeFeedImg
			(
				$thumbnail_src,
				$label,
				sprintf( __( 'Click here to view the post "%s"', COUNTERIZE_TD ), $row->label ),
				'counterize_thumb',
				$tn_width,
				$th_height
			);
			$feed->add_item_4( $row->count, $label, $row->url, $img );
			unset( $thumbnail_id, $thumbnail_arr, $thumbnail_src );
		}
		else
		{
			$feed->add_item_3( $row->count, $label, $row->url );
		}
		unset( $label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most popular posts/pages data feed
function counterize_render_most_popular_posts( $number = 10, $width = 300, $tn_width = 50, $tn_height = 50, $print_header = true )
{
	$feed = counterize_feed_most_popular_posts( $number, $tn_width, $tn_height );
	$feed->render_feed_vertical( $width, false, '100%', true, true, false, $print_header );
}












// get the most popular posts/pages data feed for the last 24 hours
function counterize_feed_most_popular_posts24hrs( $number = 10, $tn_width = 50, $tn_height = 50 )
{
	global $wpdb;
	$onedayago = date( 'Y-m-d H:i:s', time() - 86400 );
	$number = $wpdb->prepare( $number );
	$sql = "SELECT COUNT( l.`id` ) AS `count`, c.`postID`, c.`url` AS url, w.`post_title` AS label "
		. " FROM `" . counterize_logTable() . "` l, `" . counterize_pageTable() . "` c, `" . $wpdb->posts . "` w "
		. " WHERE l.`pageID` = c.`pageID` "
		. " AND c.`postID` = w.`ID` "
		. " AND l.`timestamp` >= '{$onedayago}'"
		. " GROUP BY c.`postID` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most popular posts/pages for the last 24 hours', COUNTERIZE_TD ), __( 'Posts/pages', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$label = trim( stripslashes( $row->label ) );
		if( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( $row->postID ) )
		{
			$thumbnail_id = get_post_thumbnail_id( $post->ID );
			$thumbnail_arr = wp_get_attachment_image_src( $thumbnail_id, Array( $tn_width, $tn_height ) );
			$thumbnail_src = $thumbnail_arr[0];

			$img = new CounterizeFeedImg
			(
				$thumbnail_src,
				$label,
				sprintf( __( 'Click here to view the post "%s"', COUNTERIZE_TD ), $row->label ),
				'counterize_thumb',
				$tn_width,
				$th_height
			);
			$feed->add_item_4( $row->count, $label, $row->url, $img );
			unset( $thumbnail_id, $thumbnail_arr, $thumbnail_src );
		}
		else
		{
			$feed->add_item_3( $row->count, $label, $row->url );
		}
		unset( $label );
	}
	unset( $rows, $sql, $onedayago );
	$feed->refresh_percentages();

	return $feed;
}

// render the most popular posts/pages data feed for the last 24 hours
function counterize_render_most_popular_posts24hrs( $number = 10, $width = 300, $tn_width = 50, $tn_height = 50, $print_header = true )
{
	$feed = counterize_feed_most_popular_posts24hrs( $number, $tn_width, $tn_height );
	$feed->render_feed_vertical( $width, false, '100%', true, true, false, $print_header );
}



















// get the most seen referers data feed
function counterize_feed_most_seen_referers( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT `count`, `name` AS label, `name` AS url "
		. " FROM `" . counterize_refererTable() . "`"
		. " WHERE `name` <> 'unknown' "
		. " AND `name` NOT LIKE '" . $wpdb->prepare( get_option( 'home' ) ) . "%%' "
		. " AND `name` NOT LIKE '" . $wpdb->prepare( get_option( 'siteurl' ) ) . "%%' "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most seen referers', COUNTERIZE_TD ), __( 'URL', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_3( $row->count, $row->label, $row->url );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most seen referers data feed
function counterize_render_most_seen_referers( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_seen_referers( $number );
	$feed->render_feed_vertical( $width, false, '100%', true, true, false, $print_header );
}










// get the most seen referers data feed for the last 24 hours
function counterize_feed_most_seen_referers24hrs( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$onedayago = date( 'Y-m-d H:i:s', time() - 86400 );
	$sql = "SELECT COUNT( m.id ) AS `count`, r.name AS label, r.name AS url "
		. " FROM `" . counterize_logTable() . "` m, `" . counterize_refererTable() . "` r "
		. " WHERE m.`refererID` = r.`refererID` "
		. " AND r.`name` <> 'unknown' "
		. " AND r.`name` NOT LIKE '" . $wpdb->prepare( get_option( "home" ) ) . "%%' "
		. " AND r.`name` NOT LIKE '" . $wpdb->prepare( get_option( "siteurl" ) ) . "%%' "
		. " AND m.`timestamp` >= '{$onedayago}'"
		. " GROUP BY r.`name` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most seen referers for the last 24 hours', COUNTERIZE_TD ), __( 'URL', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_3( $row->count, $row->label, $row->url );
	}
	unset( $rows, $sql, $onedayago );
	$feed->refresh_percentages();

	return $feed;
}

// render the most seen referers data feed for the last 24 hours
function counterize_render_most_seen_referers24hrs( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_seen_referers24hrs( $number );
	$feed->render_feed_vertical( $width, false, '100%', true, true, false, $print_header );
}

















// get the most active IP addresses data feed
function counterize_feed_most_active_ips( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$geoip = $wpdb->prepare( counterize_get_option( 'geoip' ) );
	$sql = "SELECT COUNT(`IP`) AS `count`, `IP` AS `label`, CONCAT( '{$geoip}', `IP` ) AS `url` "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `IP` <> 'unavailable' "
		. " GROUP BY `IP` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most active IP addresses', COUNTERIZE_TD ), __( 'IP', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_3( $row->count, $row->label, $row->url );
	}
	unset( $rows, $sql, $geoip );
	$feed->refresh_percentages();

	return $feed;
}

// render the most active IP addresses data feed
function counterize_render_most_active_ips( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_active_ips( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}







// get the most active IP addresses of the last 24 hours data feed
function counterize_feed_most_active_ips24hrs( $number = 10 )
{
	global $wpdb;
	$onedayago = date( 'Y-m-d H:i:s', time() - 86400 );
	$number = $wpdb->prepare( $number );
	$geoip = $wpdb->prepare( counterize_get_option( 'geoip' ) );
	$sql = "SELECT COUNT(`IP`) AS `count`, `IP` AS `label`, CONCAT( '{$geoip}', `IP` ) AS `url` "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `IP` <> 'unavailable' "
		. " AND `timestamp` >= '{$onedayago}'"
		. " GROUP BY `IP` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most active IP addresses for the last 24 hours', COUNTERIZE_TD ), __( 'IP', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_3( $row->count, $row->label, $row->url );
	}
	unset( $rows, $sql, $onedayago, $geoip );
	$feed->refresh_percentages();

	return $feed;
}

// render the most active IP addresses of the last 24 hours data feed
function counterize_render_most_active_ips24hrs( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_active_ips24hrs( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}
















// get the most searched keywords data feed
function counterize_feed_most_searched_keywords( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT `count`, `keyword` AS `label` "
		. " FROM `" . counterize_keywordTable() . "`"
		. " WHERE `keywordID` <> 1 "
		. " GROUP BY `keyword` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most searched keywords', COUNTERIZE_TD ), __( 'Keywords', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_2( $row->count, $row->label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most searched keywords data feed
function counterize_render_most_searched_keywords( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_searched_keywords( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, true, false, $print_header );
}






// get the most searched keywords for the last 24 hours data feed
function counterize_feed_most_searched_keywords24hrs( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$onedayago = date( 'Y-m-d H:i:s', time() - 86400 );
	$sql = "SELECT COUNT( 1 ) AS `count`, k.keyword AS `label` "
		. " FROM " . counterize_keywordTable() . " k, " . counterize_logTable() . " l, " . counterize_refererTable() . " r "
		. " WHERE r.`refererID` = l.`refererID` "
		. " AND r.`keywordID` = k.`keywordID` "
		. " AND k.`keywordID` <> 1 "
		. " AND l.`timestamp` >= '{$onedayago}' "
		. " GROUP BY k.`keyword` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most searched keywords for the last 24 hours', COUNTERIZE_TD ), __( 'Keywords', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$feed->add_item_2( $row->count, $row->label );
	}
	unset( $rows, $sqm, $onedayago );
	$feed->refresh_percentages();

	return $feed;
}

// render the most searched keywords for the last 24 hours data feed
function counterize_render_most_searched_keywords24hrs( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_searched_keywords24hrs( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, true, false, $print_header );
}












// get the most visiting countries data feed
function counterize_feed_most_visiting_countries( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT `count` , `code` "
		. " FROM `" . counterize_countryTable() . "`"
		. " WHERE `count` > 0 "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most visiting countries', COUNTERIZE_TD ), __( 'Countries', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$src = counterize_get_flag_url( $row->code );
		$name = counterize_get_countryname( $row->code );
		if( empty( $row->code ) || $row->code == ' ' || $row->code == '00' )
		{
			$label = __( 'unknown', COUNTERIZE_TD );
		}
		else
		{
			$label = $name;
		}
		if( !empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				sprintf( __( 'National flag of %s', COUNTERIZE_TD ), $name ),
				counterize_get_countryname( $row->code ) . " ({$row->code})",
				'countryflag'
			);
			$feed->add_item_4( $row->count, $label, '', $img );
		}
		else
		{
			$feed->add_item_2( $row->count, $label );
		}
		unset( $src, $name, $label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most visiting countries data feed
function counterize_render_most_visiting_countries( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_visiting_countries( $number );
	$feed->render_feed_vertical( $width, false, '100%', false, false, false, $print_header );
}









// get the most visiting countries data feed for the last 24 hours
function counterize_feed_most_visiting_countries24hrs( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$onedayago = date( 'Y-m-d H:i:s', time() - 86400 );
	$sql = "SELECT COUNT( m.id ) AS `count`, c.code, c.code AS label "
		. " FROM `" . counterize_logTable() . "` m, `" . counterize_countryTable() . "` c "
		. " WHERE m.countryID = c.countryID"
		. " AND m.timestamp >= '{$onedayago}'"
		. " GROUP BY c.code "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most visiting countries for the last 24 hours', COUNTERIZE_TD ), __( 'Countries', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$src = counterize_get_flag_url( $row->code );
		$name = counterize_get_countryname( $row->code );
		if( empty( $row->code ) || $row->code == ' ' || $row->code == '00' )
		{
			$label = __( 'unknown', COUNTERIZE_TD );
		}
		else
		{
			$label = $name;
		}
		if( !empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				sprintf( __( 'National flag of %s', COUNTERIZE_TD ), $name ),
				counterize_get_countryname( $row->code ) . " ({$row->code})",
				'countryflag'
			);
			$feed->add_item_4( $row->count, $label, '', $img );
		}
		else
		{
			$feed->add_item_2( $row->count, $label );
		}
		unset( $src, $name, $label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// show the most visiting countries data feed for the last 24 hours
function counterize_render_most_visiting_countries24hrs( $number = 10, $width = 300, $print_header = true  )
{
	$feed = counterize_feed_most_visiting_countries24hrs( $number );
	$feed->render_feed_vertical( $width, false, '100%', false, false, false, $print_header );
}

































// get the most used browsers data feed with detailed version statistics for each item
function counterize_feed_most_used_browsers_collapsible( $nb_parent_items = 10, $nb_child_items = 15 )
{
	global $wpdb;
	$nb_parent_items = (int) $wpdb->prepare( $nb_parent_items );
	$nb_child_items  = (int) $wpdb->prepare( $nb_child_items );

	$sql_parents =
			"SELECT `browserName` AS `label`, `browserCode` AS `code`, `browserURL` as `url`, SUM( `count` ) AS `count` "
		. "  FROM `" . counterize_agentsTable() . "`"
		. "  GROUP BY `label` "
		. "  ORDER BY `count` DESC , `label` ASC "
		. "  LIMIT {$nb_parent_items} ";

	$sql_children =
			"SELECT `browserVersion` AS `label`, SUM( `count` ) AS `count` "
		. "  FROM `" . counterize_agentsTable() . "`"
		. "  WHERE `browserName` = %s "
		. "  GROUP BY `label` "
		. "  ORDER BY `count` DESC , `label` ASC "
		. "  LIMIT %d";

	$parents_rows = $wpdb->get_results( $sql_parents );
	unset( $sql_parents );
	$parents_feed = new CounterizeFeed( __( 'Most used browsers ‪&#x202A;(click [+] for details)&#x202C;', COUNTERIZE_TD ), __( 'Browsers', COUNTERIZE_TD ) );

	foreach( $parents_rows as $parent_row )
	{
		$src = counterize_get_image_url( $parent_row->code );
		$name = $parent_row->label;
		if( empty( $parent_row->code ) || $parent_row->code == ' ' )
		{
			$parent_label = __( 'Unknown', COUNTERIZE_TD );
		}
		else
		{
			$parent_label = $name;
		}

		$children_rows = $wpdb->get_results( $wpdb->prepare( $sql_children, $parent_label, $nb_child_items ) );
		$has_subitems = ( ( count( $children_rows ) > 1 || ( count( $children_rows ) == 1 && $children_rows[0]->label != '' ) ) && $parent_row->code != 'unknown' );
		if( $has_subitems )
		{
			$children_feed = new CounterizeFeed( __( 'Detailed statistics for this browser', COUNTERIZE_TD ), sprintf( __( '%s versions', COUNTERIZE_TD ), $parent_label ) );
			foreach( $children_rows as $child_row )
			{
				if( empty( $child_row->label ) || $child_row->label == ' ' )
				{
					$child_label = __( '(no version)', COUNTERIZE_TD );
				}
				else
				{
					$child_label = $child_row->label;
				}
				$children_feed->add_item_2( $child_row->count, $child_label );
				unset( $child_label );
			}
			$children_feed->refresh_percentages();
		}
		unset( $children_rows );

		if( !empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				$parent_label,
				$parent_label,
				'browsericon'
			);
			if( $has_subitems )
			{
				$parents_feed->add_item_5( $parent_row->count, $parent_label, $parent_row->url, $img, $children_feed );
			}
			else
			{
				$parents_feed->add_item_4( $parent_row->count, $parent_label, $parent_row->url, $img );
			}
		}
		else
		{
			if( $has_subitems )
			{
				$parents_feed->add_item_5( $parent_row->count, $parent_label, $parent_row->url, NULL, $children_feed );
			}
			else
			{
				$parents_feed->add_item_3( $parent_row->count, $parent_label, $parent_row->url );
			}
		}
		unset( $src, $name, $parent_label );
	}
	unset( $parents_rows, $sql_children );
	$parents_feed->refresh_percentages();

	return $parents_feed;
}

// render the most used browsers data feed with detailed version statistics for each item
function counterize_render_most_used_browsers_collapsible( $nb_parent_items = 10, $nb_child_items = 15, $width = 280, $print_header = true )
{
	$feed = counterize_feed_most_used_browsers_collapsible( $nb_parent_items, $nb_child_items );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}










// get the most used browsers without version data feed
function counterize_feed_most_used_browsers_without_version( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT SUM(`count`) AS `count`, `browserName` AS label, `browserCode` AS `code`, `browserURL` AS `url` "
		. " FROM `" . counterize_agentsTable() . "`"
		. " GROUP BY `label` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most used browsers ‪‪&#x202A;(without version)‪&#x202C;', COUNTERIZE_TD ), __( 'Browsers', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$src = counterize_get_image_url( $row->code );
		$name = $row->label;
		if( empty( $row->code ) || $row->code == ' ' || $row->code == 'unknown' )
		{
			$label = __( 'Unknown', COUNTERIZE_TD );
		}
		else
		{
			$label = $name;
		}
		if( !empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				$label,
				$label,
				'browsericon'
			);
			$feed->add_item_4( $row->count, $label, $row->url, $img );
		}
		else
		{
			$feed->add_item_3( $row->count, $label, $row->url );
		}
		unset( $src, $name, $label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most used browsers without version data feed
function counterize_render_most_used_browsers_without_version( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_used_browsers_without_version( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}



















// get the most used browsers data feed
function counterize_feed_most_used_browsers( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT "
		. " 	SUM( `count` ) AS `count`, "
		. " 	CONCAT( CONCAT( `browserName`, ' ' ), `browserVersion` ) AS `label`, "
		. " 	`browserCode` AS `code`, "
		. " 	`browserURL` AS `url` "
		. " FROM `" . counterize_agentsTable() . "`"
		. " GROUP BY `label` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most used browsers', COUNTERIZE_TD ), __( 'Browsers', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$src = counterize_get_image_url( $row->code );
		$name = $row->label;
		if( empty( $row->code ) || $row->code == ' ' || $row->code == 'unknown' )
		{
			$label = __( 'Unknown', COUNTERIZE_TD );
		}
		else
		{
			$label = $name;
		}
		if( !empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				$label,
				$label,
				'browsericon'
			);
			$feed->add_item_4( $row->count, $label, $row->url, $img );
		}
		else
		{
			$feed->add_item_3( $row->count, $label, $row->url );
		}
		unset( $src, $name, $label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most used browsers data feed
function counterize_render_most_used_browsers( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_used_browsers( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}









































// get the most used os data feed with detailed version statistics for each item
function counterize_feed_most_used_os_collapsible( $nb_parent_items = 10, $nb_child_items = 15 )
{
	global $wpdb;
	$nb_parent_items = (int) $wpdb->prepare( $nb_parent_items );
	$nb_child_items  = (int) $wpdb->prepare( $nb_child_items );

	$sql_parents =
			"SELECT `osName` AS label, `osCode` AS `code`, `osURL` as `url`, SUM( `count` ) AS `count` "
		. "  FROM `" . counterize_agentsTable() . "`"
		. "  GROUP BY `label` "
		. "  ORDER BY `count` DESC , `label` ASC "
		. "  LIMIT {$nb_parent_items} ";

	$sql_children =
			"SELECT `osVersion` AS label, SUM( `count` ) AS `count` "
		. "  FROM `" . counterize_agentsTable() . "`"
		. "  WHERE `osName` = %s "
		. "  GROUP BY `label` "
		. "  ORDER BY `count` DESC , `label` ASC "
		. "  LIMIT %d ";

	$parents_rows = $wpdb->get_results( $sql_parents );
	unset( $sql_parents );
	$parents_feed = new CounterizeFeed( __( 'Most used operating systems ‪&#x202A;(click [+] for details)&#x202C;', COUNTERIZE_TD ), __( 'Operating systems', COUNTERIZE_TD ) );

	foreach( $parents_rows as $parent_row )
	{
		$src = counterize_get_image_url( $parent_row->code );
		$name = $parent_row->label;
		if( empty( $parent_row->code ) || $parent_row->code == ' ' )
		{
			$parent_label = __( 'Unknown', COUNTERIZE_TD );
		}
		else
		{
			$parent_label = $name;
		}

		$children_rows = $wpdb->get_results( $wpdb->prepare( $sql_children, $parent_label, $nb_child_items ) );
		$has_subitems = ( ( count( $children_rows ) > 1 || ( count( $children_rows ) == 1 && $children_rows[0]->label != '' ) ) && $parent_row->code != 'unknown' );
		if( $has_subitems )
		{
			$children_feed = new CounterizeFeed( __( 'Detailed statistics for this operating system', COUNTERIZE_TD ), sprintf( __( '%s versions', COUNTERIZE_TD ), $parent_label ) );
			foreach( $children_rows as $child_row )
			{
				if( empty( $child_row->label ) || $child_row->label == ' ' )
				{
					$child_label = __( '(no version)', COUNTERIZE_TD );
				}
				else
				{
					$child_label = $child_row->label;
				}
				$children_feed->add_item_2( $child_row->count, $child_label );
				unset( $child_label );
			}
			$children_feed->refresh_percentages();
		}
		unset( $children_rows );

		if( ! empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				$parent_label,
				$parent_label,
				'browsericon'
			);
			if( $has_subitems )
			{
				$parents_feed->add_item_5( $parent_row->count, $parent_label, $parent_row->url, $img, $children_feed );
			}
			else
			{
				$parents_feed->add_item_4( $parent_row->count, $parent_label, $parent_row->url, $img );
			}
		}
		else
		{
			if( $has_subitems )
			{
				$parents_feed->add_item_5( $parent_row->count, $parent_label, $parent_row->url, NULL, $children_feed );
			}
			else
			{
				$parents_feed->add_item_3( $parent_row->count, $parent_label, $parent_row->url );
			}
		}
		unset( $src, $name, $parent_label );
	}
	unset( $parents_rows, $sql_children );
	$parents_feed->refresh_percentages();

	return $parents_feed;
}

// render the most used os data feed with detailed version statistics for each item
function counterize_render_most_used_os_collapsible( $nb_parent_items = 10, $nb_child_items = 15, $width = 280, $print_header = true )
{
	$feed = counterize_feed_most_used_os_collapsible( $nb_parent_items, $nb_child_items );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}







// get the most used os without version data feed
function counterize_feed_most_used_os_without_version( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT SUM(`count`) AS `count`, `osName` AS `label`, `osCode` AS `code`, `osURL` AS `url` "
		. " FROM `" . counterize_agentsTable() . "`"
		. " GROUP BY `label` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most used operating systems ‪‪&#x202A;(without version)‪&#x202C;', COUNTERIZE_TD ), __( 'Operating systems', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$src = counterize_get_image_url( $row->code );
		$name = $row->label;
		if( empty( $row->code ) || $row->code == ' ' || $row->code == 'unknown' )
		{
			$label = __( 'Unknown', COUNTERIZE_TD );
		}
		else
		{
			$label = $name;
		}
		if( !empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				$label,
				$label,
				'browsericon'
			);
			$feed->add_item_4( $row->count, $label, $row->url, $img );
		}
		else
		{
			$feed->add_item_3( $row->count, $label, $row->url );
		}
		unset( $src, $name, $label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most used os without version data feed
function counterize_render_most_used_os_without_version( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_used_os_without_version( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}












// get the most used os data feed
function counterize_feed_most_used_os( $number = 10 )
{
	global $wpdb;
	$number = $wpdb->prepare( $number );
	$sql = "SELECT SUM( `count` ) AS `count`, CONCAT( CONCAT( `osName`, ' ' ), `osVersion` ) AS `label`, `osCode` AS `code`, `osURL` AS `url` "
		. " FROM `" . counterize_agentsTable() . "`"
		. " GROUP BY `label` "
		. " ORDER BY `count` DESC "
		. " LIMIT {$number}";
	$rows = $wpdb->get_results( $sql );

	$feed = new CounterizeFeed( __( 'Most used operating systems', COUNTERIZE_TD ), __( 'Operating systems', COUNTERIZE_TD ) );

	foreach( $rows as $row )
	{
		$src = counterize_get_image_url( $row->code );
		$name = $row->label;
		if( empty( $row->code ) || $row->code == ' ' || $row->code == 'unknown' )
		{
			$label = __( 'Unknown', COUNTERIZE_TD );
		}
		else
		{
			$label = $name;
		}
		if( !empty( $src ) )
		{
			$img = new CounterizeFeedImg
			(
				$src,
				$label,
				$label,
				'browsericon'
			);
			$feed->add_item_4( $row->count, $label, $row->url, $img );
		}
		else
		{
			$feed->add_item_3( $row->count, $label, $row->url );
		}
		unset( $src, $name, $label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the most used os data feed
function counterize_render_most_used_os( $number = 10, $width = 300, $print_header = true )
{
	$feed = counterize_feed_most_used_os( $number );
	$feed->render_feed_vertical( $width, true, '100%', false, false, false, $print_header );
}




function counterize_get_hits()
{
	$sincetoday = time() - strtotime( 'today' );
	?>

	<table id="counterizehitcountertable" width="100%" cellpadding="3" cellspacing="3" summary="<?php _e( 'Traffic statistics', COUNTERIZE_TD ); ?>">
		<tr>
			<td scope="col" style="width: 17%" align="center">&nbsp;</td>
			<td scope="col" style="width: 16%" align="center">
				<strong><?php _e( 'Today', COUNTERIZE_TD ); ?></strong>
			</td>
			<td scope="col" style="width: 17%" align="center">
				<strong><?php _e( 'Last 24 hours', COUNTERIZE_TD ); ?></strong>
			</td>
			<td scope="col" style="width: 17%" align="center">
				<strong><?php _e( 'Last 7 days', COUNTERIZE_TD ); ?></strong>
			</td>
			<td scope="col" style="width: 17%" align="center">
				<strong><?php _e( 'Last 30 days', COUNTERIZE_TD ); ?></strong>
			</td>
			<td scope="col" style="width: 16%" align="center">
				<strong><?php _e( 'Total', COUNTERIZE_TD ); ?></strong>
			</td>
		</tr>
		<tr class="alternate">
			<td align="center" class="counterize_caption_help"><strong title="<?php _e( 'A hit is counted each time a ressource is fetched. The resource is not necessarily an existing page or post.', COUNTERIZE_TD ); ?>"><?php _e( 'Hits', COUNTERIZE_TD ); ?></strong></td>
			<td align="center"><?php echo counterize_getamount( false, $sincetoday ); ?></td>
			<td align="center"><?php echo counterize_getamount( false,       86400 ); ?></td>
			<td align="center"><?php echo counterize_getamount( false,      604800 ); ?></td>
			<td align="center"><?php echo counterize_getamount( false,     2592000 ); ?></td>
			<td align="center"><?php echo counterize_getamount(                    ); ?></td>
		</tr>
		<tr>
			<td align="center" class="counterize_caption_help"><strong title="<?php _e( 'A page view is counted each time a hit concerns a valid page or post', COUNTERIZE_TD ); ?>"><?php _e( 'Pages views', COUNTERIZE_TD ); ?></strong></td>
			<td align="center"><?php echo counterize_getpagesamount( $sincetoday ); ?></td>
			<td align="center"><?php echo counterize_getpagesamount(       86400 ); ?></td>
			<td align="center"><?php echo counterize_getpagesamount(      604800 ); ?></td>
			<td align="center"><?php echo counterize_getpagesamount(     2592000 ); ?></td>
			<td align="center"><?php echo counterize_getpagesamount(             ); ?></td>
		</tr>
		<tr class="alternate">
			<td align="center" class="counterize_caption_help"><strong title="<?php _e( 'A unique visitor is counted only the first time its IP is recorded.', COUNTERIZE_TD ); ?>"><?php _e( 'Unique visitors', COUNTERIZE_TD ); ?></strong></td>
			<td align="center"><?php echo counterize_getuniqueamount( $sincetoday ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(       86400 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(      604800 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(     2592000 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(             ); ?></td>
		</tr>
		<tr>
			<td align="center" class="counterize_caption_help"><strong title="<?php _e( 'A visit will be counted again each time two or more hits from the same visitor are separated of more than 1 hour.', COUNTERIZE_TD ); ?>"><?php _e( 'Unique visitors &#x202A;(1h interval)&#x202C;', COUNTERIZE_TD ); ?></strong></td>
			<td align="center"><?php echo counterize_getuniqueamount( $sincetoday, 3600 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(       86400, 3600 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(      604800, 3600 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(     2592000, 3600 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(           0, 3600 ); ?></td>
		</tr>
		<tr class="alternate">
			<td align="center" class="counterize_caption_help"><strong title="<?php _e( 'A visit will be counted again each time two or more hits from the same visitor are separated of more than 30 minutes.', COUNTERIZE_TD ); ?>"><?php _e( 'Unique visitors &#x202A;(30&nbsp;min interval)&#x202C;', COUNTERIZE_TD ); ?></strong></td>
			<td align="center"><?php echo counterize_getuniqueamount( $sincetoday, 1800 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(       86400, 1800 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(      604800, 1800 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(     2592000, 1800 ); ?></td>
			<td align="center"><?php echo counterize_getuniqueamount(           0, 1800 ); ?></td>
		</tr>
		<tr>
			<td align="center" class="counterize_caption_help"><strong title="<?php _e( 'The number of hits per unique visitor.', COUNTERIZE_TD ); ?>"><?php _e( 'Hits per unique visitor', COUNTERIZE_TD ); ?></strong></td>
			<td align="center"><?php $res = counterize_getuniqueamount( $sincetoday ); echo ( $res > 0 ) ? ( round( counterize_getamount( false, $sincetoday ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(       86400 ); echo ( $res > 0 ) ? ( round( counterize_getamount( false,       86400 ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(      604800 ); echo ( $res > 0 ) ? ( round( counterize_getamount( false,      604800 ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(     2592000 ); echo ( $res > 0 ) ? ( round( counterize_getamount( false,     2592000 ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(             ); echo ( $res > 0 ) ? ( round( counterize_getamount(                    ) / $res, 2 ) ) : 0; ?></td>
		</tr>
		<tr class="alternate">
			<td align="center" class="counterize_caption_help"><strong title="<?php _e( 'The number of pages/posts visited per unique visitor.', COUNTERIZE_TD ); ?>"><?php _e( 'Pages per unique visitor', COUNTERIZE_TD ); ?></strong></td>
			<td align="center"><?php $res = counterize_getuniqueamount( $sincetoday ); echo ( $res > 0 ) ? ( round( counterize_getpagesamount( $sincetoday ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(       86400 ); echo ( $res > 0 ) ? ( round( counterize_getpagesamount(       86400 ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(      604800 ); echo ( $res > 0 ) ? ( round( counterize_getpagesamount(      604800 ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(     2592000 ); echo ( $res > 0 ) ? ( round( counterize_getpagesamount(     2592000 ) / $res, 2 ) ) : 0; ?></td>
			<td align="center"><?php $res = counterize_getuniqueamount(             ); echo ( $res > 0 ) ? ( round( counterize_getpagesamount(             ) / $res, 2 ) ) : 0; ?></td>
		</tr>
	</table>

	<?php
}

















// get the daily stats data feed
function counterize_feed_daily_stats( $only_this_month = false )
{
	global $wpdb;
	$sql = "SELECT "
		. " 	DAYOFMONTH( `timestamp` ) AS label, "
		. " 	COUNT( 1 ) AS `count` "
		. " FROM `" . counterize_logTable() . "`";
	if( $only_this_month )
	{
		$sql .= " WHERE `timestamp` >= '" . date( 'Y-m-01' ) . "'";
	}
	$sql .= " GROUP BY `label`";

	$rows = $wpdb->get_results( $sql );

	if( $only_this_month )
	{
		$feed = new CounterizeFeed( __( 'Hits for the current month', COUNTERIZE_TD ), __( 'Day', COUNTERIZE_TD ) );
	}
	else
	{
		$feed = new CounterizeFeed( __( 'Hits based on day of month', COUNTERIZE_TD ), __( 'Day of month', COUNTERIZE_TD ) );
	}

	foreach( $rows as $row )
	{
		$feed->add_item_2( $row->count, $row->label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the daily stats data feed
function counterize_render_daily_stats( $only_this_month = false, $print_header = true )
{
	$feed = counterize_feed_daily_stats( $only_this_month );

	if( is_admin() )
	{
		$feed->render_feed_horizontal( 80, '100%', $print_header );
	}
	else
	{
		$feed->render_feed_vertical( 300, true, '100%', false, false, false, $print_header );
	}
}

















// get the monthly stats data feed
function counterize_feed_monthly_stats( $only_this_year = false )
{
	global $wpdb;
	$sql = "SELECT "
		. " 	CONCAT( CONCAT( SUBSTRING( MONTHNAME( `timestamp` ), 1, 3 ), ' ' ), SUBSTRING( YEAR( `timestamp` ), 3, 2 ) ) AS `label`, "
		. " 	COUNT( 1 ) AS `count`, "
		. " 	MONTH( `timestamp` ) AS `m`, "
		. " 	YEAR( `timestamp` ) AS `y` "
		. " FROM `" . counterize_logTable() . "`";
	if( $only_this_year )
	{
		$sql .= " WHERE `timestamp` >= '" . date( 'Y-01-01' ) . "'";
	}
	$sql .= " GROUP BY `label` "
		. " ORDER BY `y`, `m`";

	$rows = $wpdb->get_results( $sql );

	if( $only_this_year )
	{
		$feed = new CounterizeFeed( __( 'Monthly hits for the current year', COUNTERIZE_TD ), __( 'Month', COUNTERIZE_TD ) );
	}
	else
	{
		$feed = new CounterizeFeed( __( 'Hits based on month', COUNTERIZE_TD ), __( 'Month', COUNTERIZE_TD ) );
	}

	foreach( $rows as $row )
	{
		$feed->add_item_2( $row->count, $row->label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the monthly stats data feed
function counterize_render_monthly_stats( $only_this_year = false, $print_header = true )
{
	$feed = counterize_feed_monthly_stats( $only_this_year );

	if( is_admin() )
	{
		$feed->render_feed_horizontal( 80, '100%', $print_header );
	}
	else
	{
		$feed->render_feed_vertical( 300, true, '100%', false, false, false, $print_header );
	}
}














// get the weekly stats data feed
function counterize_feed_weekly_stats( $only_this_week = false )
{
	global $wpdb;
	/*$now = time();
	if( date( 'w', $now ) == 1 )
	{
		$since = 'midnight';
	}
	else
	{
		$since = 'last Monday';
	}
	$beginning_of_week = strtotime( $since, $now );*/
	$sevendaysago = date( 'Y-m-d', time() - 604800 ); //604800 = 86400 * 7
	$sql = "SELECT "
		. " 	DAYNAME( `timestamp` ) AS `label`, "
		. " 	COUNT( 1 ) AS `count`, "
		. " 	DAYOFWEEK( `timestamp` ) AS `day` "
		. " FROM `" . counterize_logTable() . "` ";
	if( $only_this_week )
	{
		$sql .= " WHERE `timestamp` >= '{$sevendaysago}' ";
	}
	$sql .= " GROUP BY `label` ";
	if( ! $only_this_week )
	{
		$sql .= " ORDER BY `day`";
	}

	$rows = $wpdb->get_results( $sql );

	if( $only_this_week )
	{
		$feed = new CounterizeFeed( __( 'Hits for the last 7 days', COUNTERIZE_TD ), __( 'Day of week', COUNTERIZE_TD ) );
	}
	else
	{
		$feed = new CounterizeFeed( __( 'Hits based on day of week', COUNTERIZE_TD ), __( 'Day of week', COUNTERIZE_TD ) );
	}

	foreach( $rows as $row )
	{
		$feed->add_item_2( $row->count, $row->label );
	}
	unset( $rows, $sql );

	$feed->refresh_percentages();

	return $feed;
}

// render the  weekly stats data feed
function counterize_render_weekly_stats( $only_this_week = false, $print_header = true )
{
	$feed = counterize_feed_weekly_stats( $only_this_week );

	if( is_admin() )
	{
		$feed->render_feed_horizontal( 80, '100%', $print_header );
	}
	else
	{
		$feed->render_feed_vertical( 300, true, '100%', false, false, false, $print_header );
	}
}





// get the weekly stats data feed
function counterize_feed_week_progression_stats()
{
	global $wpdb;

	$sql = "SELECT ";
	for( $i = 7; $i > 0; $i-- )
	{
		$end7   = date( 'Y-m-d', strtotime(  $i - 1 . ' days ago' ) );
		$start7 = date( 'Y-m-d',     strtotime(  $i     . ' days ago' ) );

		$end14   = date( 'Y-m-d', strtotime( $i + 6 . ' days ago' ) );
		$start14 = date( 'Y-m-d',     strtotime( $i + 7 . ' days ago' ) );

		$sql .= "
		(
			SELECT DAYNAME( '{$start7}' )
		) AS `label_{$i}`,
		(
			SELECT (
				SELECT COUNT( `id` )
				FROM `" . counterize_logTable() . "`
				WHERE `timestamp` BETWEEN '{$start7}' AND '{$end7}'
			) / (
				SELECT COUNT( `id` )
				FROM `" . counterize_logTable() . "`
				WHERE `timestamp` BETWEEN '{$start14}' AND '{$end14}'
			)
		) AS `count_{$i}`";
		if( $i > 1 )
		{
			$sql .= ", ";
		}
		unset( $end7, $start7, $end14, $start14 );
	}

	$row = $wpdb->get_row( $sql, ARRAY_A );
	unset( $sql );

	//echo $sql;
	//print_r( $row );

	$feed = new CounterizeFeed( __( 'Progression between last week and current week', COUNTERIZE_TD ), __( 'Day of week', COUNTERIZE_TD ), '%' );

	for( $i = 7; $i > 0; $i-- )
	{
		$feed->add_item_2(  is_null( $row["count_{$i}"] ) ? 0 : ( $row["count_{$i}"] - 1 ) * 100, $row["label_{$i}"] );
	}
	unset( $row );

	$feed->refresh_percentages();

	return $feed;
}

// render the  weekly stats data feed
function counterize_render_week_progression_stats( $print_header = true )
{
	$feed = counterize_feed_week_progression_stats();

	if( is_admin() )
	{
		$feed->render_feed_horizontal( 80, '100%', $print_header, false );
	}
	/*else
	{
		$feed->render_feed_vertical( 300, true, '100%', false, false, false, $print_header );
	}*/
}
















// get the hourly stats data feed
function counterize_feed_hourly_stats( $only_today = false )
{
	global $wpdb;
	$onedayago = date( 'Y-m-d H:i:s', time() - 86400 );
	$sql = "SELECT "
		. " 	HOUR( `timestamp` ) AS `label`, "
		. " 	COUNT( 1 ) AS `count` "
		. " FROM `" . counterize_logTable() . "` ";
	if( $only_today )
	{
		$sql .= " WHERE `timestamp` >= '{$onedayago}'";
	}
	$sql .= " GROUP BY `label` ";

	$rows = $wpdb->get_results( $sql );

	if( $only_today )
	{
		$feed = new CounterizeFeed( __( 'Hourly hits for the last 24 hours', COUNTERIZE_TD ), __( 'Hour', COUNTERIZE_TD ) );
	}
	else
	{
		$feed = new CounterizeFeed( __( 'Hits based on hour of day', COUNTERIZE_TD ), __( 'Hour', COUNTERIZE_TD ) );
	}

	foreach( $rows as $row )
	{
		$feed->add_item_2( $row->count, $row->label );
	}
	unset( $rows, $sql );
	$feed->refresh_percentages();

	return $feed;
}

// render the  hourly stats data feed
function counterize_render_hourly_stats( $only_today = false, $print_header = true )
{
	$feed = counterize_feed_hourly_stats( $only_today );

	if( is_admin() )
	{
		$feed->render_feed_horizontal( 80, '100%', $print_header );
	}
	else
	{
		$feed->render_feed_vertical( 300, true, '100%', false, false, false, $print_header );
	}
}














function counterize_ref_analyzer( $referer )
{
	if( !empty( $referer ) && $referer != "unknown" )
	{
		$domain = explode( '/', $referer );

		$source = array(
			array( 'google'   , 'q' ),
			array( 'bing'     , 'q' ),
			array( 'yahoo'    , array( 'p', 'q') ),
			array( 'msn'      , 'q' ),
			array( 'ask'      , 'q' ),
			array( 'baidu'    , 'wd' ),
			array( 'aol'      , array( 'query', 'encquery', 'q' ) ),
			array( 'alltheweb', 'q' ),
			array( 'altavista', 'q' ),
			array( 'excite'   , 'search' ),
			array( 'hotbot'   , 'query' ),
			array( 'lycos'    , 'query' ),
			array( 'live'     , 'q' ),
			array( 't-online' , 'q' ),
			array( 'netscape' , 'query' ),
			array( 'daum'     , 'q' ),
			array( 'eniro'    , 'search_word' ),
			array( 'pchome'   , 'q' ),
			array( 'cnn'      , 'query' ),
			array( 'about'    , 'terms' ),
			array( 'mamma'    , array( 'q', 'query' ) ),
			array( 'voila'    , 'rdata' ),
			array( 'virgilio' , 'qs' ),
			array( 'alice'    , 'qs' ),
			array( 'najdi'    , 'q' ),
			array( 'seznam'   , 'q' ),
			array( 'search'   , 'q' ),
			array( 'wp'       , 'szukaj' ),
			array( 'onet'     , 'qt' ),
			array( 'szukacz'  , 'q' ),
			array( 'yam'      , 'k' ),
			array( 'kvasir'   , 'q' ),
			array( 'sesam'    , 'q' ),
			array( 'ozu'      , 'q' ),
			array( 'terra'    , 'query' ),
			array( 'mynet'    , 'q' ),
			array( 'ekolay'   , 'q' ),
			array( 'rambler'  , 'query' ),
			array( 'yandex'   , 'text' )
		);

		$keyword = '';
		$output = Array();
		for( $i = 0, $nb = count( $source ); $i < $nb; $i++ )
		{
			if( preg_match( '#' . $source[$i][0] . '#i', $referer ) )
			{
				$parse = parse_url( $referer );
				parse_str( $parse[ 'query' ], $output );
				if( is_array( $source[$i][1] ) )
				{
					foreach( $source[$i][1] as $q )
					{
						if( isset( $output[$q] ) )
						{
							$keyword = $output[$q];
						}
						break 2;
					}
				}
				else
				{
					if( isset( $output[ $source[$i][1] ] ) )
					{
						$keyword = $output[ $source[$i][1] ];
					}
					break;
				}
			}
		}

		return array( 'domain' => str_replace( 'www.', '', $domain[2] ), 'keyword' => strtolower( $keyword ) );
	}
	else
	{
		return array( 'domain' => '', 'keyword' => '' );
	}
}

// Returns amount of unique hits today
function counterize_getuniquehitstoday()
{
	global $wpdb;
	$today = date( 'Y-m-d' );
	$sql = "SELECT COUNT( DISTINCT `haship` ) "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `timestamp` >= '{$today}'";
	return $wpdb->get_var( $sql );
}

// Returns amount of hits today, from the visiting IP
function counterize_gethitstodayfromcurrentip()
{
	global $wpdb;
	$today = date( 'Y-m-d' );
	$sql = $wpdb->prepare
	(
		"SELECT COUNT( 1 ) "
		. " FROM `" . counterize_logTable() . "`"
		. " WHERE `timestamp` >= %s "
		. " AND `IP` = %s ;",
		$today,
		$_SERVER['REMOTE_ADDR']
	);
	return $wpdb->get_var( $sql );
}

//similar to WordPress's check_admin_referer but does not die if check failed
function counterize_check_admin_referer( $action = -1, $query_arg = '_wpnonce' )
{
	$adminurl = strtolower( admin_url() );
	$referer = strtolower( wp_get_referer() );
	$result = isset( $_REQUEST[$query_arg] ) ? wp_verify_nonce( $_REQUEST[$query_arg], $action ) : false;
	if( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) )
	{
		$result = false;
	}
	return $result;
}

/*
 * Returns an array containing the SQL to fetch information matching ID in DB, the number of entries and the number of pages.
 * This function is mostly used by the History.
 * It will take care of all the filters defined in the History.
 * Do not modify if you don't know what you do.
 */
function counterize_getentries_sql( $amount = 50, $entryID = null )
{
	global $wpdb;
	$limit = 50;
	$offset = 0;

	if( ! is_numeric( $amount ) || $amount == 0 )
	{
		$amount = 50;
	}

	//check if ipfilter is set
	if( isset( $_POST['ipfilter'] ) && !empty( $_POST['ipfilter'] ) )
	{
		$ipfilter = $_POST['ipfilter'];
	}
	elseif( isset( $_GET['ipfilter'] ) && !empty( $_GET['ipfilter'] ) )
	{
		$ipfilter = $_GET['ipfilter'];
	}

	//check if countryfilter is set
	if( isset( $_POST['countryfilter'] ) && !empty( $_POST['countryfilter'] ) )
	{
		$countryfilter = $_POST['countryfilter'];
	}
	elseif( isset( $_GET['countryfilter'] ) && !empty( $_GET['countryfilter'] ) )
	{
		$countryfilter = $_GET['countryfilter'];
	}

	//check if urifilter is set
	if( isset( $_POST['urifilter'] ) && !empty( $_POST['urifilter'] ) )
	{
		$urifilter = $_POST['urifilter'];
	}
	elseif( isset( $_GET['urifilter'] ) && !empty( $_GET['urifilter'] ) )
	{
		$urifilter = $_GET['urifilter'];
	}

	//check if refererfilter is set
	if( isset( $_POST['refererfilter'] ) && !empty( $_POST['refererfilter'] ) )
	{
		$refererfilter = $_POST['refererfilter'];
	}
	elseif( isset( $_GET['refererfilter'] ) && !empty( $_GET['refererfilter'] ) )
	{
		$refererfilter = $_GET['refererfilter'];
	}

	//check if agentfilter is set
	if( isset( $_POST['agentfilter'] ) && !empty( $_POST['agentfilter'] ) )
	{
		$agentfilter = $_POST['agentfilter'];
	}
	elseif( isset( $_GET['agentfilter'] ) && !empty( $_GET['agentfilter'] ) )
	{
		$agentfilter = $_GET['agentfilter'];
	}

	//check if agentfilter is set
	if( isset( $_POST['keywordfilter'] ) && !empty( $_POST['keywordfilter'] ) )
	{
		$keywordfilter = $_POST['keywordfilter'];
	}
	elseif( isset( $_GET['keywordfilter'] ) && !empty( $_GET['keywordfilter'] ) )
	{
		$keywordfilter = $_GET['keywordfilter'];
	}

	//check if filtertype is set
	if( isset( $_POST['filtertype'] ) && !empty( $_POST['filtertype'] ) )
	{
		$filtertype = $_POST['filtertype'];
	}
	elseif( isset( $_GET['filtertype'] ) && !empty( $_GET['filtertype'] ) )
	{
		$filtertype = $_GET['filtertype'];
	}

	//check if counterize_gotopage is set
	if( isset( $_POST['counterize_gotopage'] ) && !empty( $_POST['counterize_gotopage'] ) )
	{
		$counterize_gotopage = $_POST['counterize_gotopage'];
	}
	elseif( isset( $_GET['counterize_gotopage'] ) && !empty( $_GET['counterize_gotopage'] ) )
	{
		$counterize_gotopage = $_GET['counterize_gotopage'];
	}





	//generate the SQL query
	$sql_items = "SELECT `id`, `IP`, `haship`, `timestamp`, p.url AS url, r.name AS referer, ua.name AS useragent, c.code AS countrycode, "
		. " m.refererID, m.agentID, m.pageID, m.countryID, k.keyword, k.keywordID ";
	$sql_count = "SELECT COUNT( `id` ) ";

	$sql =" FROM `"
		.	counterize_logTable() . "` m, `"
		.	counterize_pageTable() . "` p, `"
		.	counterize_agentsTable() . "` ua, `"
		.	counterize_countryTable() . "` c, `"
		.	counterize_refererTable() . "` r, `"
		.	counterize_keywordTable() . "` k "
		. " WHERE m.pageID = p.pageID "
		. " AND m.agentID = ua.agentID "
		. " AND m.countryID = c.countryID "
		. " AND m.refererID = r.refererID "
		. " AND k.keywordID = r.keywordID";

	$comparator = '=';
	if
	(
		isset( $filtertype )
		&&	$filtertype == 'ex'
		&&
		(
			counterize_check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$comparator = '<>';
	}

	//if an IP filter is set
	if
	(
		isset( $ipfilter )
		&&
		(
			counterize_check_admin_referer( 'action_ip_filter' )
		||	counterize_check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$sql .= ' AND ( ';
		$filters = explode( '||', $ipfilter );
		$first = true;
		foreach( $filters as $filter )
		{
			if( $first )
			{
				$first = false;
				$sql .= " m.IP {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
			else
			{
				$logical = 'OR';
				if( $comparator == '<>' )
				{
					$logical = 'AND';
				}
				$sql .= " {$logical} m.IP {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
		}
		unset( $filters );
		$sql .= ' ) ';
	}

	//if a country filter is set
	if
	(
		isset( $countryfilter )
		&&
		(
			counterize_check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' )
		||	counterize_check_admin_referer( 'action_country_filter' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$sql .= ' AND ( ';
		$filters = explode( '||', $countryfilter );
		$first = true;
		foreach( $filters as $filter )
		{
			if( $first )
			{
				$first = false;
				$sql .= " c.code {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
			else
			{
				$logical = 'OR';
				if( $comparator == '<>' )
				{
					$logical = 'AND';
				}
				$sql .= " {$logical} c.code {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
		}
		unset( $filters );
		$sql .= ' ) ';
	}

	//if an URL filter is set
	if
	(
		isset( $urifilter )
		&&
		(
			counterize_check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' )
		||	counterize_check_admin_referer( 'action_uri_filter' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$sql .= ' AND ( ';
		$filters = explode( '||', $urifilter );
		$first = true;
		foreach( $filters as $filter )
		{
			if( $first )
			{
				$first = false;
				$sql .= " p.url {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
			else
			{
				$logical = 'OR';
				if( $comparator == '<>' )
				{
					$logical = 'AND';
				}
				$sql .= " {$logical} p.url {$comparator} '" . $wpdb->prepare( $filter ) . "' ";
			}
		}
		unset( $filters );
		$sql .= ' ) ';
	}

	//if a referer filter is set
	if
	(
		isset( $refererfilter )
		&&
		(
			counterize_check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' )
		||	counterize_check_admin_referer( 'action_referer_filter' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$sql .= ' AND ( ';
		$filters = explode( '||', $refererfilter );
		$first = true;
		foreach( $filters as $filter )
		{
			if( $first )
			{
				$first = false;
				$sql .= " r.name {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
			else
			{
				$logical = 'OR';
				if( $comparator == '<>' )
				{
					$logical = 'AND';
				}
				$sql .= " {$logical} r.name {$comparator} '" . $wpdb->prepare( $filter ) . "' ";
			}
		}
		unset( $filters );
		$sql .= ' ) ';
	}

	//if an user-agent filter is set
	if
	(
		isset( $agentfilter )
		&&
		(
			counterize_check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' )
		||	counterize_check_admin_referer( 'action_agent_filter' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$sql .= ' AND ( ';
		$filters = explode( '||', $agentfilter );
		$first = true;
		foreach( $filters as $filter )
		{
			if( $first )
			{
				$first = false;
				$sql .= " ua.name {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
			else
			{
				$logical = 'OR';
				if( $comparator == '<>' )
				{
					$logical = 'AND';
				}
				$sql .= " {$logical} ua.name {$comparator} '" . $wpdb->prepare( $filter ) . "' ";
			}
		}
		unset( $filters );
		$sql .= ' ) ';
	}

	//if a keyword filter is set
	if
	(
		isset( $keywordfilter )
		&&
		(
			counterize_check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' )
		||	counterize_check_admin_referer( 'action_keyword_filter' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$sql .= ' AND ( ';
		$filters = explode( '||', $keywordfilter );
		$first = true;
		foreach( $filters as $filter )
		{
			if( $first )
			{
				$first = false;
				$sql .= " k.keyword {$comparator} '" . $wpdb->prepare( $filter ) ."' ";
			}
			else
			{
				$logical = 'OR';
				if( $comparator == '<>' )
				{
					$logical = 'AND';
				}
				$sql .= " {$logical} k.keyword {$comparator} '" . $wpdb->prepare( $filter ) . "' ";
			}
		}
		unset( $filters );
		$sql .= ' ) ';
	}
	unset( $comparator );

	//if an entryID is set
	if( isset( $entryID ) )
	{
		$sql .= " AND m.id = " . $wpdb->prepare( $entryID );
	}

	$sql_items .= $sql;
	$sql_count .= $sql;

	$sql_items .= " ORDER BY m.timestamp DESC";





	//get the number of entries and compute the number of pages
	$nbentries = intval( $wpdb->get_var( $sql_count ) );
	unset( $sql_count );
	if( $amount <= 0 )
	{
		$amount = 50;
	}
	$lastpage = ceil( $nbentries / $amount );

	if
	(
		isset( $counterize_gotopage )
		&&	is_numeric( $counterize_gotopage )
		&&
		(
			counterize_check_admin_referer( 'counterize_history_nav', 'counterize_history_nav_field' )
		||	counterize_check_admin_referer( 'action_nav_link' )
		)
	)
	{
		$currentpage = intval( $counterize_gotopage );
	}
	else
	{
		$currentpage = 1;
	}
	if( $currentpage < 1 )
	{
		$currentpage = 1;
	}
	elseif( $currentpage > $lastpage )
	{
		$currentpage = $lastpage;
	}



	//add the LIMIT boundaries
	if( is_numeric( $amount ) )
	{
		if( intval( $amount ) > 0 )
		{
			$limit = intval( $amount );
		}
	}
	$offset = $limit * ( $currentpage - 1 );
	if( $offset < 0 )
	{
		//This case only happens when the database is empty
		$offset = 0;
	}
	$sql_items .= " LIMIT {$offset}, {$limit}";


	return Array( $sql_items, $nbentries, $lastpage );
}



/*
 * Insert new data into the database.
 * Only insert unfiltered data.
 * Only insert if not a bot.
 * Get all the informations from the $_SERVER array.
 */
function counterize_add_callback()
{
	global $wpdb;
	global $user_ID;
	global $counterize_plugin_dir;

	// Set to unknown, if we're unable to extract information below.
	$referer = $remoteaddr = $useragent = $requesturl = 'unknown';

	if( isset( $_SERVER['REMOTE_ADDR'] ) )
	{
		$remoteaddr = $_SERVER['REMOTE_ADDR'];
	}
	if( isset( $_SERVER['HTTP_USER_AGENT'] ) )
	{
		$useragent = $_SERVER['HTTP_USER_AGENT'];
	}
	if( isset( $_SERVER['REQUEST_URI'] ) )
	{
		$requesturl = $_SERVER['REQUEST_URI'];
	}
	if( isset( $_SERVER['HTTP_REFERER'] ) )
	{
		$referer = $_SERVER['HTTP_REFERER'];
	}

	$this_url = "http://" . $_SERVER['HTTP_HOST'] . $requesturl;
	// Check to see if we really want to insert the entry...

	$checkval = 0;

	//
	// Bots detected and excluded if necessary
	//
	$logbots = counterize_get_option( 'logbots' );
	if( $logbots != '1' )
	{
		$botarray = Array();
		if( file_exists( $counterize_plugin_dir . "/botlist.txt" ) )
		{
			$botarray = file( $counterize_plugin_dir . "/botlist.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES );
		}

		// Run through bot-array and see if there's anything we don't like...
		foreach( $botarray as $entry )
		{

			//Check for special parameters to allow complex bot search without
			// blocking the user agent completely.
			//Formats are :
			// "complexfilter:Suspicious user-agent string###/page_url_without_domain_name###Complete_referer_string" without quotes
			// "regexp:regular_expression" without quotes
			//Desired effect of the first format is: remove bot entries without deleting legitimate
			// entries, in case the bot is faking a real browser user agent but
			// always use the same referer and page, which real users do not.
			$is_regexp  = ( strpos( $entry, 'regexp:' ) !== FALSE );
			$is_complex = ( strpos( $entry, 'complexfilter:' ) !== FALSE );

			if( $is_complex )
			{
				$entry = str_replace( 'complexfilter:', '', $entry );
				$temp = explode( '###', $entry );
				if( isset( $temp[1] ) && isset( $temp[2] ) )
				{
					$page = $temp[1];
					$refer = $temp[2];
					if( $refer == '%HTTP_HOST%' )
					{
						$refer = 'http://' . $_SERVER['HTTP_HOST'] . '/';
					}
				}
				else
				{
					//by security
					$is_complex = false;
				}
				unset( $temp );
				$condition = stristr( $useragent, $bot ) !== FALSE;
			}
			elseif( $is_regexp )
			{
				$bot = str_replace( 'regexp:', '', $entry );
				$refer = '';
				$page = '';
				$condition = preg_match( $bot, $useragent );
			}
			else
			{
				$bot = $entry;
				$refer = '';
				$page = '';
				$condition = stristr( $useragent, $bot ) !== FALSE;
			}

			//if we found a bot then
			if( $condition )
			{
				//if we have a complex filter
				if( $is_complex && !empty( $refer ) && !empty( $page ) )
				{
					if( $page != '*' )
					{
						if( $refer == $referer && $requesturl == $page )
						{
							$checkval = 1;
						}
					}
					else
					{
						if( $refer == $referer )
						{
							$checkval = 1;
						}
					}
				}
				else
				{
					$checkval = 1;
				}
				break;
			}
		}
	}

	// From SHRIKEE, don't count RSS and other stuff...
	// Exclude files from being counted
	if( $checkval == 0 )
	{
		// Exclude if referer is the same as url
		if( $this_url == $referer )
		{
			$checkval = 1;
		}

		// Exclude RSS feeds (Both with and without permalinks)
		// Stating just feed would make it impossible to name a page or post 'feed'
		/* if( stristr( $requesturl, "feed/" ) )
		$checkval = 1;
		if( stristr( $requesturl, "feed=" ) )
		$checkval = 1;
		*/
		// Exclude files which browsers like safari and opera request on each page
		if( stristr( $requesturl, 'robots.txt' ) )
		{
			$checkval = 1;
		}
		elseif( stristr( $requesturl, 'favicon.ico' ) )
		{
			$checkval = 1;
		}

		// Exclude any admin or core files
		elseif( stristr( $requesturl, 'wp-includes/' ) )
		{
			$checkval = 1;
		}
		elseif( stristr( $requesturl, 'wp-admin/' ) )
		{
			$checkval = 1;
		}
		elseif( stristr( $requesturl, 'wp-content/' ) )
		{
			$checkval = 1;
		}
	}

	// more extensions?
	elseif( stristr( $requesturl, '.jpg' ) )
	{
		$checkval = 1;
	}
	elseif( stristr( $requesturl, '.bmp' ) )
	{
		$checkval = 1;
	}
	elseif( stristr( $requesturl, '.png' ) )
	{
		$checkval = 1;
	}
	elseif( stristr( $requesturl, '.gif' ) )
	{
		$checkval = 1;
	}


	// If not found anything unwanted yet, check to see if it's on the excludelist...
	if( $checkval == 0 )
	{
		$excludelist = counterize_get_option( 'excludedip' );

		$tmp_array = explode( ',', $excludelist );
		$count = count( $tmp_array );

		if( $excludelist != '' && $excludelist != ' ' )
		{
			for( $i = 0; $i < $count; $i++ )
			{
				if( strpos( $remoteaddr, $tmp_array[$i] ) !== FALSE )
				{
					// IP found on exclude-list - we don't want it!
					$checkval = 1;
				}
			}
		}
	}

	// DISABLED: This functionality is replaced with the admin functionality
	//			to enable/disable counting of certain users...
	//
	// let's check it is a logged in user.
	// If he's logged in, we don't count him.
	if( $checkval == 0 )
	{
		$excluded_users = explode( ',', counterize_get_option( 'excludedusers' ) );
		get_currentuserinfo();
		$tmp = count( $excluded_users );
		if( $user_ID != '' && $user_ID != ' ' && in_array( $user_ID, $excluded_users ) )
		{
			$checkval = 1;
		}
	}

	// If checkval is still 0, then yes - we want to insert it...
	if( $checkval == 0 )
	{
		// Replace %20's(spaces) in strings with a white-space
		// Man, someone should create a better checking-module... *sigh*
		$requesturl = str_replace( '%20', ' ', $requesturl );
		$referer = str_replace( '%20', ' ', $referer );
		$timestamp = gmdate( 'Y-m-d H:i:s', time() + ( get_option( 'gmt_offset' ) * 3600  ) ); // 3600 = 60 * 60

		$can_collect_ip = intval( counterize_get_option( 'enableip' ) );
		$country_code = counterize_iptocountrycode( $remoteaddr );

		$agentID   = counterize_getUserAgentID( $useragent    );
		$pageID    = counterize_getPageID     ( $requesturl   );
		$keywordID = counterize_getKeywordID  ( $referer      );
		$refererID = counterize_getRefererID  ( $referer      );
		$countryID = counterize_getCountryID  ( $country_code );

		$sql = "INSERT IGNORE INTO `" . counterize_logTable() . "` "
			. " (`IP`, `haship`, `timestamp`, `pageID`, `refererID`, `agentID`, `countryID`) "
			. " VALUES ( %s, %s, %s, %d, %d, %d, %d ) ;";
		$sql = $wpdb->prepare
		(
			$sql,
			( $can_collect_ip > 0 ? $remoteaddr : 'unavailable' ),
			substr( md5( $remoteaddr ), 1, 16 ),
			$timestamp,
			$pageID,
			$refererID,
			$agentID,
			$countryID
		);

		$results = $wpdb->query( $sql );

		counterize_AddUserAgentVisit( $agentID   );
		counterize_AddPageVisit     ( $pageID    );
		counterize_AddKeywordVisit  ( $keywordID );
		counterize_AddRefererVisit  ( $refererID );
		counterize_AddCountryVisit  ( $countryID );
	}
}

// gives the useragentID back
function counterize_getUserAgentID( $useragent )
{
	global $wpdb;
	$sql = $wpdb->prepare
	(
		"SELECT `agentID` "
		. " FROM `" . counterize_agentsTable() . "` "
		. " WHERE `name` = %s",
		$useragent
	);

	$agentID = $wpdb->get_var( $sql );

	if( is_null( $agentID ) )
	{
		// creates a new agent
		list
		(
			$browser_name, $browser_code, $browser_ver, $browser_url,
			$os_name, $os_code, $os_ver, $os_url,
			$pda_name, $pda_code, $pda_ver, $pda_url
		) = counterize_detect_browser( $useragent );

		$sql = $wpdb->prepare
		(
			"INSERT IGNORE INTO `" . counterize_agentsTable() . "` "
			. " (`name`, `count`, `browserName`, `browserCode`, `browserVersion`, `browserURL`, `osName`, `osCode`, `osVersion`, `osURL`) "
			. " VALUES ( %s, 0, %s, %s, %s, %s, %s, %s, %s, %s ) ;",
			$useragent,
			$browser_name,
			$browser_code,
			$browser_ver,
			$browser_url,
			$os_name,
			$os_code,
			$os_ver,
			$os_url
		);
		$wpdb->query( $sql );
		return $wpdb->insert_id;
	}
	return $agentID;
}

function counterize_AddUserAgentVisit( $agentID )
{
	global $wpdb;
	if( is_numeric( $agentID ) )
	{
		$sql = $wpdb->prepare
		(
			"UPDATE `" . counterize_agentsTable() . "` "
			. " SET `count` = `count` + 1 "
			. " WHERE `agentID` = %d ;",
			$agentID
		);
		$wpdb->query( $sql );
	}
}









// gives the useragentID back
function counterize_getCountryID( $code )
{
	global $wpdb;
	$sql = $wpdb->prepare
	(
		"SELECT `countryID` "
		. " FROM `" . counterize_countryTable() . "`  "
		. " WHERE `code` = %s ;",
		$code
	);
	$countryID = $wpdb->get_var( $sql );

	if( is_null( $countryID ) )
	{
		// creates a new country
		$sql = $wpdb->prepare
		(
			"INSERT IGNORE INTO `" . counterize_countryTable() . "` "
			. " (`code`, `count`) VALUES ( '%s', 0 ) ;",
			$code
		);
		$wpdb->query( $sql );
		return $wpdb->insert_id;
	}
	return $countryID;
}

function counterize_AddCountryVisit( $countryID )
{
	global $wpdb;
	if( is_numeric( $countryID ) )
	{
		$sql = $wpdb->prepare
		(
			"UPDATE `" . counterize_countryTable() . "` "
			. " SET `count` = `count` + 1 "
			. " WHERE `countryID` = %d ;",
			$countryID
		);
		$wpdb->query( $sql );
	}
}





// gives the keywordID back
function counterize_getKeywordID( $referer )
{
	global $wpdb;
	$ref = counterize_ref_analyzer( $referer );
	$sql = $wpdb->prepare
	(
		"SELECT `keywordID` "
		. " FROM `" . counterize_keywordTable() . "` "
		. " WHERE `keyword` = %s ;",
		$ref['keyword']
	);
	$keywordID = $wpdb->get_var( $sql );

	if( is_null( $keywordID )  )
	{
		// create new keyword
		$sql = $wpdb->prepare
		(
			"INSERT IGNORE INTO `" . counterize_keywordTable() . "` "
			. " (`keyword`, `count`) "
			. " VALUES ( %s, 0 ) ;",
			$ref['keyword']
		);
		$wpdb->query( $sql );
		return $wpdb->insert_id;
	}
	return $keywordID;
}


function counterize_AddKeywordVisit( $keywordID )
{
	global $wpdb;
	if( is_numeric( $keywordID ) )
	{
		$sql = $wpdb->prepare
		(
			"UPDATE `" . counterize_keywordTable() . "` "
			. " SET `count` = `count` + 1 "
			. " WHERE `keywordID` = %d ;",
			$keywordID
		);
		$wpdb->query( $sql );
	}
}

// gives the pageID back
function counterize_getPageID( $url )
{
	global $wpdb;
	global $post;
	$sql = $wpdb->prepare
	(
		"SELECT `pageID` "
		. " FROM `" . counterize_pageTable() . "` "
		. " WHERE `url` = %s ;",
		$url
	);
	$pageID = $wpdb->get_var( $sql );

	if( is_null( $pageID ) )
	{
		//search for an eventual post ID
		$post_id = ( ( is_single() || $post->post_type == 'page' ) ? $post->ID : 'NULL' );
		if( $post_id == 'NULL' )
		{
			$post_id = url_to_postid( $url );
			if( $post_id == 0 )
			{
				$post_id = 'NULL';
			}
		}

		// create a new page
		$sql = $wpdb->prepare
		(
			"INSERT IGNORE INTO `" . counterize_pageTable() . "` "
			. " ( `url`, `count`, `postID` ) "
			. " VALUES ( %s, 0, %d ) ;",
			$url,
			$post_id
		);
		$wpdb->query( $sql );
		return $wpdb->insert_id;
	}
	return $pageID;
}

function counterize_AddPageVisit( $pageID )
{
	global $wpdb;
	if( is_numeric( $pageID ) )
	{
		$sql = $wpdb->prepare
		(
			"UPDATE `" . counterize_pageTable() . "` "
			. " SET `count` = `count` + 1 "
			. " WHERE `pageID` = %d ;",
			$pageID
		);
		$wpdb->query( $sql );
	}
}



// gives the refererID back
function counterize_getRefererID( $referer )
{
	global $wpdb;
	$sql = $wpdb->prepare
	(
		"SELECT `refererID` "
		. " FROM `" . counterize_refererTable() . "`"
		. " WHERE `name` = %s ;",
		$referer
	);
	$refererID = $wpdb->get_var( $sql );

	if( is_null( $refererID ) )
	{
		$keywordID = counterize_getKeywordID( $referer );
		// create new referer
		$sql = $wpdb->prepare
		(
			"INSERT IGNORE INTO `" . counterize_refererTable() . "`"
			. " (`name`, `count`, `keywordID`) "
			. " VALUES ( %s, 0, %d ) ;",
			$referer,
			$keywordID
		);
		$wpdb->query( $sql );
		return $wpdb->insert_id;
	}
	return $refererID;
}

function counterize_AddRefererVisit( $refererID )
{
	global $wpdb;
	if( is_numeric( $refererID ) )
	{
		$sql = $wpdb->prepare
		(
			"UPDATE `" . counterize_refererTable() . "`"
			. " SET `count` = `count` + 1 "
			. " WHERE `refererID` = %d ;",
			$refererID
		);
		$wpdb->query( $sql );
	}
}

function counterize_copyright()
{
	?>

	<p style="text-align: center">
		<small><?php
			_e( 'Statistics recorded with <a href="http://www.gabsoftware.com/products/scripts/counterize/" title="Counterize - Statistics-plugin for WordPress by GabSoftware">Counterize</a>', COUNTERIZE_TD );
			echo ' - ' . __( 'Version' ) . ' ' . counterize_get_version( 'major' ) . "." . counterize_get_version( 'minor' ) . "." . counterize_get_version( 'revision' );
		?></small>
	</p>

	<?php
}








/*
 * Add an invisible space every 5 characters into words of more than 10 characters
 * in order to make the string breakable when fitting in a small box
 */
function counterize_wordwrap( $text )
{
	$split = explode( ' ', $text );
	foreach( $split as $key=>$value )
	{
		if( strlen( $value ) > 10 )
		{
			//$split[$key] = chunk_split( $value, 5, '&#8203;' );
			$split[$key] = chunk_split( $value, 5, ' ' );
		}
	}
	return implode( ' ', $split );
}



/*
 *
 * Show the Counterize History.
 * Modify with caution.
 */
function counterize_show_history( $frompage = "counterize_dashboard", $directcall = false )
{
	global $counterize_plugin_dir;
	global $counterize_plugin_url;
	global $wpdb;

	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}

	$howmany = __( 'Latest entries', COUNTERIZE_TD );

	$amount = counterize_get_option( 'amount' );
	if( $amount == '' || $amount == ' ' )
	{
		$amount = 50;
	}

	$howmany = "{$howmany} &#x202A;({$amount})&#x202C;";

	$url = "admin.php?page={$frompage}";

	//check if ipfilter is set
	if( isset( $_POST['ipfilter'] ) && !empty( $_POST['ipfilter'] ) )
	{
		$ipfilter = htmlspecialchars( $_POST['ipfilter'] );
	}
	elseif( isset( $_GET['ipfilter'] ) && !empty( $_GET['ipfilter'] ) )
	{
		$ipfilter = htmlspecialchars( $_GET['ipfilter'] );
	}

	//check if countryfilter is set
	if( isset( $_POST['countryfilter'] ) && !empty( $_POST['countryfilter'] ) )
	{
		$countryfilter = htmlspecialchars( $_POST['countryfilter'] );
	}
	elseif( isset( $_GET['countryfilter'] ) && !empty( $_GET['countryfilter'] ) )
	{
		$countryfilter = htmlspecialchars( $_GET['countryfilter'] );
	}

	//check if urifilter is set
	if( isset( $_POST['urifilter'] ) && !empty( $_POST['urifilter'] ) )
	{
		$urifilter = htmlspecialchars( $_POST['urifilter'] );
	}
	elseif( isset( $_GET['urifilter'] ) && !empty( $_GET['urifilter'] ) )
	{
		$urifilter = htmlspecialchars( $_GET['urifilter'] );
	}

	//check if refererfilter is set
	if( isset( $_POST['refererfilter'] ) && !empty( $_POST['refererfilter'] ) )
	{
		$refererfilter = htmlspecialchars( $_POST['refererfilter'] );
	}
	elseif( isset( $_GET['refererfilter'] ) && !empty( $_GET['refererfilter'] ) )
	{
		$refererfilter = htmlspecialchars( $_GET['refererfilter'] );
	}

	//check if agentfilter is set
	if( isset( $_POST['agentfilter'] ) && !empty( $_POST['agentfilter'] ) )
	{
		$agentfilter = htmlspecialchars( $_POST['agentfilter'] );
	}
	elseif( isset( $_GET['agentfilter'] ) && !empty( $_GET['agentfilter'] ) )
	{
		$agentfilter = htmlspecialchars( $_GET['agentfilter'] );
	}

	//check if agentfilter is set
	if( isset( $_POST['keywordfilter'] ) && !empty( $_POST['keywordfilter'] ) )
	{
		$keywordfilter = htmlspecialchars( $_POST['keywordfilter'] );
	}
	elseif( isset( $_GET['keywordfilter'] ) && !empty( $_GET['keywordfilter'] ) )
	{
		$keywordfilter = htmlspecialchars( $_GET['keywordfilter'] );
	}

	//check if filtertype is set
	if( isset( $_POST['filtertype'] ) && !empty( $_POST['filtertype'] ) )
	{
		$filtertype = htmlspecialchars( $_POST['filtertype'] );
	}
	elseif( isset( $_GET['filtertype'] ) && !empty( $_GET['filtertype'] ) )
	{
		$filtertype = htmlspecialchars( $_GET['filtertype'] );
	}

	//check if counterize_gotopage is set
	if( isset( $_POST['counterize_gotopage'] ) && !empty( $_POST['counterize_gotopage'] ) )
	{
		$counterize_gotopage = htmlspecialchars( $_POST['counterize_gotopage'] );
	}
	elseif( isset( $_GET['counterize_gotopage'] ) && !empty( $_GET['counterize_gotopage'] ) )
	{
		$counterize_gotopage = htmlspecialchars( $_GET['counterize_gotopage'] );
	}

	?>

	<div class="wrap" id="counterizehistorytop">

		<h2><?php _e( 'Filters', COUNTERIZE_TD ); ?></h2>

		<!-- Form for filters -->
		<form action="<?php echo $url; ?>" method="post" name="form_filter" id="form_filter">

			<fieldset>

				<legend><?php _e( 'Define one or more filters (you can separate entries with "||")', COUNTERIZE_TD ); ?></legend>

				<table summary="<?php _e( 'Filter fields', COUNTERIZE_TD ); ?>">
					<tr>
						<td>
							<label for="ipfilter"><?php _e( 'Filter for these IP addresses:', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="text" size="60" name="ipfilter" id="ipfilter"<?php echo ( isset( $ipfilter ) ) ? 'value="' . $ipfilter . '"' : ''; ?> />
						</td>
						<td>
							<input type="button" class="button-secondary" value="<?php _e( 'Clear', COUNTERIZE_TD ); ?>" onclick="javascript:clear_filter_form( Array( 'ipfilter' ) );" />
						</td>
					</tr>

					<tr>
						<td>
							<label for="countryfilter"><?php _e( 'Filter for these countries:', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="text" size="60" name="countryfilter" id="countryfilter"<?php echo ( isset( $countryfilter ) ) ? 'value="' . $countryfilter . '"' : ''; ?> />
						</td>
						<td>
							<input type="button" class="button-secondary" value="<?php _e( 'Clear', COUNTERIZE_TD ); ?>" onclick="javascript:clear_filter_form( Array( 'countryfilter' ) );" />
						</td>
					</tr>

					<tr>
						<td>
							<label for="urifilter"><?php _e( 'Filter for these URLs:', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="text" size="60" name="urifilter" id="urifilter"<?php echo ( isset( $urifilter ) ) ? 'value="' . $urifilter . '"' : ''; ?> />
						</td>
						<td>
							<input type="button" class="button-secondary" value="<?php _e( 'Clear', COUNTERIZE_TD ); ?>" onclick="javascript:clear_filter_form( Array( 'urifilter' ) );" />
						</td>
					</tr>

					<tr>
						<td>
							<label for="refererfilter"><?php _e( 'Filter for these referers:', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="text" size="60" name="refererfilter" id="refererfilter"<?php echo ( isset( $refererfilter ) ) ? 'value="' . $refererfilter . '"' : ''; ?> />
						</td>
						<td>
							<input type="button" class="button-secondary" value="<?php _e( 'Clear', COUNTERIZE_TD ); ?>" onclick="javascript:clear_filter_form( Array( 'refererfilter' ) );" />
						</td>
					</tr>

					<tr>
						<td>
							<label for="agentfilter"><?php _e( 'Filter for these user-agents:', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="text" size="60" name="agentfilter" id="agentfilter"<?php echo ( isset( $agentfilter ) ) ? 'value="' . $agentfilter . '"' : ''; ?> />
						</td>
						<td>
							<input type="button" class="button-secondary" value="<?php _e( 'Clear', COUNTERIZE_TD ); ?>" onclick="javascript:clear_filter_form( Array( 'agentfilter' ) );" />
						</td>
					</tr>

					<tr>
						<td>
							<label for="keywordfilter"><?php _e( 'Filter for these keywords', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="text" size="60" name="keywordfilter" id="keywordfilter"<?php echo ( isset( $keywordfilter ) ) ? 'value="' . $keywordfilter . '"' : ''; ?> />
						</td>
						<td>
							<input type="button" class="button-secondary" value="<?php _e( 'Clear', COUNTERIZE_TD ); ?>" onclick="javascript:clear_filter_form( Array( 'keywordfilter' ) );" />
						</td>
					</tr>

					<tr>
						<td>
							<label for="filterinclude"><?php _e( 'Include filter', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="radio" name="filtertype" id="filterinclude" value="in"<?php echo ( ( ! isset( $filtertype ) ) || ( isset( $filtertype ) && $filtertype == 'in' ) ) ? ' checked="checked"' : ''; ?> />
						</td>
					</tr>

					<tr>
						<td>
							<label for="filterexclude"><?php _e( 'Exclude filter', COUNTERIZE_TD ) ?></label>
						</td>
						<td>
							<input type="radio" name="filtertype" id="filterexclude" value="ex"<?php echo ( isset( $filtertype ) && $filtertype == 'ex' ) ? ' checked="checked"' : ''; ?> />
						</td>
					</tr>

				</table>

				<input type="hidden" name="counterize_hidden_check" id="counterize_hidden_check" value="present" />

				<?php wp_nonce_field( 'counterize_filter_data', 'counterize_filter_data_field' ); ?>

				<input type="submit" class="button-primary" name="counterize_filter_submit" id="counterize_filter_submit" value="<?php _e( 'Submit filter', COUNTERIZE_TD ); ?>" />
				<input type="button" class="button-primary" value="<?php _e( 'Clear form', COUNTERIZE_TD ); ?>" onclick="javascript:clear_filter_form( Array( 'ipfilter', 'urifilter', 'refererfilter', 'agentfilter', 'countryfilter' ) );" />
				<input type="reset" class="button-primary" value="<?php _e( 'Cancel changes', COUNTERIZE_TD ); ?>" />
				<a href="admin.php?page=<?php echo $frompage; ?>" class="button-secondary"><?php _e( 'Reset filters', COUNTERIZE_TD ); ?></a>

			</fieldset>

		</form>
		<br />

		<h2><?php echo $howmany; ?></h2>

		<?php

		$entries_tmp = counterize_getentries_sql( $amount );
		$entries = $wpdb->get_results( $entries_tmp[0] );
		$nbentries = $entries_tmp[1];
		$lastpage = $entries_tmp[2];

		//compute the current page number
		if( isset( $counterize_gotopage ) && is_numeric( $counterize_gotopage ) )
		{
			$currentpage = intval( $counterize_gotopage );
		}
		else
		{
			$currentpage = 1;
		}
		if( $currentpage < 1 )
		{
			$currentpage = 1;
		}
		elseif( $currentpage > $lastpage )
		{
			$currentpage = $lastpage;
		}

		//generate the navigation links
		$nav_link = wp_nonce_url( $url, 'action_nav_link' );
		$nav_link .= ( isset( $ipfilter      ) ? '&amp;ipfilter='      . htmlspecialchars( $ipfilter      ) : '' );
		$nav_link .= ( isset( $countryfilter ) ? '&amp;countryfilter=' . htmlspecialchars( $countryfilter ) : '' );
		$nav_link .= ( isset( $urifilter     ) ? '&amp;urifilter='     . htmlspecialchars( $urifilter     ) : '' );
		$nav_link .= ( isset( $refererfilter ) ? '&amp;refererfilter=' . htmlspecialchars( $refererfilter ) : '' );
		$nav_link .= ( isset( $agentfilter   ) ? '&amp;agentfilter='   . htmlspecialchars( $agentfilter   ) : '' );
		$nav_link .= ( isset( $keywordfilter ) ? '&amp;keywordfilter=' . htmlspecialchars( $keywordfilter ) : '' );
		$nav_link .= ( isset( $filtertype    ) ? '&amp;filtertype='    . htmlspecialchars( $filtertype    ) : '' );
		$nav_frst_link = $nav_link . '&amp;counterize_gotopage=1';
		$nav_prev_link = $nav_link . '&amp;counterize_gotopage=' . ( $currentpage - 1 );
		$nav_next_link = $nav_link . '&amp;counterize_gotopage=' . ( $currentpage + 1 );
		$nav_last_link = $nav_link . '&amp;counterize_gotopage=' . ( $lastpage );

		if( ! empty( $_POST ) && isset( $_POST['counterize_gotopage'] ) )
		{
			if( ! check_admin_referer( 'counterize_history_nav', 'counterize_history_nav_field' ) )
			{
			   echo "<p>" . __( 'Nonce not verified. What are you trying to do?', COUNTERIZE_TD ) . "</p>";
			   exit;
			}
		}

		?>

		<!-- Navigation bar -->
		<div id="counterize_history_navigationbar">
			<ul>
				<?php if( $currentpage > 1 ): ?>
				<li><a href="<?php echo $nav_frst_link; ?>" class="button-secondary"><?php _e( '&laquo;&nbsp;First page', COUNTERIZE_TD ); ?></a></li>
				<li><a href="<?php echo $nav_prev_link; ?>" class="button-secondary"><?php _e( '&lsaquo;&nbsp;Previous page', COUNTERIZE_TD ); ?></a></li>
				<?php endif; ?>
				<li>
					<form action="<?php echo $url; ?>" method="post" name="counterize_form_nav" id="counterize_form_nav">
						<label for="counterize_gotopage"><?php _e( 'Go to page:', COUNTERIZE_TD ); ?></label>
						<input type="text" id="counterize_gotopage" name="counterize_gotopage" size="2" value="<?php echo $currentpage; ?>" />
						<span>&nbsp;/&nbsp;<?php echo $lastpage; ?></span>
						<?php wp_nonce_field( 'counterize_history_nav', 'counterize_history_nav_field' ); ?>
						<input type="submit" value="<?php _e( 'OK', COUNTERIZE_TD ); ?>" class="button-secondary" />
					</form>
				</li>
				<?php if( $currentpage < $lastpage ): ?>
				<li><a href="<?php echo $nav_next_link; ?>" class="button-secondary"><?php _e( 'Next page&nbsp;&rsaquo;', COUNTERIZE_TD ); ?></a></li>
				<li><a href="<?php echo $nav_last_link; ?>" class="button-secondary"><?php _e( 'Last page&nbsp;&raquo;', COUNTERIZE_TD ); ?></a></li>
				<?php endif; ?>
			</ul>
		</div>

		<?php
			$killmass_url    = "{$url}&amp;killmass=yes";
			$killmass_link = wp_nonce_url( $killmass_url, "action_killmass" );
		?>

		<!-- History data begins here -->
		<form method="post" action="<?php echo $killmass_link; ?>" name="tablesForm" id="tablesForm">

			<table id="counterizehistorytable" width="100%" cellpadding="3" cellspacing="3" rules="rows" summary="<?php _e( 'History', COUNTERIZE_TD ); ?>">
				<thead>
					<tr class="alternate">
						<th style="width: 3%"><?php _e( 'Select',       COUNTERIZE_TD ); ?></th>
						<th style="width: 3%"><?php _e( 'ID',           COUNTERIZE_TD ); ?></th>
						<th style="width: 10%"><?php _e( 'IP',          COUNTERIZE_TD ); ?></th>
						<th style="width: 10%"><?php _e( 'Country',     COUNTERIZE_TD ); ?></th>
						<th style="width: 10%"><?php _e( 'Timestamps',  COUNTERIZE_TD ); ?></th>
						<th style="width: 20%"><?php _e( 'URL',         COUNTERIZE_TD ); ?></th>
						<th style="width: 20%"><?php _e( 'Referers',    COUNTERIZE_TD ); ?></th>
						<th style="width: 12%"><?php _e( 'User-agents', COUNTERIZE_TD ); ?></th>
						<th style="width: 10%"><?php _e( 'Keywords',    COUNTERIZE_TD ); ?></th>
						<th style="width: 2%"><?php _e( 'Kill',         COUNTERIZE_TD ); ?></th>
					</tr>
				</thead>
				<tfoot>
					<tr class="alternate">
						<th><?php _e( 'Select',      COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'ID',          COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'IP',          COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Country',     COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Timestamps',  COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'URL',         COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Referers',    COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'User-agents', COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Keywords',    COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Kill',        COUNTERIZE_TD ); ?></th>
					</tr>
				</tfoot>
				<tbody>

				<?php


		//$url = "admin.php?page={$frompage}";

		$uri_filter_link     = wp_nonce_url( $url, 'action_uri_filter'     );
		$ip_filter_link      = wp_nonce_url( $url, 'action_ip_filter'      );
		$country_filter_link = wp_nonce_url( $url, 'action_country_filter' );
		$referer_filter_link = wp_nonce_url( $url, 'action_referer_filter' );
		$agent_filter_link   = wp_nonce_url( $url, 'action_agent_filter'   );
		$keyword_filter_link = wp_nonce_url( $url, 'action_agent_keyword'  );
		$uri_kill_link       = wp_nonce_url( $url, 'action_uri_kill'       );

		if( ! empty( $_POST ) && isset( $_POST['counterize_hidden_check'] ) )
		{
			if( ! check_admin_referer( 'counterize_filter_data', 'counterize_filter_data_field' ) )
			{
			   echo '<p>' . __( 'Nonce not verified. What are you trying to do?', COUNTERIZE_TD ) . '</p>';
			   exit;
			}
		}



		$i = 0;
		$offset = 0;
		$entrycounter = 1;
		foreach( $entries as $entry )
		{
			if( $i % 25 == 0 && $i > 0 )
			{
				$offset++;
				?>

				</tbody>
				<tbody>
					<tr class="alternate repeat">
						<th><?php _e( 'Select',      COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'ID',          COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'IP',          COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Country',     COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Timestamps',  COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'URL',         COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Referers',    COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'User-agents', COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Keywords',    COUNTERIZE_TD ); ?></th>
						<th><?php _e( 'Kill',        COUNTERIZE_TD ); ?></th>
					</tr>

				<?php
			}


			?>

					<tr <?php if( ( $i + $offset ) % 2 ) { echo 'class="alternate"'; } ?>>
						<td style="text-align: center">
							<?php echo $entrycounter; $entrycounter++; ?>
							<small>
								<input type="checkbox"
								name='counterize_killemall[<?php echo $entry->id; ?>]'
								value="<?php echo $entry->id; ?>" />
							</small>
						</td>

						<td style="text-align: center">
							<small>
								<?php echo $entry->id; ?>
							</small>
						</td>


						<td style="text-align: center">
							<small>
								<?php
								printf( "<a href='%s&amp;ipfilter=%s' onclick='javascript:add_filter( \"%s\", \"ipfilter\" ); return false;' title='%s' class='button-secondary'>F</a>
								", $ip_filter_link, $entry->IP, $entry->IP, __( 'Add a filter for this IP address', COUNTERIZE_TD ) );

								printf( '<a target="_blank" href="%s%s" title="%s" class="button-secondary">G</a>
								', counterize_get_option( 'geoip' ), $entry->IP, __( 'Geo IP tool service', COUNTERIZE_TD ) );

								printf( ' <a target="_blank" href="%s%s" title="%s">&#x202A;%s&#x202C;</a>
								', counterize_get_option( 'whois' ), $entry->IP, __( 'Whois service for this IP address', COUNTERIZE_TD ), $entry->IP );
								?>

							</small>
						</td>

						<td style="text-align: center">
							<small>
								<a href="<?php echo $country_filter_link . "&amp;countryfilter=" . htmlspecialchars( $entry->countrycode ); ?>" onclick="javascript:add_filter( '<?php echo htmlspecialchars( $entry->countrycode ); ?>', 'countryfilter' ); return false;" title="<?php _e( 'Add a filter for this country', COUNTERIZE_TD ); ?>" class="button-secondary">F</a>
								 <span><?php echo counterize_get_countrycode3( $entry->countrycode ); ?></span>
								<?php
									if( file_exists( "{$counterize_plugin_dir}/ip_files/flags/{$entry->countrycode}.gif" ) )
									{
										echo "&nbsp;<img src='{$counterize_plugin_url}/ip_files/flags/{$entry->countrycode}.gif' title='" . counterize_get_countryname( $entry->countrycode ) . " ({$entry->countrycode})' alt='" . sprintf( __( 'National flag of %s', COUNTERIZE_TD ), counterize_get_countryname( $entry->countrycode ) ) . "' />";
									}
									elseif( file_exists( "{$counterize_plugin_dir}/ip_files/flags/" . strtolower( $entry->countrycode ) . ".gif" ) )
									{
										//sometimes some tools such as unzip modify the filenames to be lowercase (happened to me)
										echo "&nbsp;<img src='{$counterize_plugin_url}/ip_files/flags/" . strtolower( $entry->countrycode ) . ".gif' title='" . counterize_get_countryname( $entry->countrycode ) . " ({$entry->countrycode})' alt='" . sprintf( __( 'National flag of %s', COUNTERIZE_TD ), counterize_get_countryname( $entry->countrycode ) ) . "' />";
									}
								?>
							</small>
						</td>

						<td style="text-align: center">
							<small><?php echo $entry->timestamp; ?> </small>
						</td>

						<td>
							<small>
								<a href="<?php echo $uri_filter_link . "&amp;urifilter=" . htmlspecialchars( $entry->url ); ?>" onclick="javascript:add_filter( '<?php echo htmlspecialchars( $entry->url ); ?>', 'urifilter' ); return false;" title="<?php _e( 'Add a filter for this URL', COUNTERIZE_TD ); ?>" class="button-secondary">F</a>
								 <?php echo '<a href="' . htmlspecialchars( $entry->url ) . '" target="_blank">&#x202A;' . htmlspecialchars( counterize_wordwrap( $entry->url ) ); ?>&#x202C;</a>
							</small>
						</td>

						<td>
							<small>
							<?php
							if( $entry->referer != "unknown" )
							{
								?><a href="<?php echo $referer_filter_link . "&amp;refererfilter=" . htmlspecialchars( $entry->referer ); ?>" onclick="javascript:add_filter( '<?php echo htmlspecialchars( $entry->referer ); ?>', 'refererfilter' ); return false;" title="<?php _e( 'Add a filter for this referer', COUNTERIZE_TD ); ?>" class="button-secondary">F</a>
								<?php
								echo ' <a href="' . htmlspecialchars( $entry->referer ) . '" target="_blank">&#x202A;' . htmlspecialchars( counterize_wordwrap( $entry->referer ) ) . '&#x202C;</a>';
								?>
								<?php
							}
							else
							{
								?><a href="<?php echo $referer_filter_link . "&amp;refererfilter=" . htmlspecialchars( $entry->referer ); ?>" onclick="javascript:add_filter( '<?php echo htmlspecialchars( $entry->referer ); ?>', 'refererfilter' ); return false;" title="<?php _e( 'Add a filter for this referer', COUNTERIZE_TD ); ?>" class="button-secondary">F</a>
								 <?php
								echo htmlspecialchars( counterize_wordwrap( $entry->referer ) );
							}
							?>
							</small>
						</td>

						<td>
							<small>
								<span title="<?php echo htmlspecialchars( $entry->useragent ); ?>"><?php echo counterize_browser_string( $entry->useragent , true, '<br />' ); ?></span>
								 <a href="<?php echo $agent_filter_link . '&amp;agentfilter=' . htmlspecialchars( urlencode( $entry->useragent ) ); ?>" onclick="javascript:add_filter( '<?php echo htmlspecialchars( $entry->useragent ); ?>', 'agentfilter' ); return false;" title="<?php _e( 'Add a filter for this user-agent', COUNTERIZE_TD ); ?>" class="button-secondary">F</a>
							</small>
						</td>

						<td style="text-align: left">
							<small>
								<?php if( ! empty( $entry->keyword ) ): ?>
								<a href="<?php echo $keyword_filter_link . '&amp;keywordfilter=' . htmlspecialchars( $entry->keyword ); ?>" onclick="javascript:add_filter( '<?php echo htmlspecialchars( $entry->keyword ); ?>', 'keywordfilter' ); return false;" title="<?php _e( 'Add a filter for this keyword', COUNTERIZE_TD ); ?>" class="button-secondary">F</a>
								<?php endif; ?>
								<?php echo ( empty( $entry->keyword ) ? "&nbsp;" : counterize_wordwrap( htmlspecialchars( $entry->keyword ) ) ) ; ?>
							</small>
						</td>

						<td style="text-align: center">
							<a href="javascript:counterize_conf( '<?php echo $uri_kill_link . "&amp;kill={$entry->id}"; ?>' );" class="button-secondary counterize_history_killbutton" title="<?php _e( 'Click here to delete this entry', COUNTERIZE_TD ); ?>">X</a>
						</td>
					</tr>
			<?php
			$i++;
		}
		unset( $entries );
		?>
				</tbody>
			</table>

			<input
				type="button"
				class="button-primary"
				name="counterize_checkAll"
				value="<?php _e( 'Check All', COUNTERIZE_TD ); ?>"
				onclick="javascript:counterize_check_all( document.tablesForm );" />
			<input
				type="button"
				class="button-primary"
				name="counterize_uncheckAll"
				value="<?php _e( 'Uncheck All', COUNTERIZE_TD ); ?>"
				onclick="javascript:counterize_uncheck_all( document.tablesForm );" />
			<input
				type="submit"
				class="button-primary"
				value="<?php _e( 'Delete selected Entries', COUNTERIZE_TD ); ?>" />
		</form>

		<div id="counterize_history_navigationbar2">
			<ul>
				<?php if( $currentpage > 1 ): ?>
				<li><a href="<?php echo $nav_frst_link; ?>" class="button-secondary"><?php _e( '&laquo;&nbsp;First page', COUNTERIZE_TD ); ?></a></li>
				<li><a href="<?php echo $nav_prev_link; ?>" class="button-secondary"><?php _e( '&lsaquo;&nbsp;Previous page', COUNTERIZE_TD ); ?></a></li>
				<?php endif; ?>
				<li><a href="#counterizehistorytop" class="button-secondary"><?php _e( '&uarr;&nbsp;Top of the page&nbsp;&uarr;', COUNTERIZE_TD ) ?></a></li>
				<?php if( $currentpage < $lastpage ): ?>
				<li><a href="<?php echo $nav_next_link; ?>" class="button-secondary"><?php _e( 'Next page&nbsp;&rsaquo;', COUNTERIZE_TD ); ?></a></li>
				<li><a href="<?php echo $nav_last_link; ?>" class="button-secondary"><?php _e( 'Last page&nbsp;&raquo;', COUNTERIZE_TD ); ?></a></li>
				<?php endif; ?>
			</ul>
		</div>

	</div>

<?php

}

function counterize_updateText( $text = '', $color='red' )
{
	if( $text == '' )
	{
		$text = __( 'Configuration updated', COUNTERIZE_TD );
	}
	echo "<div id=\"message\" class=\"updated fade\"><p><font color=\"{$color}\">";
	echo $text;
	echo "</font></p></div>";
}


function counterize_show_data_traffic( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- Traffic -->
	<div class="wrap">

		<h2><?php _e( 'Hit Counter', COUNTERIZE_TD );?></h2>

		<?php counterize_get_hits(); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_daily_stats( false ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_daily_stats( true ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_weekly_stats(); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_weekly_stats( true ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_week_progression_stats( true ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_monthly_stats(); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_monthly_stats( true ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_hourly_stats(); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_hourly_stats( true ); ?>

	</div>

	<?php
}

function counterize_show_data_pages( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- Popular posts -->
	<div class="wrap">

		<?php counterize_render_most_popular_posts( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_popular_posts24hrs( $amount2, $width ); ?>

	</div>

	<!-- Urls -->
	<div class="wrap">

		<?php counterize_render_most_requested_urls( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_requested_urls24hrs( $amount2, $width ); ?>

	</div>

	<?php
}

function counterize_show_data_ip( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- IPs -->
	<div class="wrap">

		<?php counterize_render_most_active_ips( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_active_ips24hrs( $amount2, $width ); ?>

	</div>

	<?php
}

function counterize_show_data_countries( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- Countries -->
	<div class="wrap">

		<?php counterize_render_most_visiting_countries( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_visiting_countries24hrs( $amount2, $width ); ?>

	</div>

	<?php
}

function counterize_show_data_referers( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data. ", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- Referers -->
	<div class="wrap">

		<?php counterize_render_most_seen_referers( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_seen_referers24hrs( $amount2, $width ); ?>

	</div>

	<?php
}

function counterize_show_data_browsers( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- Browsers -->
	<div class="wrap">

		<?php counterize_render_most_used_browsers_collapsible( $amount2, $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_used_browsers_without_version( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_used_browsers( $amount2, $width ); ?>

	</div>

	<?php
}

function counterize_show_data_os( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- OS -->
	<div class="wrap">

		<?php counterize_render_most_used_os_collapsible( $amount2, $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_used_os_without_version( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_used_os( $amount2, $width ); ?>

	</div>

	<?php
}

function counterize_show_data_keywords( $admin = false, $width = 250, $amount2 = 10, $directcall = true )
{
	if( $directcall )
	{
		if( ! counterize_getamount() )
		{
			_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
			return;
		}
	}
	?>

	<!-- Keywords -->
	<div class="wrap">

		<?php counterize_render_most_searched_keywords( $amount2, $width ); ?>

	</div>

	<div class="wrap">

		<?php counterize_render_most_searched_keywords24hrs( $amount2, $width ); ?>

	</div>

	<?php
}

//display all the statistics
function counterize_showStats( $admin = false )
{
	if( ! counterize_getamount() )
	{
		_e( "There's no data in the database - You can't see stats until you have data.", COUNTERIZE_TD );
		return;
	}

	// Amount to pass as option to the graphs...
	$amount2 = counterize_get_option( 'amount2' );
	if( $amount2 == '' || $amount2 == ' ' || !is_numeric( $amount2 ) )
	{
		$amount2 = 10;
	}
	$width = 250;

	counterize_show_data_traffic(   $admin, $width, $amount2, false );
	counterize_show_data_pages(     $admin, $width, $amount2, false );
	counterize_show_data_ip(        $admin, $width, $amount2, false );
	counterize_show_data_countries( $admin, $width, $amount2, false );
	counterize_show_data_referers(  $admin, $width, $amount2, false );
	counterize_show_data_browsers(  $admin, $width, $amount2, false );
	counterize_show_data_os(        $admin, $width, $amount2, false );
	counterize_show_data_keywords(  $admin, $width, $amount2, false );
}

//Call the proper function depending of the $pattern
function counterize_check_data( $data, $pattern, $function, $argc=0 )
{
	if( is_callable( $function ) && is_numeric( $argc ) )
	{
		while( preg_match( $pattern, $data, $matches ) )
		{
			ob_start();

			$correct = true;
			if( $argc == 1 && isset( $matches[2] ) )
			{
				if( is_numeric( $matches[2] ) )
				{
					$ret = call_user_func( $function, $matches[2] );
				}
				else
				{
					$correct = false;
				}
			}
			elseif( $argc == 2 && isset( $matches[2] ) && isset( $matches[3] ) )
			{
				if( is_numeric( $matches[2] ) && is_numeric( $matches[3] ) )
				{
					$ret = call_user_func( $function, $matches[2], $matches[3] );
				}
				else
				{
					$correct = false;
				}
			}
			else
			{
				$ret = call_user_func( $function );
			}

			if( $correct )
			{
				$content = ob_get_contents();
				ob_end_clean();
				$replace_pattern = $pattern;
				$data = preg_replace( $replace_pattern, $content, $data );
			}
		}
	}
	return $data;
}


//Allow the authors to integrate charts into their posts using the following syntax (in HTML mode):
// <!-- keyword -->
function counterize_filter_callback( $data )
{
	//search if the post has the magic word
	$pattern = '/(\<\!\-|\#)\-\s*counterize_stats/';

	if( preg_match( $pattern, $data ) )
	{
		//we probably want to add some statistics. Lets verify:

		//<!-- counterize_stats --> : Shows all the stats
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats\s*\-(\-\>|\#)/'                              , 'counterize_showStats'                         , 0 );

		//<!-- counterize_stats_hits --> : Shows a table containing statistics about hits
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_hits\s*\-(\-\>|\#)/'                         , 'counterize_get_hits'                          , 0 );

		//<!-- counterize_stats_browsers_nb --> : Shows a list of the nb most used browsers (with their version)
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_browsers_([0-9]+)\s*\-(\-\>|\#)/'            , 'counterize_render_most_used_browsers'         , 1 );

		//<!-- counterize_stats_browsers_nover_nb --> : Shows a list of the nb most used browsers (without their version)
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_browsers_nover_([0-9]+)\s*\-(\-\>|\#)/'      , 'counterize_render_most_used_browsers_without_version', 1 );

		//<!-- counterize_stats_browsers_mixed_nb1_nb2 --> : Shows a list of the nb1 most used browsers (clicking each entry will show the version details)
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_browsers_mixed_([0-9]+)_([0-9]+)\s*\-(\-\>|\#)/', 'counterize_render_most_used_browsers_collapsible', 2);

		//<!-- counterize_stats_os_nb --> : Shows a list of the nb most used operating systems (with their version)
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_os_([0-9]+)\s*\-(\-\>|\#)/'                  , 'counterize_render_most_used_os'               , 1 );

		//<!-- counterize_stats_os_nover_nb --> : Shows a list of the nb most used operating systems (without their version)
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_os_nover_([0-9]+)\s*\-(\-\>|\#)/'            , 'counterize_render_most_used_os_without_version'    , 1 );

		//<!-- counterize_stats_os_mixed_nb1_nb2 --> : Shows a list of the nb1 most used operating systems (clicking each entry will show the version details)
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_os_mixed_([0-9]+)_([0-9]+)\s*\-(\-\>|\#)/'   , 'counterize_render_most_used_os_collapsible'   , 2);

		//<!-- counterize_stats_ip_nb --> : Shows a list of the nb most active ips
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_ip_([0-9]+)\s*\-(\-\>|\#)/'                  , 'counterize_render_most_active_ips'            , 1 );

		//<!-- counterize_stats_ip_24hrs_nb --> : Shows a list of the nb most active ips during the last 24 hours
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_ip_24hrs_([0-9]+)\s*\-(\-\>|\#)/'            , 'counterize_render_most_active_ips24hrs'       , 1 );

		//<!-- counterize_stats_countries_nb --> : Shows a list of the nb most visiting countries
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_countries_([0-9]+)\s*\-(\-\>|\#)/'           , 'counterize_render_most_visiting_countries'    , 1 );

		//<!-- counterize_stats_countries_24hrs_nb --> : Shows a list of the nb most visiting countries during the last 24 hours
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_countries_24hrs_([0-9]+)\s*\-(\-\>|\#)/'     , 'counterize_render_most_visiting_countries24hrs', 1 );

		//<!-- counterize_stats_urls_nb --> : Shows a list of the nb most requested URLs
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_urls_([0-9]+)\s*\-(\-\>|\#)/'                , 'counterize_render_most_requested_urls'        , 1 );

		//<!-- counterize_stats_urls_24hrs_nb --> : Shows a list of the nb most requested URLs during the last 24 hours
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_urls_24hrs_([0-9]+)\s*\-(\-\>|\#)/'          , 'counterize_render_most_requested_urls24hrs'   , 1 );

		//<!-- counterize_stats_posts_nb --> : Shows a list of the nb most popular posts/pages
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_posts_([0-9]+)\s*\-(\-\>|\#)/'               , 'counterize_render_most_popular_posts'         , 1 );

		//<!-- counterize_stats_posts_24hrs_nb --> : Shows a list of the nb most popular posts/pages during the last 24 hours
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_posts_24hrs_([0-9]+)\s*\-(\-\>|\#)/'         , 'counterize_render_most_popular_posts24hrs'    , 1 );

		//<!-- counterize_stats_referers_nb --> : Shows a list of the nb most seen referers
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_referers_([0-9]+)\s*\-(\-\>|\#)/'            , 'counterize_render_most_seen_referers'         , 1 );

		//<!-- counterize_stats_referers_24hrs_nb --> : Shows a list of the nb most seen referers during the last 24 hours
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_referers_24hrs_([0-9]+)\s*\-(\-\>|\#)/'      , 'counterize_render_most_seen_referers24hrs'    , 1 );

		//<!-- counterize_stats_keywords_nb --> : Shows a list of the nb most searched keywords
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_keywords_([0-9]+)\s*\-(\-\>|\#)/'            , 'counterize_render_most_searched_keywords'     , 1 );

		//<!-- counterize_stats_keywords_today_nb --> : Shows a list of the nb most searched keywords today
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_keywords_today_([0-9]+)\s*\-(\-\>|\#)/'      , 'counterize_render_most_searched_keywords24hrs', 1 );

		//<!-- counterize_stats_copyright --> : Shows a small copyright notice
		$data = counterize_check_data( $data, '/(\<\!\-|\#)\-\s*counterize_stats_copyright\s*\-(\-\>|\#)/'                    , 'counterize_copyright'                         , 0);

	}

	return $data;
}

function counterize_pagefooter()
{
	?>
	<div class="wrap counterizefooter">
		<p>
			<?php _e( '<strong>Need help? </strong>Go to <a href="http://www.gabsoftware.com/products/scripts/counterize/" target="_blank">the Counterize homepage</a> and search inside the comments. Someone may have had the same question or problem as you...', COUNTERIZE_TD ); ?>
		</p>
		<p>
			<?php _e( 'Alternatively, you can also post your questions, suggestions and report problems in <a href="http://forum.gabsoftware.com/" target="_blank">our forum</a>.', COUNTERIZE_TD ); ?>
		</p>
	</div>
	<?php
}








//Executed when WordPress is loaded but before any header is sent.
//Inside we register our javascript and stylesheet files.
function counterize_init_callback()
{
	global $counterize_plugin_url;
	global $counterize_plugin_dir;
	global $counterize_dashboard_capability;

	if( function_exists( 'load_plugin_textdomain' ) )
	{
		load_plugin_textdomain( COUNTERIZE_TD, false, dirname( plugin_basename( __FILE__ ) ) );
	}

	wp_register_script( 'counterize_javascript', $counterize_plugin_url . '/counterize.js.php', __FILE__);
	wp_register_style( 'counterize_stylesheet', $counterize_plugin_url . '/counterize.css.php', __FILE__);

	add_action( 'wp_print_scripts', 'counterize_javascript_head_callback' );
	add_action( 'wp_print_styles', 'counterize_stylesheet_head_callback' );




	//Do the administrative stuff only if we are in the administration area
	if( is_admin() )
	{
		//require_once( ABSPATH . 'wp-includes/pluggable.php' );
		if( current_user_can( 'manage_options' ) )
		{
			//include admin-related files
			require_once( "counterize_admin.php" );
			require_once( "counterize_dashboard.php" );

			//check if we need to install Counterize
			counterize_should_install();

			//Add admin actions
			add_action( 'admin_init', 'counterize_admin_init_callback' );
			add_action( 'admin_menu', 'counterize_add_pages_admin_callback' );
		}
		else
		{
			//Non admin pages
			$capability = counterize_get_option( 'display_dashboard_capability' );
			if( $capability === FALSE )
			{
				$capability = 'manage_options';
				counterize_set_option( 'display_dashboard_capability', $capability );
			}

			if( current_user_can( $capability ) )
			{
				$counterize_dashboard_capability = $capability;
				require_once( "counterize_dashboard.php" );
				add_action( 'admin_menu', 'counterize_add_pages_callback' );
			}
		}
	}
}


//Add the Counterize widget into the dashboard
function counterize_add_dashboard_widget_callback()
{
	wp_add_dashboard_widget( 'dashboard_counterize', __( 'Counterize Status', COUNTERIZE_TD ), 'counterize_dashboard_callback' );
}

//Add the Counterize javascript file to the <head> section
function counterize_javascript_head_callback()
{
	wp_enqueue_script( 'counterize_javascript' );
}

//Add the Counterize stylesheet file to the <head> section
function counterize_stylesheet_head_callback()
{
	wp_enqueue_style( 'counterize_stylesheet' );
}

//add a Configure link in the plugins page
function counterize_filter_plugin_actions_callback( $links, $file )
{
	$settings_link = '<a href="options-general.php?page=counterize_options_page_id">' . __( 'Configure', COUNTERIZE_TD ) . '</a>';
	array_unshift( $links, $settings_link ); // add the configure link before other links
	return $links;
}

function counterize_add_dashboard( $capability )
{
	global $counterize_plugin_url;
	global $menu;

	//tries to detect an available menu position. Usually at position 3 (right after the Dashboard menu)
	//there is an opening, but if not, it will find the next available position.
	$counterize_menu_position = 0;
	for( $i=2; $i< 99; $i++ )
	{
		if( ! isset( $menu[$i] ) )
		{
			$counterize_menu_position = $i;
			break;
		}
	}

	$counterize_dashboard_handles['dashboard'] = add_menu_page( __( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ), __( 'Counterize', COUNTERIZE_TD )                                                                                    , $capability, 'counterize_dashboard'           , 'counterize_display_dashboard_page_callback', $counterize_plugin_url . '/bar_chart_20x20.png', $counterize_menu_position );
	$counterize_dashboard_handles['traffic']   = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'Traffic', COUNTERIZE_TD )          , __( 'Traffic', COUNTERIZE_TD )          , $capability, 'counterize_dashboard_traffic'   , 'counterize_display_dashboard_traffic_page_callback' );
	$counterize_dashboard_handles['pages']     = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'Popular pages', COUNTERIZE_TD )    , __( 'Popular pages', COUNTERIZE_TD )    , $capability, 'counterize_dashboard_pages'     , 'counterize_display_dashboard_pages_page_callback' );
	$counterize_dashboard_handles['ip']        = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'IP addresses', COUNTERIZE_TD )     , __( 'IP addresses', COUNTERIZE_TD )     , $capability, 'counterize_dashboard_ip'        , 'counterize_display_dashboard_ip_page_callback' );
	$counterize_dashboard_handles['countries'] = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'Countries', COUNTERIZE_TD )        , __( 'Countries', COUNTERIZE_TD )        , $capability, 'counterize_dashboard_countries' , 'counterize_display_dashboard_countries_page_callback' );
	$counterize_dashboard_handles['referers']  = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'Referers', COUNTERIZE_TD )         , __( 'Referers', COUNTERIZE_TD )         , $capability, 'counterize_dashboard_referers'  , 'counterize_display_dashboard_referers_page_callback' );
	$counterize_dashboard_handles['browsers']  = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'Browsers', COUNTERIZE_TD )         , __( 'Browsers', COUNTERIZE_TD )         , $capability, 'counterize_dashboard_browsers'  , 'counterize_display_dashboard_browsers_page_callback' );
	$counterize_dashboard_handles['os']        = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'Operating systems', COUNTERIZE_TD ), __( 'Operating systems', COUNTERIZE_TD ), $capability, 'counterize_dashboard_os'        , 'counterize_display_dashboard_os_page_callback' );
	$counterize_dashboard_handles['keywords']  = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'Keywords', COUNTERIZE_TD )         , __( 'Keywords', COUNTERIZE_TD )         , $capability, 'counterize_dashboard_keywords'  , 'counterize_display_dashboard_keywords_page_callback' );
	if( current_user_can( 'manage_options' ) )
	{
		$counterize_dashboard_handles['history']   = add_submenu_page( 'counterize_dashboard',__( 'Counterize', COUNTERIZE_TD ) . ' - ' . __( 'Dashboard', COUNTERIZE_TD ) . ' - ' . __( 'History', COUNTERIZE_TD )          , __( 'History', COUNTERIZE_TD )          , $capability, 'counterize_dashboard_history' , 'counterize_display_dashboard_history_page_callback' );
	}

	//print_r( $GLOBALS['menu']);

	add_action( "admin_print_scripts-{$counterize_dashboard_handles['dashboard']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['dashboard']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['traffic']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['traffic']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['pages']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['pages']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['ip']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['ip']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['countries']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['countries']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['referers']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['referers']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['browsers']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['browsers']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['os']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['os']}" , 'counterize_stylesheet_head_callback' );
	add_action( "admin_print_scripts-{$counterize_dashboard_handles['keywords']}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_dashboard_handles['keywords']}" , 'counterize_stylesheet_head_callback' );

	if( current_user_can( 'manage_options' ) )
	{
		add_action( "admin_print_scripts-{$counterize_dashboard_handles['history']}", 'counterize_javascript_head_callback' );
		add_action( "admin_print_styles-{$counterize_dashboard_handles['history']}" , 'counterize_stylesheet_head_callback' );
	}

	return $counterize_dashboard_handles;
}

//Add options menus an pages for administrators
function counterize_add_pages_admin_callback()
{
	//specify that we want to add a dashboard widget
	add_action( 'wp_dashboard_setup', 'counterize_add_dashboard_widget_callback' );

	//add the Counterize dashboard to the Dashboard section
	$counterize_dashboard_handles = counterize_add_dashboard( 'manage_options' );

	//add the Counterize options page
	$counterize_options_page_handle = add_options_page( __( 'Counterize Options', COUNTERIZE_TD ), __( 'Counterize', COUNTERIZE_TD ), 'manage_options', "counterize_options_page_id", 'counterize_options_page_callback' );

	//specify that we want to add the javascript code only for the Counterize options pages
	add_action( "admin_print_scripts-{$counterize_options_page_handle}", 'counterize_javascript_head_callback' );
	add_action( "admin_print_styles-{$counterize_options_page_handle}", 'counterize_stylesheet_head_callback' );

	//specify that we want to alter the links in the plugins page
	add_filter( 'plugin_action_links_' . plugin_basename( __FILE__), 'counterize_filter_plugin_actions_callback', 10, 2 );
}

function counterize_add_pages_callback()
{
	global $counterize_dashboard_capability;

	//specify that we want to add a dashboard widget
	add_action( 'wp_dashboard_setup', 'counterize_add_dashboard_widget_callback' );

	$counterize_dashboard_handles = counterize_add_dashboard( $counterize_dashboard_capability );
}


//check is Counterize should be installed or upgraded
function counterize_should_install()
{
	$MajorVersion = get_option( 'counterize_MajorVersion' );
	if( $MajorVersion === FALSE )
	{
		$MajorVersion = counterize_get_version( 'major' );
		$MinorVersion = counterize_get_version( 'minor' );
		$Revision     = counterize_get_version( 'revision' );
	}
	else
	{
		$MajorVersion = get_option( 'counterize_MajorVersion', 1 );
		$MinorVersion = get_option( 'counterize_MinorVersion', 0 );
		$Revision     = get_option( 'counterize_Revision'    , 0 );
	}

	global $counterize_MajorVersion;
	global $counterize_MinorVersion;
	global $counterize_Revision;

	if( $MajorVersion != $counterize_MajorVersion || $MinorVersion != $counterize_MinorVersion || $Revision != $counterize_Revision )
	{
		require_once( 'counterize_install.php' );
		counterize_install( $counterize_MajorVersion, $counterize_MinorVersion, $counterize_Revision );
	}
}

add_action( 'init', 'counterize_init_callback' );

// Create API hook instead of placing code in the header.php-file
add_action( 'wp_head', 'counterize_add_callback', 1 );
add_filter( 'the_content', 'counterize_filter_callback' );

?>
