<?php
/*
Plugin Name: WassUp
Plugin URI: http://www.wpwp.org
Description: Wordpress plugin to analyze your visitors traffic with real time stats, chart and a lot of chronological informations. It has sidebar Widget support to show current online visitors and other statistics.
Version: 1.4.5-wp2.2
Author: Michele Marcucci
Author URI: http://www.michelem.org/

Copyright (c) 2007 Michele Marcucci
Released under the GNU General Public License (GPL)
http://www.gnu.org/licenses/gpl.txt
*/

//# Stop any attempt to call wassup.php directly.  -Helene D. 1/27/08.
if (preg_match('#'.basename(__FILE__) .'#', $_SERVER['PHP_SELF'])) { 
	die('Permission Denied! You are not allowed to call this page directly.');
}
$version = "1.4.5-wp2.2";
define('WASSUPFOLDER', dirname(plugin_basename(__FILE__)), TRUE);
require_once(dirname(__FILE__).'/lib/main.php');
$wpurl = get_bloginfo('wpurl');

if (isset($_GET['export'])) {
	export_wassup();
}

function wassup_activation_error() {
	echo '<p><strong>' . __("Sorry, Wassup requires WordPress 2.3 or higher to work.","wassup") . '</strong></p>';
}

global $wp_version;
//#This works only in WP2.2 or higher
if (version_compare($wp_version, '2.2', '<')) {
	add_action('admin_notices', wassup_activation_error());
	exit(1);
} else {
	register_activation_hook( __FILE__, 'wassup_install' );
	add_action('admin_head', 'add_wassup_css');
	add_action('init', 'add_wassup_scripts');
	add_action('wp_head', 'add_wassup_meta_info');
	add_action("widgets_init", "wassup_widget_init");
	add_action('admin_menu', 'wassup_add_pages');
	add_action('send_headers', 'wassupAppend');
}

//#initial wassup settings for options this is here because
//I need it in more then one function (using global)
$defaultWdata = array(
	'wassup_active' => "1",
	'wassup_loggedin' => "1",
	'wassup_spider' => "1",
	'wassup_attack' => "1",
	'wassup_spamcheck' => "1",
        'wassup_spam' => "1",
        'wassup_refspam' => "1",
	'wassup_exclude' => "",
	'wassup_savepath' => null,
	'wassup_wchart' => "1",
	'delete_auto' => "never",
        'delete_auto_size' => "0",
	'wassup_remind_mb' => "0",
	'wassup_remind_flag' => "0",
	'wassup_refresh' => "3",
	'wassup_userlevel' => "8",
	'wassup_screen_res' => "800",
	'wassup_default_type' => "everything",
	'wassup_default_limit' => "10",
	'wassup_widget_title' => "Visitors Online",
	'wassup_widget_ulclass' => "links",
	'wassup_widget_loggedin' => "1",
	'wassup_widget_comauth' => "1",
	'wassup_widget_search' => "1",
	'wassup_widget_searchlimit' => "5",
	'wassup_widget_ref' => "1",
	'wassup_widget_reflimit' => "5",
	'wassup_widget_topbr' => "1",
	'wassup_widget_topbrlimit' => "5",
	'wassup_widget_topos' => "1",
	'wassup_widget_toposlimit' => "5",
	'wassup_widget_chars' => "18"
	);

//#add initial options and create table when Wassup activated
function wassup_install() {
  global $wpdb, $defaultWdata;
  //### add/update wassup settings to Wordpress options table
  $wassup_settings = get_option('wassup_settings');
  if (empty($wassup_settings)) {
   	//# initialize wassup settings to default values
	add_option('wassup_settings', $defaultWdata, 'Options for WassUp');
  } else {
   	//# update wassup settings for 'spamcheck', 'refspam', and 'spam'
   	if (!isset($wassup_settings['wassup_spamcheck'])) {
	   $wassup_settings['wassup_spamcheck'] = "1";
   	   //#set wassup_spamcheck=0 if wassup_refspam=0 and wassup_spam=0
   	   if (!isset($wassup_settings['wassup_spam']) && !isset($wassup_settings['wassup_refspam'])) {
   	   	$wassup_settings['wassup_spam'] = "1";
		$wassup_settings['wassup_refspam'] = "1";
	   } elseif ( $wassup_settings['wassup_spam'] == "0" && $wassup_settings['wassup_refspam'] == "0" ) { 
  	   	$wassup_settings['wassup_spamcheck'] = "0";
  	   }
  	}
	//# update wassup settings for 'savepath' (default is null)
   	if (!isset($wassup_settings['wassup_savepath'])) {
  		$wassup_settings['wassup_savepath'] = null;
  		//$wassup_settings['wassup_savepath'] = "/tmp"; #debug
	}
	//#save wassup settings changes
  	update_option('wassup_settings', $wassup_settings);
  }

  //### create/upgrade wassup table
  $table_name = $wpdb->prefix . "wassup";
  if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
  	CreateTable();
  } else {
  	UpdateTable();
  }
} //#end function wassup_install

$wassup_settings = get_option('wassup_settings');

function add_wassup_meta_info() {
	global $version;
	print '<meta name="wassup-version" content="'.$version.'" />';
}

//Add jquery AJAX library and dependent scripts for all Wassup admin menus...
function add_wassup_scripts() {
	global $wpurl;
	if (stristr($_GET['page'],WASSUPFOLDER) !== FALSE) {
	if ( function_exists('wp_deregister_script')) {
		wp_deregister_script('jquery');	//removes old jquery vers.
	}
	// the safe way to load jquery into WP...
	wp_register_script('jquery', $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/js/jquery.js',FALSE,'1.2.2');
	if ($_GET['page'] == "wassup-spy") {
		//the safe way to load a jquery dependent script into WP...
		wp_enqueue_script('spy', $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/js/spy.js', array('jquery'), '1.4');
	} elseif($_GET['page'] == "wassup-options") {
		wp_enqueue_script('ui.tabs', $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/js/ui.tabs.js', array('jquery'), '3');
	} else {
		//the safe way to load a jquery dependent script into WP...
		wp_enqueue_script('thickbox', $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/thickbox/thickbox.js', array('jquery'), '3');
	} 
	}
}

//Add the wassup stylesheet and other javascripts...
function add_wassup_css() {
	global $wpurl;
	$hash = wp_hash('wassup');
	$plugin_page = attribute_escape($_GET['page']);
	if (stristr($plugin_page,'wassup') !== FALSE) { $plugin_page="wassup"; }
	//Add css and javascript to wassup menu pages only...
	if ($plugin_page == "wassup") {
		$wassup_settings = get_option('wassup_settings');
		//$siteurl =  get_bloginfo('siteurl');	//not used
		//$wpurl =  get_bloginfo('wpurl');	//global

echo '<link rel="stylesheet" href="'.$wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/wassup.css'.'" type="text/css" />';
echo '<link rel="stylesheet" href="'.$wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/thickbox/thickbox.css'.'" type="text/css" />';
echo '<link rel="stylesheet" href="'.$wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/ui.tabs.css'.'" type="text/css" />';

if ($_GET['page'] != "wassup-options" AND $_GET['page'] != "wassup-spy") { ?>
<script type='text/javascript'>
  //<![CDATA[
  function selfRefresh(){
 	location.href='?<?php print $_SERVER['QUERY_STRING']; ?>';
  }
  setTimeout('selfRefresh()', <?php print ($wassup_settings['wassup_refresh'] * 60000); ?>);
  //]]>
</script>

<script type='text/javascript'>
  //<![CDATA[
  var _countDowncontainer="0";
  var _currentSeconds="0";
  function ActivateCountDown(strContainerID, initialValue) {
  	_countDowncontainer = document.getElementById(strContainerID);
  	SetCountdownText(initialValue);
  	window.setTimeout("CountDownTick()", 1000);
  }
  function CountDownTick() {
  	SetCountdownText(_currentSeconds-1);
  	window.setTimeout("CountDownTick()", 1000);
  }
  function SetCountdownText(seconds) {
  	//store:
  	_currentSeconds = seconds;
  	//build text:
  	var strText = AddZero(seconds);
  	//apply:
  	if (_countDowncontainer) {	//prevents error in "Options" submenu
  		_countDowncontainer.innerHTML = strText;
  	}
  }
  function AddZero(num) {
  	return ((num >= "0")&&(num < 10))?"0"+num:num+"";
  }
  //]]>
</script>
<script type="text/javascript">
  //<![CDATA[
  window.onload=WindowLoad;
  function WindowLoad(event) {
  	ActivateCountDown("CountDownPanel", <?php print ($wassup_settings['wassup_refresh'] * 60); ?>);
  }
  //]]>
</script>

<script type="text/javascript">
  //<![CDATA[
  jQuery(document).ready(function($){
  	$("a.showhide").click(function(){
  	   var id = $(this).attr('id');
  	   $("div.navi" + id).toggle("slow");
  	   return false;
  	});
  	$("a.toggleagent").click(function(){
  	   var id = $(this).attr('id');
  	   $("div.naviagent" + id).slideToggle("slow");
  	   return false;
  	});
        $("a.deleteID").click(function(){
           var id = $(this).attr('id');
                 $.ajax({
                  url: "<?php echo $wpurl; ?>/wp-content/plugins/<?php echo WASSUPFOLDER; ?>/lib/action.php?action=delete&hash=<?php echo $hash; ?>&id=" + id,
                  async: false
                 })
           $("div.delID" + id).fadeOut("slow");
           return false;
        });
  	$("a.show-search").toggle(function(){
  	   $("div.search-ip").slideDown("slow");
  	     $("a.show-search").html("<a href='#' class='show-search'>Hide Search</a>");
  	    },function() {
  	   $("div.search-ip").slideUp("slow");
  	     $("a.show-search").html("<a href='#' class='show-search'>Search</a>");
  	   return false;
  	   });
  	$("a.show-topten").toggle(function(){
  	   $("div.topten").slideDown("slow");
  	     $("a.show-topten").html("<a href='#' class='show-topten'>Hide TopTen</a>");
  	    },function() {
  	   $("div.topten").slideUp("slow");
  	     $("a.show-topten").html("<a href='#' class='show-topten'>Show TopTen</a>");
  	   return false;
  	   });

  	$("a.toggle-all").toggle(function() {
  	     $("div.togglenavi").slideDown("slow");
  	     $("a.toggle-all").html("<a href='#' class='toggle-all'>Collapse All</a>");
  	    },function() {
  	     $("div.togglenavi").slideUp("slow");
  	     $("a.toggle-all").html("<a href='#' class='toggle-all'>Expand All</a>");
  	   return false;
  	    });
  	$("a.toggle-allcrono").toggle(function() {
  	     $("div.togglecrono").slideUp("slow");
  	     $("a.toggle-allcrono").html("<a href='#' class='toggle-allcrono'>Expand Cronology</a>");
  	  },function() {
  	     $("div.togglecrono").slideDown("slow");
  	     $("a.toggle-allcrono").html("<a href='#' class='toggle-allcrono'>Collapse Cronology</a>");
  	  return false;
  	  });
  });	//end jQuery(document).ready
  //]]>
</script>
<?php } //end if page != wassup-options ?>

<script type='text/javascript'>
  //<![CDATA[
  function go()
  {
  	box = document.forms["0"].navi;
  	destination = box.options[box.selectedindex].value;
  	if (destination) location.href = destination;
  }
  function go2()
  {
  	box2 = document.forms["0"].type;
  	destination2 = box2.options[box2.selectedindex].value;
  	if (destination2) location.href = destination2;
  }
  //]]>
</script>

<?php
if ($_GET['page'] == "wassup-spy") {
?>
<script type="text/javascript">
  jQuery(document).ready(function($){
  	$('#spyContainer > div:gt(4)').fadeEachDown(); // initial fade
  	$('#spyContainer').spy({ 
  		limit: 10, 
  		fadeLast: 5, 
		ajax: '<?php echo $wpurl."/wp-content/plugins/".WASSUPFOLDER."/lib/action.php?action=spy&hash=$hash"; ?>',
  		timeout: 2000, 
  		'timestamp': myTimestamp, 
		fadeInSpeed: 1100 });
  });
	
  function myTimestamp() {
  	var d = new Date();
  	var timestamp = d.getFullYear() + '-' + pad(d.getMonth()) + '-' + pad(d.getDate());
  	timestamp += ' ';
  	timestamp += pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
  	return timestamp;
  }

  // pad ensures the date looks like 2006-09-13 rather than 2006-9-13
  function pad(n) {
  	n = n.toString();
  	return (n.length == 1 ? '0' + n : n);
  }

  //]]>
</script>
<?php } //end if page == "wassup-spy"

} //end if plugin_page == "wassup"
} //end function add_wassup_css()

//put WassUp in the top-level admin menu and add submenus....
function wassup_add_pages() {
	$wassup_settings = get_option('wassup_settings');
	$userlevel = $wassup_settings['wassup_userlevel'];
	if (empty($userlevel)) { $userlevel = 8; }
	// add the default submenu first (important!)...
	add_submenu_page(WASSUPFOLDER, __('Visitor Details', 'wassup'), __('Visitor Details', 'wassup'), $userlevel, WASSUPFOLDER, 'WassUp'); //<-- WASSUPFOLDER needed here for directory names that include a version number...
	// then add top menu and other submenus...
	add_menu_page('Wassup', 'WassUp', $userlevel, WASSUPFOLDER, 'Wassup');
	add_submenu_page(WASSUPFOLDER, __('Spy Visitors', 'wassup'), __('SPY Visitors', 'wassup'), $userlevel, 'wassup-spy', 'WassUp');
	add_submenu_page(WASSUPFOLDER, __('Current Visitors Online', 'wassup'), __('Current Visitors Online', 'wassup'), $userlevel, 'wassup-online', 'WassUp');
	add_submenu_page(WASSUPFOLDER, __('Options', 'wassup'), __('Options', 'wassup'), $userlevel, 'wassup-options', 'WassUp');
}

function WassUp() {
	global $wpdb, $version, $wpurl, $defaultWdata;
	$hash = wp_hash('wassup');
	$table_name = $wpdb->prefix . "wassup";
	$wassup_settings = get_option('wassup_settings');
	// RUN THE SAVE/RESET OPTIONS
	if (isset($_POST['submit'])) {
		if ($_POST['wassup_remind_flag'] == 1 AND $_POST['wassup_remind_mb'] == "") {
			$wassup_settings['wassup_remind_flag'] = $_POST['wassup_remind_flag'];
			$wassup_settings['wassup_remind_mb'] = 10;
		} else {
			$wassup_settings['wassup_remind_flag'] = $_POST['wassup_remind_flag'];
	                $wassup_settings['wassup_remind_mb'] = $_POST['wassup_remind_mb'];
		}
		$wassup_settings['wassup_active'] = $_POST['wassup_active'];
		$wassup_settings['wassup_loggedin'] = $_POST['wassup_loggedin'];
		$wassup_settings['wassup_spider'] = $_POST['wassup_spider'];
		$wassup_settings['wassup_attack'] = $_POST['wassup_attack'];
		$wassup_settings['wassup_spamcheck'] = $_POST['wassup_spamcheck'];
                $wassup_settings['wassup_spam'] = $_POST['wassup_spam'];
                $wassup_settings['wassup_refspam'] = $_POST['wassup_refspam'];
		$wassup_settings['wassup_exclude'] = $_POST['wassup_exclude'];
		$wassup_settings['delete_auto'] = $_POST['delete_auto'];
                $wassup_settings['delete_auto_size'] = $_POST['delete_auto_size'];
		$wassup_settings['wassup_screen_res'] = $_POST['wassup_screen_res'];
		$wassup_settings['wassup_refresh'] = $_POST['wassup_refresh'];
		$wassup_settings['wassup_userlevel'] = $_POST['wassup_userlevel'];
		$wassup_settings['wassup_default_type'] = $_POST['wassup_default_type'];
		$wassup_settings['wassup_default_limit'] = $_POST['wassup_default_limit'];
		if ( $_POST['wassup_savepath'] != $wassup_settings['wassup_savepath'] ) {
			if ( empty($_POST['wassup_savepath']) || rtrim($_POST['wassup_savepath'],"/") == wGetSessionpath() ) {
				$wassup_settings['wassup_savepath'] = NULL;
			} else {
				$wassup_settings['wassup_savepath'] = rtrim($_POST['wassup_savepath'],"/");
			}
		}
		update_option('wassup_settings', $wassup_settings);
	} elseif (isset($_POST['submit-spam'])) {
		$wassup_settings['wassup_spamcheck'] = $_POST['wassup_spamcheck'];
                $wassup_settings['wassup_spam'] = $_POST['wassup_spam'];
                $wassup_settings['wassup_refspam'] = $_POST['wassup_refspam'];
		update_option('wassup_settings', $wassup_settings);
        } elseif (isset($_POST['reset-to-default'])) {
	print_r($defaultWdata);
                delete_option('wassup_settings');
                update_option('wassup_settings', $defaultWdata);
		$wassup_settings = get_option('wassup_settings');
        }


	if ($_GET['page'] == "wassup-spy") {
		$class_spy="class='current'";
	} elseif ($_GET['page'] == "wassup-options") {
		$class_opt="class='current'";
	} elseif ($_GET['page'] == "wassup-online") {
		$class_ol="class='current'";
	} else {
		$class_sub="class='current'";
	}

	//for stringShortener calculated values and max-width...-Helene D. 11/27/07, 12/6/07
	if (!empty($wassup_settings['wassup_screen_res'])) {
		$screen_res_size = (int) $wassup_settings['wassup_screen_res'];
	} else { 
		$screen_res_size = 670;
	}
	$max_char_len = ($screen_res_size)/10;
	$screen_res_size = $screen_res_size+20; //for wrap margins...

	//moved max-width to single "wrap" div and removed it from 
	//  the individual spans and divs in style.php...	
	print '<div class="wrap" style="max-width:'.$screen_res_size.'px;" >';
	//#moved CreateTable/UpdateTable to "wassup_install" function...

	//for generating page link urls....
	//$wpurl =  get_bloginfo('wpurl');	//global
	$siteurl =  get_bloginfo('siteurl');

	if ($_GET['page'] == "wassup-online") {
		$to_date = wassup_get_time();
		$from_date = strtotime('-3 minutes', $to_date);
		print '<h2>Current Visitors Online</h2>';
		print '<p style="font-size:11px">Legend: <span class="box-log">&nbsp;&nbsp;</span> Logged-in Users <span class="box-aut">&nbsp;&nbsp;</span> Comments Authors <span class="box-spider">&nbsp;&nbsp;</span> Spiders/bots</p><br />'."\n";
		print '<p style="font-size:11px;"><a href="#" class="toggle-all">Expand All</a></p>';
		$currenttot = $wpdb->get_var("SELECT COUNT(DISTINCT wassup_id) as currenttot FROM $table_name WHERE timestamp BETWEEN $from_date AND $to_date");
		$currenttot = $currenttot+0;	//set to integer
		print "<p style='font-size:11px;'>Visitors online: <strong>".$currenttot."</strong></p><br />";
		if ($currenttot > 0) {
		$qryC = $wpdb->get_results("SELECT id, wassup_id, max(timestamp) as max_timestamp, ip, hostname, searchengine, urlrequested, agent, referrer, spider, username, comment_author FROM $table_name WHERE timestamp BETWEEN $from_date AND $to_date GROUP BY ip ORDER BY max_timestamp DESC");
		foreach ($qryC as $cv) {
		//$timestamp = $cv->max_timestamp;	//redundant
		$timed = gmdate("H:i:s", $cv->max_timestamp);
		$ip = @explode(",", $cv->ip);
		if ($cv->referrer != '') {
			if (!eregi($wpurl, $cv->referrer) OR $cv->searchengine != "") { 
				if (!eregi($wpurl, $cv->referrer) AND $cv->searchengine == "") {
				$referrer = '<a href="'.$cv->referrer.'" target=_"BLANK"><span style="font-weight: bold;">'.stringShortener($cv->referrer, round($max_char_len*.8,0)).'</span></a>';
				} else {
				$referrer = '<a href="'.$cv->referrer.'" target=_"BLANK">'.stringShortener($cv->referrer, round($max_char_len*.9,0)).'</a>';
				}
			} else { 
			$referrer = "Direct hit"; 
			} 
		} else { 
			$referrer = "From your blog"; 
		} 
		$numurl = $wpdb->get_var("SELECT COUNT(DISTINCT id) as numurl FROM $table_name WHERE wassup_id='".$cv->wassup_id."'");
	?>
			<div class="sum">
			<span class="sum-box"><?php if ($numurl >= 2) { ?><a  href="#" class="showhide" id="<?php echo $cv->id ?>"><?php print $ip[0]; ?></a><? } else { ?><?php print $ip[0]; ?><?php } ?></span>
			<div class="sum-det"><span class="det1">
			<?php
			//# html_entity_decode() links that were already 
			//#  "htmlentities-encoded" in database to prevent wacky links
			//#  like "/imagegallery/?album=3&amp;amp;amp;gallery=13"
			print '<a href="'.wAddSiteurl(htmlspecialchars(html_entity_decode($cv->urlrequested))).'" target="_BLANK">';
			print stringShortener(urlencode(html_entity_decode($cv->urlrequested)), round($max_char_len*.9,0)); ?></a></span><br />
			<span class="det2"><strong><?php print $timed; ?> - </strong><?php print $referrer ?></span></div>
			</div>
			<?php // User is logged in or is a comment's author
			if ($cv->username != "" OR $cv->comment_author != "") {
				if ($cv->username != "") {
					$Ousername = '<li class="users"><span class="indent-li-agent">LOGGED IN USER: <strong>'.$cv->username.'</strong></span></li>'; 
					$Ocomment_author = '<li class="users"><span class="indent-li-agent">COMMENT AUTHOR: <strong>'.$cv->comment_author.'</strong></span></li>'; 
					$unclass = "userslogged";
				} elseif ($cv->comment_author != "") {
					$Ocomment_author = '<li class="users"><span class="indent-li-agent">COMMENT AUTHOR: <strong>'.$cv->comment_author.'</strong></span></li>'; 
					$unclass = "users";
				}
			?>
			<ul class="<?php print $unclass; ?>">
				<?php print $Ousername; ?>
				<?php print $Ocomment_author; ?>
			</ul>
			<?php  } ?>
			<div style="display: none;" class="togglenavi navi<?php echo $cv->id ?>">
			<ul class="url">
	<?php 
			$qryCD = $wpdb->get_results("SELECT timestamp, urlrequested FROM $table_name WHERE wassup_id='".$cv->wassup_id."' ORDER BY timestamp ASC");
			$i=0;
			foreach ($qryCD as $cd) {	
			//$timestamp2 = $cd->timestamp; //redundant
			$time2 = gmdate("H:i:s", $cd->timestamp);
			$num = ($i&1);
			$char_len = round($max_char_len*.9,0);
			if ($num == 0) $classodd = "urlodd"; else  $classodd = "url";
			if ($i >= 1) {
	?>
				<li class="<?php print $classodd; ?> navi<?php echo $cv->id ?>"><span class="indent-li"><?php print $time2; ?> - 
				<?php
				print '<a href="'.wAddSiteurl(htmlspecialchars(html_entity_decode($cd->urlrequested))).'" target="_BLANK">';
				print stringShortener(urlencode(html_entity_decode($cd->urlrequested)), $char_len).'</a></span></li>'."\n";
			}
			$i++;
			} //end foreach qryCD
			print '</ul>';
			print '</div>';
			print '<p class="sum-footer"></p>';
		} //end foreach qryC
		} //end if currenttot
		print '<br /><p style="font-size:11px;"><a href="#" class="toggle-all">Expand All</a></p>';
	
	// HERE IS THE SPY MODE VIEW
	} elseif ($_GET['page'] == "wassup-spy") {
		print '<h2>SPY Visitors</h2>';
		print '<p style="font-size:11px">Legend: <span class="box-log">&nbsp;&nbsp;</span> Logged-in Users <span class="box-aut">&nbsp;&nbsp;</span> Comments Authors <span class="box-spider">&nbsp;&nbsp;</span> Spiders/bots</p><br />'."\n";
		print '<div>';
		print '<a href="#?" onclick="return pauseSpy();"><span id="spy-pause">Pause</span></a> ';
		print '<a href="#?" onclick="return playSpy();"><span id="spy-play">Play</span></a>';
		print '<br />&nbsp;<br /></div>'."\n";
		print '<div id="spyContainer">'."\n".'<!-- spyContainer is empty -->'."\n";
		//display the last few hits here. The rest will be added via spy.js
		$to_date = (wassup_get_time()-2);
		$from_date = ($to_date - 12*(60*60)); //display last 10 visits in 12 hours...
		spyview($from_date,$to_date,10);
		print '</div>';
echo "<br />";

	// HERE IS THE OPTIONS VIEW
	} elseif($_GET['page'] == "wassup-options") {
		//#moved content to external include file, "settings.php"
		//#  to make "wassup" code easier to read and modify 
		//#  -Helene D. 1/15/08.
		include(dirname(__FILE__).'/lib/settings.php'); ?>

<?php	// HERE IS THE MAIN/DETAILS VIEW
	} else {

		$search = attribute_escape($_GET['search']);
		$res = (int) $wassup_settings['wassup_screen_res'];
		if (empty($res)) $res=620;
		elseif ($res < 800) $res=620;
		elseif ($res < 1024) $res=740;
		elseif ($res < 1200) $res=1000;
		else $res=1000;
		
        if (isset($_GET['wmark'])) {
		if ($_GET['wmark'] == 0) {
                	$wassup_settings['wmark'] = "0";
	                $wassup_settings['wip'] = "";
                } else {
			$wassup_settings['wmark'] = "1";
	                $wassup_settings['wip'] = attribute_escape($_GET['wip']);
		}
                update_option('wassup_settings', $wassup_settings);
        }
        if (isset($_GET['wchart'])) {
		if ($_GET['wchart'] == 0) {
			$wassup_settings['wchart'] = 0;
		} else {
			$wassup_settings['wchart'] = 1;
		}
                update_option('wassup_settings', $wassup_settings);
	}
		
		if ($wassup_settings['wassup_default_limit'] != '' AND !isset($_GET['limit'])) {
			$items = $wassup_settings['wassup_default_limit'];
		} elseif(isset($_GET['limit'])) {
			$items = htmlentities(attribute_escape($_GET['limit'])); 
		} else {
			$items = 10;
		}

		if ($wassup_settings['wassup_default_type'] != '' AND !isset($_GET['type'])) {
			$type = $wassup_settings['wassup_default_type'];
		} else {
			$type = htmlentities(attribute_escape($_GET['type']));
		}

		if ($type == 'spider') {
			$whereis = " AND spider!=''";
		} elseif ($type == 'nospider') {
			$whereis = " AND spider=''";
                } elseif ($type == 'spam') {
                        $whereis = " AND spam>0";
                } elseif ($type == 'nospam') {
                        $whereis = " AND spam=0";
                } elseif ($type == 'nospamspider') {
                        $whereis = " AND spam=0 AND spider=''";
		} elseif ($type == 'searchengine') {
			$whereis = " AND searchengine!='' AND search!=''";
		} elseif ($type == 'referrer') {
			$whereis = " AND referrer!='' AND referrer NOT LIKE '%$wpurl%' AND searchengine='' AND search=''";
		} elseif ($type == 'comauthor') {
			$whereis = " AND comment_author!='' AND username=''";
		} elseif ($type == 'loggedin') {
			$whereis = " AND username!=''";
		}

		$pages = 1;
		if(isset($_GET['pages']) and is_numeric($_GET['pages']) and $pages = $_GET['pages']) {
			$limit = " LIMIT ".(($pages-1)*$items).",$items";
		} else {
			$limit = " LIMIT $items";
		}

		print "<h2>Latest hits</h2>";
		$to_date = wassup_get_time();
		if ($_GET['last'] == "") $last = 1; else $last = htmlentities(attribute_escape($_GET['last']));
		$from_date = strtotime('-'.$last.' day', $to_date);

		// Instantiate class to count items
		$Tot = New MainItems;
		$Tot->tableName = $table_name;
		$Tot->from_date = $from_date;
		$Tot->to_date = $to_date;
		$Tot->whereis = $whereis;
		$Tot->Limit = $limit;
		$Tot->WpUrl = $wpurl;

		$itemstot = $Tot->calc_tot("items", $search);
		$pagestot = $Tot->calc_tot("pages", $search);
		$spamtot = $Tot->calc_tot("spam", $search);
		// Check if some records was marked
		if ($wassup_settings['wmark'] == 1) {
			$Tot->Marked_ip = $wassup_settings['wip']; 
			$markedtot = $Tot->calc_tot("items_by_type", $search, "marked");
		}


		$new_limit = eregi_replace("\&limit=".$_GET['limit']."", "", $_SERVER['QUERY_STRING']);
		$new_type = eregi_replace("\&type=".$_GET['type']."", "", $_SERVER['QUERY_STRING']);
		$new_last = eregi_replace("\&last=".$_GET['last']."", "", $_SERVER['QUERY_STRING']);

		if ($wassup_settings['wassup_active'] != 1) {
			print "<p style='color: red; font-weight: bold;'>WassUp recording is disabled</p>";
		}
		// DELETE EVERY RECORD MARKED BY IP
		if ($_GET['deleteMARKED'] == 1) {
			$rec_deleted = $wpdb->get_var("SELECT COUNT(ip) as deleted FROM $table_name WHERE ip='".urlencode(attribute_escape($_GET['dip']))."'");
			$wpdb->query("DELETE FROM $table_name WHERE ip='%s'", urlencode(attribute_escape($_GET['dip'])));
			echo "<p><strong>".$rec_deleted." records deleted</strong></p>";
		}
		echo "<table width='100%'>
		<tr>
		<td>
		<form><p style=\"font-size: 11px;\">";
		if ($wassup_settings['wchart'] == 1) {
			echo "<a href='?page=".WASSUPFOLDER."&wchart=0' style='text-decoration:none;'><img src='$wpurl/wp-content/plugins/".WASSUPFOLDER."/img/chart_delete.png' style='padding:0px 6px 0 0;' alt='hide chart' title='Hide the chart and site usage'></a>";
		} else {
			echo "<a href='?page=".WASSUPFOLDER."&wchart=1' style='text-decoration:none;'><img src='$wpurl/wp-content/plugins/".WASSUPFOLDER."/img/chart_add.png' style='padding:0px 6px 0 0;' alt='show chart' title='Show the chart and site usage'></a>";
		}
		echo "Summary for the last <select style=\"font-size: 11px;\" name='last' onChange='window.location.href=this.options[this.selectedIndex].value;'>
		<option value='?$new_last&last=1'".($_GET['last'] == 1 ? " SELECTED" : "").">24 hours</option>
		<option value='?$new_last&last=7'".($_GET['last'] == 7 ? " SELECTED" : "").">7 days</option>
		<option value='?$new_last&last=30'".($_GET['last'] == 30 ? " SELECTED" : "").">1 month</option>
		<option value='?$new_last&last=365'".($_GET['last'] == 365 ? " SELECTED" : "").">1 year</option>
		</select></p>
		</td>
		<td align='right'><p style=\"font-size: 11px;\">Items per page: <select name='navi' style=\"font-size: 11px;\" onChange='window.location.href=this.options[this.selectedIndex].value;'>
		<option value='?$new_limit&limit=10'".($items == 10 ? " SELECTED" : "").">10</option>
		<option value='?$new_limit&limit=20'".($items == 20 ? " SELECTED" : "").">20</option>
		<option value='?$new_limit&limit=50'".($items == 50 ? " SELECTED" : "").">50</option>
		<option value='?$new_limit&limit=100'".($items == 100 ? " SELECTED" : "").">100</option>
		</select> - Show items by: <select style=\"font-size: 11px;\" name='type' onChange='window.location.href=this.options[this.selectedIndex].value;'>
		<option value='?page=".WASSUPFOLDER."'>--</option>
		<option value='?$new_type&type=spider'".($type == "spider" ? " SELECTED" : "").">Spider</option>
		<option value='?$new_type&type=nospider'".($type == "nospider" ? " SELECTED" : "").">NO Spider</option>
                <option value='?$new_type&type=spam'".($type == "spam" ? " SELECTED" : "").">Spam</option>
                <option value='?$new_type&type=nospam'".($type == "nospam" ? " SELECTED" : "").">NO Spam</option>
                <option value='?$new_type&type=nospamspider'".($type == "nospamspider" ? " SELECTED" : "").">NO Spam NO Spider</option>
		<option value='?$new_type&type=loggedin'".($type == "loggedin" ? " SELECTED" : "").">Users logged in</option>
		<option value='?$new_type&type=comauthor'".($type == "comauthor" ? " SELECTED" : "").">Comment's authors</option>
		<option value='?$new_type&type=searchengine'".($type == "searchengine" ? " SELECTED" : "").">Referer from search engine</option>
		<option value='?$new_type&type=referrer'".($type == "referrer" ? " SELECTED" : "").">Referer from ext link</option>
		<option value='?$new_type&type=everything'".($type == "everything" ? " SELECTED" : "").">Everything</option>
		</select>
		</p>
		</form>
		</td>
		</tr>
		</table>
		";
		
		if ($wassup_settings['wchart'] == 1) {
		// Print Site Usage
		//#print useage/google chart only on page 1...
		//if (!isset($_GET['pages']) || (int)$_GET['pages'] < 2) {
		echo "
	<div class='main-tabs'>
		<div id='usage'>
			<ul>
				<li><span style='border-bottom: 2px solid #0077CC;'>".$itemstot."</span> <small>Visits</small></li>
				<li><span style='border-bottom: 2px dashed #FF6D06;'>".$pagestot."</span> <small>Pageviews</small></li>
				<li><span>".@number_format(($pagestot/$itemstot), 2)."</span> <small>Pages/Visits</small></li>
				<li><span><a href=\"#TB_inline?height=55&width=400&inlineId=hiddenspam\" class=\"thickbox\">".$spamtot."</a></span> <span>(".@number_format(($spamtot*100/$pagestot), 2)."%)</span> <small>Spams</small></li>
			</ul>";
		// Print the Google chart!
		if ($pagestot > 20) {
			echo $Tot->TheChart($last, $res, attribute_escape($_GET['search']))."";
		} else {
			echo "<div id='placeholder' align='center'><p style='padding-top:50px;'>Waiting for some data to print chart...</p></div>";
		}
		echo "
		</div>
	</div>";
		}
	
		if ($_GET['limit'] == 10 OR $_GET['limit'] == 20 OR !isset($_GET['limit'])) {
			$expcol = '
		<table width="100%"><tr>
		<td align="left" style="font-size: 11px;"><a href="#" class="toggle-all">'.__('Expand All','wassup').'</a></td>
		<td align="right" style="font-size: 11px;"><a href="#" class="toggle-allcrono">'.__('Collapse Chronology','wassup').'</a></td>
		</tr></table><br />';
		}
		
		// MAIN QUERY
		$main = $Tot->calc_tot("main", $search);

		if ($itemstot > 0) {
		$p=new pagination();
		$p->items($itemstot);
		$p->limit($items);
		$p->currentPage($pages);
		$p->target("admin.php?page=".WASSUPFOLDER."&limit=$items&type=$type&last=$last&search=$search");
		$p->calculate();
		$p->adjacents(5);
		}

		// hidden spam options
                ?>
                <div id="hiddenspam" style="display:none;">
        <h2>Spam Options</h2>
        <form action="" method="post">
	<p><input type="checkbox" name="wassup_spamcheck" value="1" <?php if($wassup_settings['wassup_spamcheck'] == 1 ) print "CHECKED"; ?> /> <strong><?php _e('Enable/Disable Spam Check on Records','wassup'); ?></strong></p>
        <p style="padding-left:30px;"><input type="checkbox" name="wassup_spam" value="1" <?php if($wassup_settings['wassup_spam'] == 1) print "CHECKED"; ?> /> <?php _e('Record Akismet comment spam attempts','wassup'); ?></p>
        <p style="padding-left:30px;"><input type="checkbox" name="wassup_refspam" value="1" <?php if($wassup_settings['wassup_refspam'] == 1) print "CHECKED"; ?> /> <?php _e('Record referrer spam attempts','wassup'); ?></p>
        <p style="padding-left:0;"><input type="submit" name="submit-spam" value="<?php _e('Save Settings','wassup'); ?>" /></p>
        </form>
                </div>
		<table width="100%">
		<tr>
		<td align="left" style="font-size: 11px;"><?php if ($wassup_settings['wmark'] == 1) echo "<a href='?".$_SERVER['QUERY_STRING']."&search=".$wassup_settings['wip']."' title='Filter by marked IP'><strong>$markedtot</strong> visits marked</a> - "; if ($search != "") print "Searched for: <strong>$search</strong> - "; ?>Auto refresh in <span id="CountDownPanel"></span> seconds</td>
                        
		<td align="right" style="font-size: 11px;"><a href="<?php echo $wpurl."/wp-content/plugins/".WASSUPFOLDER."/lib/action.php?height=400&width=$res&action=topten&hash=$hash&from_date=$from_date&to_date=$to_date"; ?>" class="thickbox">Show TopTen</a> - <a href="#" class='show-search'>Search</a></td>
		</tr>
		</table>
<div class="search-ip" style="display: none;">
	<table border=0 width="100%">
		<tr valign="top">
		<td align="right">
        	<form action="" method="get">
		<input type="hidden" name="page" value="<?php echo WASSUPFOLDER; ?>">
			<input type="text" size="25" name="search" value="<?php if ($search != "") print $search; ?>"><input type="submit" name="submit-search" value="search">
		</form>
		</td>
		</tr>
	</table>
</div>
<!-- end Top Ten -->
<?php
	//# Detailed List of Wassup Records...
	print $expcol;
	//# Show Page numbers/Links...
	if ($itemstot >= 10) {
		print "<div id='pag' align='center'>".$p->show()."</div>";
	}
	?>
	<br />
	
	<?php
	if ($itemstot > 0) {
	foreach ($main as $rk) {
		$timestampF = $rk->max_timestamp;
		$dateF = gmdate("d M Y", $timestampF);
		$timeF = gmdate("H:i:s", $timestampF);
		$datetimeF = gmdate('Y-m-d H:i:s', $timestampF);
		$ip = @explode(",", $rk->ip);
		if ($rk->referrer != '') {
			if (!eregi($wpurl, $rk->referrer) OR $rk->searchengine != "") { 
				if (!eregi($wpurl, $rk->referrer) AND $rk->searchengine == "") {
				$referrer = '<a href="'.$rk->referrer.'" target="_BLANK"><span style="font-weight: bold;">'.stringShortener($rk->referrer, round($max_char_len*.8,0)).'</span></a>';
				} else {
				$referrer = '<a href="'.$rk->referrer.'" target="_BLANK">'.stringShortener($rk->referrer, round($max_char_len*.9,0)).'</a>';
				}
			} else { 
			$referrer = "From your blog"; 
			} 
		} else { 
			$referrer = "Direct hit"; 
		} 
		$numurl = $wpdb->get_var("SELECT COUNT(DISTINCT id) as numurl FROM $table_name WHERE wassup_id='".$rk->wassup_id."'");
		if ($rk->hostname != "") $hostname = $rk->hostname; else $hostname = "unknown";
	?>

	<div class="delID<?php echo $rk->wassup_id ?>">
                <div class="<?php if ($wassup_settings['wmark'] == 1 AND $wassup_settings['wip'] ==  $ip[0]) echo "sum-nav-mark"; else echo "sum-nav"; ?>">

                        <p class="delbut">
                        <?php // Mark/Unmark IP
                        if ($wassup_settings['wmark'] == 1 AND $wassup_settings['wip'] ==  $ip[0]) { ?>
                        <a  href="?<?php echo $_SERVER['QUERY_STRING'] ?>&deleteMARKED=1&dip=<?php print $ip[0]; ?>" style="text-decoration:none;"><img src="<?php echo $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/img/cross.png'; ?>" alt="delete" title="Delete EVERY records marked by this IP from DB"></a>
                        <a href="?page=<?php echo WASSUPFOLDER; ?>&wmark=0" style="text-decoration:none;">
                        <img src="<?php echo $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/img/error_delete.png'; ?>" alt="mark" title="UnMark IP">
                        </a>
                        <?php } else { ?>
                        <a  href="#" class="deleteID" id="<?php echo $rk->wassup_id ?>" style="text-decoration:none;"><img src="<?php echo $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/img/cross.png'; ?>" alt="delete" title="Delete record from DB"></a>
                        <a href="?<?php echo $_SERVER['QUERY_STRING'] ?>&wmark=1&wip=<?php print $ip[0]; ?>" style="text-decoration:none;">
                        <img src="<?php echo $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/img/error_add.png'; ?>" alt="mark" title="Mark IP">
                        </a>
                        <?php } ?>
			<a href="<?php echo $wpurl."/wp-content/plugins/".WASSUPFOLDER."/lib/action.php?height=400&width=$res&action=displayraw&hash=$hash&wassup_id=".$rk->wassup_id.""; ?>" class="thickbox"><img src="<?php echo $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/img/database_table.png'; ?>" alt="show raw table" title="Show the items as raw table"></a>
                        </p>

			<span class="sum-box"><?php if ($numurl >= 2) { ?><a  href="#" class="showhide" id="<?php echo $rk->id ?>"><?php print $ip[0]; ?></a><? } else { ?><?php print $ip[0]; ?><?php } ?></span>
			<span class="sum-date"><?php print $datetimeF; ?></span>
			<div class="sum-det"><span class="det1">
			<?php 
			print '<a href="'.wAddSiteurl(htmlspecialchars(html_entity_decode($rk->urlrequested))).'" target="_BLANK">';
			print stringShortener(urlencode(html_entity_decode($rk->urlrequested)), round($max_char_len*.8,0)); ?></a>
			</span><br />
			<span class="det2"><strong>Referer: </strong><?php print $referrer; ?><br /><strong>Hostname:</strong> <a  href="#" class="toggleagent" id="<?php echo $rk->id ?>"><?php print $hostname; ?></a></span></div>
			</div>
			<div style="margin-left: auto; margin-right: auto;">
			<div style="display: none;" class="togglenavi naviagent<?php echo $rk->id ?>">
			<ul class="useragent">
					<li class="useragent"><span class="indent-li-agent">UserAgent: <strong><?php print $rk->agent; ?></strong></span></li>
			</ul>
			</div>
			<?php // Referer is search engine
			if ($rk->searchengine != "") {
				if (eregi("images", $rk->searchengine)) {
					$bg = 'style="background: #e5e3ec;"';
					$page = (number_format(($rk->searchpage / 19), 0) * 18); 
					$Apagenum = explode(".", number_format(($rk->searchpage / 19), 1));
					$pagenum = ($Apagenum[0] + 1);
					$url = parse_url($rk->referrer); 
					$ref = $url['scheme']."://".$url['host']."/images?q=".eregi_replace(" ", "+", $rk->search)."&start=".$page;
				} else {
					$bg = 'style="background: #e4ecf4;"';
					$pagenum = $rk->searchpage;
					$ref = $rk->referrer;
				}
			?>
			<ul class="searcheng" <?php print $bg; ?>>
					<li class="searcheng"><span class="indent-li-agent">SEARCH ENGINE: <strong><?php print $rk->searchengine." (page: $pagenum)"; ?></strong></span></li>
					<li class="searcheng">KEYWORDS: <strong><a href="<?php print $ref;  ?>" target="_BLANK"><?php print stringShortener($rk->search, round($max_char_len*.52,0)); ?></a></strong></li>
			</ul>
			<?php 
			} ?>
			<?php
			// User is logged in or is a comment's author
			if ($rk->username != "" OR $rk->comment_author != "") {
				if ($rk->username != "") {
					$Ocomment_author = '<li class="users"><span class="indent-li-agent">LOGGED IN USER: <strong>'.$rk->username.'</strong></span></li>
					<li class="users"><span class="indent-li-agent">COMMENT AUTHOR: <strong>'.$rk->comment_author.'</strong></span></li>'; 
					$unclass = "userslogged";
				} elseif ($rk->comment_author != "") {
					$Ocomment_author = '<li class="users"><span class="indent-li-agent">COMMENT AUTHOR: <strong>'.utf8_decode($rk->comment_author).'</strong></span></li>'; 
					$unclass = "users";
				}
			?>
			<ul class="<?php print $unclass; ?>">
				<?php print $Ocomment_author; ?>
			</ul>
			<?php  } ?>
			<?php // Referer is a Spider or Bot
			if ($rk->spider != "") {
			if ($rk->feed != "") { ?>
			<ul style="background:#fdeec8;" class="spider">
				<li class="feed"><span class="indent-li-agent">FEEDREADER: <strong><?php print $rk->spider; ?></strong></span></li>
				<li class="feed"><span class="indent-li-agent">SUBSCRIBER(S): <strong><?php print $rk->feed; ?></strong></span></li>
			</ul>
			<?php  } else { ?>
			<ul class="spider">
				<li class="spider"><span class="indent-li-agent">SPIDER: <strong><?php print $rk->spider; ?></strong></span></li>
			</ul>
			<?php  }
			} ?>
                        <?php // Referer is a SPAM
                        if ($rk->spam > 0) { ?>
                        <ul class="spam">
                                <li class="spam"><span class="indent-li-agent">Probably SPAM! <?php if ($rk->spam==1) { ?>(Akismet Spam)<?php } elseif ($rk->spam==2) { ?>(Referer Spam)<?php } ?></span></li>
                        </ul>
                        <?php  } ?>
			<?php // User os/broswer/language
			if ($rk->os != "" OR $rk->browser != "") {
			?>
			<ul class="agent">
					<li class="agent"><span class="indent-li-agent"><?php if ($rk->language != "") { ?><img src="<?php echo $wpurl.'/wp-content/plugins/'.WASSUPFOLDER.'/img/flags/'.strtolower($rk->language).'.png'; ?>" alt="<?php print strtolower($rk->language); ?>" title="Language: <?php print strtolower($rk->language); ?>"><?php } ?> OS: <strong><?php print $rk->os; ?></strong></span></li>
					<li class="agent">BROWSER: <strong><?php print $rk->browser; ?></strong></li>
			</ul>
			<?php  } ?>
			
			<div style="display: visible;" class="togglecrono navi<?php echo $rk->id ?>">
			<ul class="url">
	<?php 
			$qryCD = $wpdb->get_results("SELECT timestamp, urlrequested FROM $table_name WHERE wassup_id='".$rk->wassup_id."' ORDER BY timestamp ASC");
			$i=0;
			foreach ($qryCD as $cd) {	
			//$timestamp2 = $cd->timestamp; //redundant
			$time2 = gmdate("H:i:s", $cd->timestamp);
			$char_len = round($max_char_len*.92,0);
			$num = ($i&1);
			if ($num == 0) $classodd = "urlodd"; else  $classodd = "url";
			if ($i >= 1) {
				print '<li class="'.$classodd.' navi'.$rk->id.'"><span class="indent-li-nav">'.$time2.' ->';
				print '<a href="'.wAddSiteurl(htmlspecialchars(html_entity_decode($cd->urlrequested))).'" target="_BLANK">';
				print stringShortener(urlencode(html_entity_decode($cd->urlrequested)), $char_len).'</a></span></li>'."\n";
			}
			$i++;
			} //end foreach qryCD
			print "</ul>";
			?>
			</div>
			<p class="sum-footer"></p>
		</div>
	</div>
<?php	} //end foreach qry

	} //end if itemstot > 0
		print '<br />';
		if ($itemstot >= 10) $p->show();
		print '<br />';
		if ($_GET['limit'] == 10 OR $_GET['limit'] == 20 OR !isset($_GET['limit'])) {
		        print $expcol;
		}

	} //end MAIN/DETAILS VIEW

		print "<p><small>WassUp ver: $version - Check the official <a href='http://www.wpwp.org' target='_BLANK'>WassUp</a> page for updates, bug reports and your hints to improve it</small></p>";
		print "</div>";	
} //end function Wassup

function CreateTable() {
	global $wpdb;
	$table_name = $wpdb->prefix . "wassup";
	$sql_createtable = "CREATE TABLE " . $table_name . " (
  id mediumint(9) NOT NULL auto_increment,
  wassup_id varchar(50) NOT NULL,
  timestamp varchar(20) default NULL,
  ip varchar(35) default NULL,
  hostname varchar(255) default NULL,
  urlrequested text,
  agent varchar(255) default NULL,
  referrer text default NULL,
  search varchar(255) default NULL,
  searchpage int(11) default 0,
  os varchar(15) default NULL,
  browser varchar(50) default NULL,
  language varchar(5) default NULL,
  screen_res varchar(15) default NULL,
  searchengine varchar(20) default NULL,
  spider varchar(50) default NULL,
  feed varchar(30) default NULL,
  username  VARCHAR( 50 ) default NULL,
  comment_author VARCHAR( 50 ) default NULL,
  spam VARCHAR( 50 ) default 0,
  UNIQUE KEY id (id),
  KEY wassup_id (wassup_id)
);";
	require_once( ABSPATH.'wp-admin/upgrade-functions.php');
	dbDelta($sql_createtable);	
} //end function createTable

function UpdateTable() {
	global $wpdb, $wassup_settings;
	$table_name = $wpdb->prefix . "wassup";
	// Upgrade from version < 1.1b 
	if ($wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'username'") == "") {
		$sql_add_username = "ALTER TABLE {$table_name} ADD COLUMN username VARCHAR( 50 ) NULL";
		$wpdb->query( $sql_add_username );
	}
	if ($wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'comment_author'") == "") {
		$sql_add_comment_author = "ALTER TABLE {$table_name} ADD COLUMN comment_author VARCHAR( 50 ) NULL";
		$wpdb->query( $sql_add_comment_author );
	}
	// Upgrade from version < 1.1.4b 
	$Freferrer = $wpdb->get_results("show columns from $table_name LIKE 'referrer'");
	foreach ($Freferrer as $ff) {
		if (eregi("varchar", $ff->Type)) {
			$sql_alter_referrer = "ALTER TABLE {$table_name} CHANGE referrer referrer TEXT NULL";
			$wpdb->query( $sql_alter_referrer );
		}
	}
	// Upgrade from version < 1.2b
	$Fsearchpage = $wpdb->get_results("show columns from $table_name LIKE 'searchpage'");
	foreach ($Fsearchpage as $ss) {
		if ($ss->Default == "") {
			$sql_alter_searchpage = "ALTER TABLE {$table_name} CHANGE searchpage searchpage INT( 11 ) NULL DEFAULT '0'";
			$wpdb->query( $sql_alter_searchpage );
		}
	}
	$Fuseragent = $wpdb->get_results("show columns from $table_name LIKE 'agent'");
	foreach ($Fuseragent as $ua) {
		if ($ua->Type != "varchar(255)") {
			$sql_alter_useragent = "ALTER TABLE {$table_name} CHANGE agent agent varchar(255) NULL";
			$wpdb->query( $sql_alter_useragent );
		}
	}
	$Fbrowser = $wpdb->get_results("show columns from $table_name LIKE 'browser'");
	foreach ($Fbrowser as $br) {
		if ($br->Type != "varchar(50)") {
			$sql_alter_browser = "ALTER TABLE {$table_name} CHANGE browser browser varchar(50) NULL";
			$wpdb->query( $sql_alter_browser );
		}
	}
	$Fspider = $wpdb->get_results("show columns from $table_name LIKE 'spider'");
	foreach ($Fspider as $sp) {
		if ($sp->Type != "varchar(50)") {
			$sql_alter_spider = "ALTER TABLE {$table_name} CHANGE spider spider varchar(50) NULL";
			$wpdb->query( $sql_alter_spider );
		}
	}
        // Upgrade from version < 1.3.9 
        if ($wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'spam'") == "") {
                $sql_add_spam = "ALTER TABLE {$table_name} ADD COLUMN spam VARCHAR( 50 ) DEFAULT '0'";
                $wpdb->query( $sql_add_spam );
        }
} //end function UpdateTable()

//Track visitors and save record in wassup table
function wassupAppend() {
	global $wpdb, $wassup_id, $wp_query, $HTTP_COOKIE_VARS, $screen_res, $wassup_settings, $wpurl;
	$siteurl =  get_bloginfo('siteurl');
	$table_name = $wpdb->prefix . "wassup";	//moved;

	if (!is_admin()) {	//exclude wordpress admin page visits

	//#### Get the visitor's details from http header...
	if (isset($_SERVER["REMOTE_ADDR"])) {
		if ($_SERVER["HTTP_X_FORWARDED_FOR"] != ""){
		        $IP = $_SERVER["HTTP_X_FORWARDED_FOR"];
		        $proxy = $_SERVER["REMOTE_ADDR"];
		        $hostname = @gethostbyaddr($_SERVER["HTTP_X_FORWARDED_FOR"]);
			$ipAddress = $proxy.",".$IP;
		}else{
		        $IP = $_SERVER["REMOTE_ADDR"];
		        $hostname = @gethostbyaddr($_SERVER["REMOTE_ADDR"]);
			$ipAddress = $IP;
		} 
	}
	$urlRequested = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' );
    	$referrer = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
    	$userAgent = (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
    	$language = (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? attribute_escape($_SERVER['HTTP_ACCEPT_LANGUAGE']) : '');
	$current_user = wp_get_current_user();
	$logged_user = $current_user->user_login;
	$comment_user = utf8_encode($_COOKIE['comment_author_'.COOKIEHASH]);
   
	$timestamp  = wassup_get_time(); //Add a timestamp to visit... 

	//#####Start recording visit....
	//## wassup is activated and IP not on exclusion list... 
	if ($wassup_settings['wassup_active'] == 1) {	//(moved)
	if (empty($wassup_settings['wassup_exclude']) ||
	     strstr($wassup_settings['wassup_exclude'],$ipAddress) == FALSE) {

	//### Exclude requests for themes, plugins, and favicon from recordings
	if (stristr($urlRequested,"favicon.ico") === FALSE) {		//moved
	if (stristr($urlRequested,"/wp-content/plugins") === FALSE || stristr($urlRequested,"forum") !== FALSE ) {	//moved and modified to allow forum requests
	if (stristr($urlRequested,"/wp-content/themes") === FALSE || stristr($urlRequested,"comment") !== FALSE ) {	//moved and modified to allow comment requests

		//##### Extract useful visit information from http header..
		$dip = &new Detector("", $userAgent);
		$browser =  $dip->browser." ".$dip->browser_version;
		$os = $dip->os." ".$dip->os_version;		
		if ($os != "" OR $browser != "") { 
			$bot=wGetSpider($userAgent);
			if (is_array($bot)) {
				$spider = $bot[0];
				$feed = $bot[1];
			} else {
				$spider = trim($bot);
			}
		}
		//#I prefer to see os/browser info. for spiders/bots.
		//if ($spider != '') { $os=''; $browser=''; }
		
	//# More recording exclusion controls (moved to avoid unneeded spam testing)
	if ($wassup_settings['wassup_loggedin'] == 1 || !is_user_logged_in() ) {
	if ($wassup_settings['wassup_spider'] == 1 || $spider == '') {
	if ($wassup_settings['wassup_attack'] == 1 || stristr($userAgent,"libwww-perl") === FALSE ) {
	
	//#===================================================
	//###Start visitor tracking with "session"...
	//
	//#create a temporary id for this visit from a combination of 
	//#  date/hour/min/ip/spider/browser/os. It is not unique so 
	//#  that multiple visits from the same ip/userAgent within a 
	//#  10 minute-period, can be tracked as such, even when 
	//#  session/cookies is disabled. An md5 encoded version of 
	//#  this id is saved in a session/cookie as "wassup_id".
	$temp_id = sprintf("%-032.32s",str_replace(array(" ","/",".","\"","'","\\","\$","-","&","+","_","\;","\,","\>","\<",":","#","*","%","http","\)","\(",), '', substr(date('YmdHi'),0,11).$ipAddress.$spider.$browser.$os.$userAgent));
	$wassup_id = "";
	$session_timeout = 1;
	$dup_urlrequest=0;
	//
	//### Check if this is an ongoing visit or a new hit...
	//# Test for valid savepath directory before session_start()
	//#   Note: a read-only savepath directory can cause errors here.
	if (!empty($wassup_settings['wassup_savepath'])) {
		$sessionpath = $wassup_settings['wassup_savepath'];
	} else {
		$sessionpath = wGetSessionpath();
	}
	if ( file_exists($sessionpath)) {
	   //#reset sessionpath to value set in options...
	   if ( $sessionpath != wGetSessionpath() ) {
		   session_save_path($sessionpath);
	   }
	   session_start();	//required to use/update $_SESSION
	   //#confirm that session is started...
	   if (isset($_SESSION)) {
	   	if (isset($_SESSION['wassup_id'])) {
	   		$wassup_id = $_SESSION['wassup_id'];
	   		$session_timeout = ((int)$_SESSION['wassup_timer'] - (int)time());
	   		if (isset($_SESSION['spamresult'])) {
	   			$spamresult = $_SESSION['spamresult'];
	   		}
	   		if ( $_SESSION['urlrequest'] == $urlRequested && (($timestamp - (int)$_SESSION['visittime']) < 5)) {
	      			$dup_urlrequest=1;
	      		}
	   	} 
	   	//#reset wassup_id for new visitors or when timer is 0...
	   	if (empty($wassup_id) or $session_timeout < 1) {
	   		//# don't "destroy" old session in case it is
	   		//#  in use elsewhere in wordpress ??..
	   		//if (!empty($wassup_id)) {
	   		//	session_destroy();
	   		//	session_start();
	   		//}
	   		$_SESSION['wassup_id'] = md5($temp_id);
	   		//$_SESSION['wassup_id'] = md5(uniqid(rand(), true));
	   		//#timeout session after 24 minutes
	   		$_SESSION['wassup_timer'] = ((int)time() + 1440);
	   		$dup_urlrequest=0;
	   	}
	   	$wassup_id = $_SESSION['wassup_id'];
	   	if ($dup_urlrequest == 0) {	//for dup checks
	     		$_SESSION['visittime'] = $timestamp;	//for dup checks
	   		$_SESSION['urlrequest'] = $urlRequested;
	   	}
	   	//#SID is empty when session uses cookies...
	   	//if (defined('SID') && !empty(SID)) {
	   	//	//#manually add SID to url_rewriter when trans-sid 
	   	//	//#  is disabled (how to test for this???)...
	   	//	output_add_rewrite_var(session_name(), htmlspecialchars(session_id()));
	   	//}
	   	@session_write_close(); /* close session and commit changes*/

	   } elseif (isset($_COOKIE['wassup_id'])) {
	   	$wassup_id = $_COOKIE['wassup_id'];
	   } 
	} elseif (isset($_COOKIE['wassup_id'])) {
	   $wassup_id = $_COOKIE['wassup_id'];
	} 
	//#create cookie when bad session_savepath or when "session" is not available
	if (empty($wassup_id)) {
		//$wassup_id = md5(uniqid(rand(), true));
		$wassup_id = md5($temp_id);
		$url = parse_url(get_option('home'));
		setcookie('wassup_id', $wassup_id, wassup_get_time()+1440, $url['path'] . '/');
	}
	//#End session/cookie section
	//#===================================================

	//### Exclude duplicates...
	if ($dup_urlrequest == 0) {	//#dup checked only with sessions

	   //### Extract useful visit information from http header...
	   $language = @explode("-", $language);
	   $language = @explode(",", $language[1]);
	   $language = @explode(";", $language[0]);

	   list($searchengine,$search_phrase)=explode("|",wGetSE($referrer));
	   $se=seReferer($referrer);
	   if ($search_phrase != '')  {
	   	if (stristr($searchengine,"images")) {
	   		// ATTENTION Position retrieved by referer in Google Images is 
	   		// the Position number of image NOT the number of items in the page like web search
	   		$searchpage=$se['Pos'];
	   		$searchcountry = explode(".", $se['Se']);
	   	} else {
	   		$searchpage=($se['Pos']/10+1);
	   		$searchcountry = explode(".", $se['Se']);
	   	}
	   	if ($searchcountry[3] != '' ) {
	   		$searchengine .= " ".strtoupper($searchcountry[3]);
	   	} elseif ($searchcountry[2] != '') {
	   		$searchengine .= " ".strtoupper($searchcountry[2]);
	   	}
	   }
	   if ($searchpage == "") {
	   	$searchpage = 0;
	   }

	//### Check for spam...
	$spam = 0;	//a spam default of 0 is required to add record...
	//# some useragents to exclude from spam checking...
	$goodbots = array('Google','Yahoo!', 'SummizeFeedReader'); //omit

	if ( $wassup_settings['wassup_spamcheck'] == 1 ) { 
	//
	//# No duplicate spam testing in same session unless there 
	//#  is a forum page request or comment...
	if (isset($spamresult) && stristr($urlRequested,"comment") === FALSE && stristr($urlRequested,"forum") === FALSE && empty($comment_user) && empty($_POST['comment'])) { 
	   	$spam = $spamresult;

	//# No spam check on known bots (google, yahoo,...) unless
	//#  there is a comment or forum page request...
	} elseif ( empty($spider) || array_search($spider,$goodbots) === FALSE || stristr($urlRequested,"comment") !== FALSE || stristr($urlRequested,"forum") !== FALSE  || !empty($comment_user) ) { 
	   	
	   //#first check for referrer spam (faster, if positive)
	   //#...but skip when referrer is own blog ($siteurl/$wpurl)
	   if (!empty($referrer)) {
	   if (!stristr($referrer,$wpurl) && !stristr($referrer,$siteurl)) {
	   	// Do a control if it is Referrer Spam
	   	if (wGetSpamRef($referrer) == 1) { $spam = 2; }
	   }
	   }

	   //#lastly check for comment spammers using Akismet API
	   // Start Akismet integration to prevent spam records
	   $akismet_key = get_option('wordpress_api_key');
	   if (!empty($akismet_key) && ($spam == 0 || !empty($comment_user)) || is_feed()) { 
		$comment_user_email = utf8_encode($_COOKIE['comment_author_email_'.COOKIEHASH]);
		$comment_user_url = utf8_encode($_COOKIE['comment_author_url_'.COOKIEHASH]);
		include(dirname(__FILE__).'/lib/akismet.class.php');

		// load array with comment data 
		$Acomment = array( 
			'author' => $comment_user, 
			'email' => $comment_user_email, 
			'website' => $comment_user_url, 
			'body' => $_POST["comment"], 
			'permalink' => $urlRequested, 
			'user_ip' => $ipAddress,
			'user_agent' => $userAgent
		);
		
		// instantiate an instance of the class 
		$akismet = new Akismet($wpurl, $akismet_key, $Acomment);

                // Check if it's spam
	        if ( $akismet->isSpam() ) {
        		$spam = 1;
		}
		// test for errors
		// no need for error checks...spam=0 already set by default
		//if($akismet->errorsExist()) {
		// returns true if any errors exist 
			//if($akismet->isError('AKISMET_INVALID_KEY')) { 
                        //	$spam = 0;
			//} elseif($akismet->isError('AKISMET_RESPONSE_FAILED')) { 
                        //	$spam = 0;
			//} elseif($akismet->isError('AKISMET_SERVER_NOT_FOUND')) { 
                        //	$spam = 0;
			//} 
		//}
	   //end if akismet_key
	   } else {	
	   	//#no akismet key...check for known spammers using 
	   	//#  wGetSpamRef() with $hostname in place of 
		//#  $referrer...
	   	if ( $spam == 0) {
	   		if (!empty($hostname) && $hostname != "unknown") {
	      		if (wGetSpamRef($hostname) == 1) { $spam = 1; }
	   		}
	   	}
	   } //end else akismet_key

	   // #save spam results in session...
	   if ( file_exists($sessionpath)) {
	      	@session_start(); //required to access $_SESSION
	      	$_SESSION['spamresult'] = $spam;
	      	@session_write_close(); 
	   } 

	   } //end else $spamresult
	   } //end if wassup_spamcheck

	   // Personally used to debug
	   if ($current_user->user_email == "michele@befree.it") {
	   }

	   //### Record visit in wassup table...
	   //## Final exclusion control is spam...
           if ($spam == 0 OR ($wassup_settings['wassup_spam'] == 1 AND $spam == 1) OR ($wassup_settings['wassup_refspam'] == 1 AND $spam == 2)) {

		$insert = $wpdb->query("INSERT INTO $table_name (wassup_id, timestamp, ip, hostname, urlrequested, agent, referrer, search, searchpage, os, browser, language, screen_res, searchengine, spider, feed, username, comment_author, spam) 
   	           VALUES (
	   	   '".$wassup_id."',
	   	   '".$timestamp."',
	   	   '".attribute_escape($ipAddress)."',
	   	   '".attribute_escape($hostname)."',
	   	   '".attribute_escape($urlRequested)."', 
	   	   '".attribute_escape($userAgent)."',
	   	   '".attribute_escape($referrer)."',
	   	   '".$search_phrase."',
	   	   '".$searchpage."', 
	   	   '".$os."', 
	   	   '".$browser."', 
	   	   '".$language[0]."', 
	   	   '".$screen_res."', 
	   	   '".$searchengine."', 
	   	   '".$spider."', 
	   	   '".$feed."', 
	   	   '".attribute_escape($logged_user)."', 
	   	   '".attribute_escape($comment_user)."',
	   	   '".$spam."')"
	   	   );

	} //end if wassup_spam
	} //end if dup_urlrequest == 0

	} //end if wassup_attack
	} //end if wassup_spider
	} //end if wassup_loggedin

	} //end if !themes
	} //end if !plugins
	} //end if !favicon

	//### Purge old records from wassup table
	//automatic database cleanup of old records...
	if ($wassup_settings['delete_auto'] != "") {
	   // do purge every few visits to keep wassup fast...
	   if ( ((int)$timestamp)%5 == 0 ) {
	   	//use visit timestamp instead of current time for
	   	//  delete parameter
	   	//$to_date = wassup_get_time();
	   	$from_date = strtotime($wassup_settings['delete_auto'], $timestamp);
	      	if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name AND $wpdb->get_var("SELECT COUNT(id) FROM $table_name WHERE timestamp<'$from_date'") > 0) {
	      		$wpdb->query("DELETE FROM $table_name WHERE timestamp<'$from_date'");
	      		$wpdb->query("OPTIMIZE TABLE $table_name");
	      	}
	   }
	} //end if delete_auto

	} //end if wassup_exclude
	} //end if wassup_active
	} //end if !is_admin
	
	//### Notify admin if alert is set and wassup table > alert
	if ($wassup_settings['wassup_remind_flag'] == 1) {
	   // check database size every few visits to keep wassup fast...
	   if ( (time())%7 == 0 ) {
		$table_status = $wpdb->get_results("SHOW TABLE STATUS LIKE '$table_name'");
		foreach ($table_status as $fstatus) {
			$data_lenght = $fstatus->Data_length;
		}
		$tusage = ($data_lenght/1024/1024);
		if ($tusage > $wassup_settings['wassup_remind_mb']) {
			$recipient = get_bloginfo('admin_email');
			$sender = get_bloginfo('name').' <wassup_noreply@'.parse_url(get_bloginfo('siteurl'),PHP_URL_HOST).'>';
			$subject = "[ALERT] WassUp Plugin table has reached maximum size!";
			$message = "Hi,\nyou have received this email because your WassUp Database table at your Wordpress blog (".get_bloginfo('url').") had reached the maximum value you set in the options menu (".$wassup_settings['wassup_remind_mb']." Mb).\n\nThis is only a reminder, please take the actions you want in the WassUp options menu (".get_bloginfo('url')."/wp-admin/admin.php?page=wassup-options).\n\nThis alert now will be removed and you will be able to set a new one.\n\nThank you for using WassUp plugin. Check if there is a new version available here: http://wordpress.org/extend/plugins/wassup/\n\nHave a nice day!";
			mail($recipient, $subject, $message, "From: $sender");
			$wassup_settings['wassup_remind_flag'] = 2;
			update_option('wassup_settings', $wassup_settings);

		}
	   }
	} //if wassup_remind_flag
} //end function wassupAppend()

function wGetQueryPairs($url){
	$parsed_url = parse_url($url);
	$tab=parse_url($url);
	$host = $tab['host'];
	if(key_exists("query",$tab)){
	 $query=$tab["query"];
	 return explode("&",$query);
	} else {
	 return null;
	}
}

function array_search_extended($file,$str_search)
{
foreach($file as $key => $line)
{
       if (strpos($line, $str_search)!== FALSE)
       {
              return $key;
       }
}
return false;
}

function seReferer($ref = false){
    $SeReferer = (is_string($ref) ? $ref : mb_convert_encoding(strip_tags($_SERVER['HTTP_REFERER']), "HTML-ENTITIES", "auto"));
    if( //Check against Google, Yahoo, MSN, Ask and others
        preg_match(
        "/[&\?](prev|q|p|w|searchfor|as_q|as_epq|s|query)=([^&]+)/i",
        $SeReferer,$pcs)
    ){
        if(preg_match("/https?:\/\/([^\/]+)\//i",$SeReferer,$SeDomain)){
            $SeDomain    = trim(strtolower($SeDomain[1]));
            $SeQuery    = $pcs[2];
            if(preg_match("/[&\?](start|b|first|stq)=([0-9]*)/i",$SeReferer,$pcs)){
                $SePos    = (int)trim($pcs[2]);
            }
        }
    }
    if(!isset($SeQuery)){
        if( //Check against DogPile
            preg_match(
            "/\/search\/web\/([^\/]+)\//i",
            $SeReferer,$pcs)
        ){
            if(preg_match("/https?:\/\/([^\/]+)\//i",$SeReferer,$SeDomain)){
                $SeDomain    = trim(strtolower($SeDomain[1]));
                $SeQuery    = $pcs[1];
            }
        }
    }
    // We Do Not have a query
    if(!isset($SeQuery)){ return false; }
    $OldQ=$SeQuery;
    $SeQuery=urldecode($SeQuery);
    // The Multiple URLDecode Trick to fix DogPile %XXXX Encodes
    while($SeQuery != $OldQ){
        $OldQ=$SeQuery; $SeQuery=urldecode($SeQuery);
    }
    //-- We have a query
    return array(
        "Se"=>$SeDomain,
        "Query"=>$SeQuery,
        "Pos"=>(int)$SePos,
        "Referer"=>$SeReferer
    );
}

function wGetSE($referrer = null){
	$key = null;
	$lines = array("Alice|search.alice.it|qs|","Google|www.google.|q|","Google Groups|groups.google.|q|", "Google Images|images.google.|prev|", "Yahoo|search.yahoo.com|p|", 
			"Virgilio|search.virgilio.it|qs|","Arianna|arianna.libero.it|query|","Altavista|.altavista.com|q|","Kataweb|kataweb.it|q|",
			"Il Trovatore|categorie.iltrovatore.it|query|","Il Trovatore|search.iltrovatore.it|q|","2020Search|2020search.c|us|st|pn|1|",
			"abcsearch.com|abcsearch.com|terms|","100Links|100links.supereva.it|q|","Alexa|alexa.com|q|","Alltheweb|alltheweb.com|q|",
			"Aol|.aol.|query|","Aol|aolrecherches.aol.fr|query|","Ask|ask.com|ask|","Ask|ask.com|q|","DMOZ|search.dmoz.org|search|",
			"Dogpile|dogpile.com|q|","Excite|excite.|q|","Godago|.godago.com|keywords|","HotBot|hotbot.*|query|","ixquick|ixquick.com|query|",
			"Lycos|cerca.lycos.it|query|","Lycos|lycos.|q|","Windows Live|search.live.com|q|mkt|","My Search|mysearch.com|searchfor|",
			"My Way|mysearch.myway.com|searchfor|","Metacrawler|metacrawler.|q|","Netscape Search|search.netscape.com|query|","MSN|msn.|q|",
			"Overture|overture.com|Keywords|","Supereva|supereva.it|q|","Teoma|teoma.com|q|","Tiscali|search-dyn.tiscali.|key|","Voil|voila.fr|kw|",
			"Web|web.de|su|","Clarence|search.clarence.com|q|","Gazzetta|search.gazzetta.it|q|","PagineGialle|paginegialle.it|qs|",
			"Jumpy|servizi.mediaset.it|searchWord|","ItaliaPuntoNet|italiapuntonet.net|search|","StartNow|search.startnow.|q|","Search|search.it|srctxt|",
			"Search|search.com|q|");
	foreach($lines as $line_num => $se) {
		list($nome,$url,$key,$lang)=explode("|",$se);
		if(@strpos($referrer,$url)===FALSE) continue;
		// found it!
		// The SE is Google Images
		if ($nome == "Google Images") {
			$variables = wGetQueryPairs($referrer);
			$rightkey = array_search_extended($variables, "images");
			$variables = eregi_replace("prev=/images\?q=", "", urldecode($variables[$rightkey]));
			$variables = explode("&",$variables);
			return ($nome."|".urldecode($variables[0]));
		} else {
			$variables = wGetQueryPairs($referrer);
			$i = count($variables);
			while($i--){
			   $tab=explode("=",$variables[$i]);
			   if($tab[0] == $key){return ($nome."|".urldecode($tab[1]));}
			}
		}
	}
	return null;
}

function wGetSpider($agent = null){
    $agent=str_replace(" ","",$agent);
	$key = null;
	$lines = array("Wordpress Pingback/Trackback|Wordpress|", "Alexa|ia_archiver|","Ask.com/Teoma|AskJeeves/Teoma)|","Biz360|Biz360|","Naver|NaverBot|","Naver|Cowbot|","cURL|curl/|","Google|Googlebot/|",
			"Google|googlebot/|","Google Images|Googlebot-Image|","LookSmart|grub-client|","Yahoo!|slurp@inktomi|","Yahoo!|Yahoo!Slurp|",
			"Yahoo!|MMCrawler|","MSN|msnbot|","AltaVista|Scooter-|","Wget|Wget/1.|","Technorati|Technoratibot|","Moreover|Moreoverbot|",
			"Yahoo FeedSeeker|YahooFeedSeeker|","Java|Java/|","relevantNOISE|www.relevantnoise.com|","Voila|VoilaBot|","IRLIRLbot/|","Snapbot|Snap|",
			"ichiro|ichiro|", "shelob|shelob|", "Google AdSense|Mediapartners-Google|", "Seekbot|HTTPFetcher|", "CommentTracker|CommentTracker|", 
			"Bloglines|bloglines|",	"Italian Blog Rankings|blogbabel", "Ask Jeeves/Teoma|ask|", "Akregator|Akregator|", "NewsGatorOnline|NewsGatorOnline|", "Rojo|rojo|", "FeedTools|feedtools|",
			"Feedfetcher-Google|Feedfetcher-google|", "AideRSS|AideRSS|", "psbot|psbot|", "Ruby|Rfeedfinder|", "everyfeed-spider|everyfeed-spider", "Attentio/Nutch|Attentio", 
			"Megite2.0|Megite.com|", "radianrss|RadianRSS|", "Sitemap Generator|Sitemap Generator|", "Feedshow|Feedshow|", "ABCdatos|ABCdatos|", "Acme.Spider|Due|", "Ahoy!|Ahoy!|", 
			"Alkaline|AlkalineBOT|", "appie|Appie|", "Arachnophilia|Arachnophilia|", "Araneo|Araneo/0.7|", "AraybOt|AraybOt/1.0|", "ArchitextSpider|ArchitextSpider|", 
			"ARIADNE|Due|", "ASpider|ASpider/0.09|", "Atomz.com|Atomz/1.0|", "AURESYS|AURESYS/1.0|", "BackRub|BackRub/*.*|", "BBot|bbot/0.100|", "Big|Big|", "Bjaaland|Bjaaland/0.5|", 
			"BlackWidow|BlackWidow|", "Die|Die|", "Borg-Bot|borg-bot/0.9|", "BoxSeaBot|BoxSeaBot/0.5|", "BSpider|BSpider/1.0|", "CACTVS|CACTVS|", "Calif|Calif/0.6|", 
			"Digimarc|Digimarc|", "Checkbot|Checkbot/x.xx|", "cIeNcIaFiCcIoN.nEt|cIeNcIaFiCcIoN.nEt|", "CMC/0.01|CMC/0.01|", "Combine|combine/0.0|", "ConfuzzledBot|Confuzzledbot/X.X|", 
			"CoolBot|CoolBot|", "Web|root/0.1|", "XYLEME|cosmos/0.3|", "Cusco|Cusco/3.2|", "CyberSpyder|CyberSpyder/2.1|", "CydralSpider|CydralSpider/X.X|", "Desert|DesertRealm.com;|", 
			"DeWeb(c)|Deweb/1.01|", "DienstSpider|dienstspider/1.0|", "Digger|Digger/1.0|", "Digital|DIIbot|", "Direct|grabber|", "DNAbot|DNAbot/1.0|", "DragonBot|DragonBot/1.0|", 
			"DWCP|DWCP/2.0|", "e-collector|LWP::|", "EIT|EIT-Link-Verifier-Robot/0.2|", "Emacs-w3|Emacs-w3/v[0-9\.]+|", "ananzi|EMC|", "esculapio|esculapio/1.1|", "Esther|esther|", 
			"Evliya|Evliya|", "nzexplorer|explorersearch|", "FastCrawler|FastCrawler|", "Dynamics|(compatible:|", "Felix|FelixIDE/1.0|", "Wild|Hazel's|", "FetchRover|ESIRover|", 
			"fido|fido/0.9|", "KIT-Fireball|KIT-Fireball/2.0|", "Fish|Fish-Search-Robot|", "Fouineur|Fouineur|", "Robot|Robot|", "Freecrawl|Freecrawl|", "FunnelWeb|FunnelWeb-1.0|", 
			"gammaSpider|gammaSpider|", "gazz|gazz/1.0|", "GCreep|gcreep/1.0|", "GetURL|GetURL.rexx|", "Golem|Golem/1.1|", "Googlebot|Googlebot/2.X|", "Gromit|Gromit/1.0|", 
			"Northern|Gulliver/1.1|", "Gulper|Gulper|", "Harvest|yes|", "havIndex|havIndex/X.xx[bxx]|", "HI|AITCSRobot/1.1|", "Hometown|Hometown|", "Wired|wired-digital-newsbot/1.5|", 
			"ht://Dig|htdig/3.1.0b2|", "HTMLgobble|HTMLgobble|", "Hyper-Decontextualizer|Hyper|", "iajaBot|iajaBot/0.1|", "IBM_Planetwide|IBM_Planetwide,|", 
			"Popular|gestaltIconoclast/1.0|", "Ingrid|INGRID/0.1|", "Imagelock|Imagelock|", "IncyWincy|IncyWincy/1.0b1|", "Informant|Informant|", "InfoSeek|InfoSeek|", 
			"Infoseek|Infoseek|", "InfoSpiders|InfoSpiders/0.1|", "Inspector|inspectorwww/1.0|", "IntelliAgent|'IAGENT/1.0'|", "Israeli-search|IsraeliSearch/1.0|", "JBot|JBot|", 
			"JCrawler|JCrawler/0.2|", "AskJeeves|Askjeeves|", "JoBo|JoBo|", "Jobot|Jobot/0.1alpha|", "JoeBot|JoeBot/x.x,|", "The|JubiiRobot/version#|", "JumpStation|jumpstation|", 
			"image.kapsi.net|image.kapsi.net/1.0|", "Katipo|Katipo/1.0|", "KDD-Explorer|KDD-Explorer/0.1|", "KO_Yappo_Robot|KO_Yappo_Robot/1.0.4(http://yappo.com/info/robot.html)|", 
			"LabelGrabber|LabelGrab/1.1|", "larbin|larbin|", "legs|legs|", "Link|Linkidator/0.93|", "LinkWalker|LinkWalker|", "logo.gif|logo.gif|", "Lycos|Lycos/x.x|", 
			"Magpie|Magpie/1.0|", "marvin/infoseek|marvin/infoseek|", "Mattie|M/3.8|", "MediaFox|MediaFox/x.y|", "NEC-MeshExplorer|NEC-MeshExplorer|", "MindCrawler|MindCrawler|", 
			"mnoGoSearch|UdmSearch|", "MOMspider|MOMspider/1.00|", "Monster|Monster/vX.X.X|", "Motor|Motor/0.2|", "MSNBot|MSNBOT/0.1|", "Muninn|Muninn/0.1|", 
			"Muscat|MuscatFerret/<version>|", "Mwd.Search|MwdSearch/0.1|", "Internet|User-Agent:|", "NDSpider|NDSpider/1.5|", "NetCarta|NetCarta|", "NetMechanic|NetMechanic|", 
			"NetScoop|NetScoop/1.0|", "newscan-online|newscan-online/1.1|", "NHSE|NHSEWalker/3.0|", "Nomad|Nomad-V2.x|", "ObjectsSearch|ObjectsSearch/0.01|", "Occam|Occam/1.0|", 
			"HKU|HKU|", "Openfind|Openfind|", "Orb|Orbsearch/1.0|", "Pack|PackRat/1.0|", "ParaSite|ParaSite/0.21|", "Patric|Patric/0.01a|", "PerlCrawler|PerlCrawler/1.0|", 
			"Phantom|Duppies|", "PhpDig|phpdig/x.x.x|", "PiltdownMan|PiltdownMan/1.0|", "Pimptrain.com's|Pimptrain|", "Pioneer|Pioneer|", "Portal|PortalJuice.com/4.0|", 
			"PGP|PGP-KA/1.2|", "PlumtreeWebAccessor|PlumtreeWebAccessor/0.9|", "Poppi|Poppi/1.0|", "PortalB|PortalBSpider/1.0|", "psbot|psbot/0.X|", "GetterroboPlus|straight|", 
			"Raven|Raven-v2|", "Resume|Resume|", "RoadHouse|RHCS/1.0a|", "RixBot|RixBot|", "Road|Road|", "Robbie|Robbie/0.1|", "ComputingSite|ComputingSite|", "RoboCrawl|RoboCrawl|", 
			"RoboFox|Robofox|", "Robozilla|Robozilla/1.0|", "Roverbot|Roverbot|", "RuLeS|RuLeS/1.0|", "SafetyNet|SafetyNet|", "Scooter|Scooter/2.0|", "Search.Aus-AU.COM|not|", 
			"Sleek|Sleek|", "SearchProcess|searchprocess/0.9|", "Senrigan|Senrigan/xxxxxx|", "SG-Scout|SG-Scout|", "Shai'Hulud|Shai'Hulud|", "Simmany|SimBot/1.0|", "SBIder|Site|", 
			"SiteTech-Rover|SiteTech-Rover|", "Skymob.com|aWapClient|", "Inktomi|Slurp/2.0|", "Smart|ESISmartSpider/2.0|", "Snooper|Snooper/b97_01|", "Solbot|Solbot/1.0|", 
			"Spider|Spider|", "spider_monkey|mouse.house/7.1|", "SpiderBot|SpiderBot/1.0|", "Spiderline|spiderline/3.1.3|", "SpiderView(tm)|SpiderView|", "Site|ssearcher100|", 
			"Suke|suke/*.*|", "suntek|suntek/1.0|", "Sygol|http://www.sygol.com|", "TACH|TACH|", "Tarantula|Tarantula/1.0|", "tarspider|tarspider|", "Tcl|dlw3robot/x.y|", 
			"TechBOT|TechBOT|", "Templeton|Templeton/{version}|", "TitIn|TitIn/0.2|", "TITAN|TITAN/0.1|", "UCSD|UCSD-Crawler|", "UdmSearch|UdmSearch/2.1.1|", "UptimeBot|uptimebot|", 
			"URL|urlck/1.2.3|", "URL|URL|", "Valkyrie|Valkyrie/1.0|", "Verticrawl|Verticrawlbot|", "Victoria|Victoria/1.0|", "vision-search|vision-search/3.0'|", 
			"void-bot|void-bot/0.1|", "Voyager|Voyager/0.0|", "VWbot|VWbot_K/4.2|", "The|w3index|", "W3M2|W3M2/x.xxx|", "WallPaper|CrawlPaper/n.n.n|", "the|WWWWanderer|", 
			"w@pSpider|w@pSpider/xxx|", "WebCatcher|WebCatcher/1.0|", "WebCopy|WebCopy/(version)|", "webfetcher|WebFetcher/0.8,|", "Webinator|weblayers|", "weblayers/0.0|WebLinker|", 
			"WebLinker/0.0|WebMirror|", "Digimarc|WebReaper|", "WebReaper|webs|", "webs@recruit.co.jp|Websnarf|", "WebVac|webvac/1.0|", "webwalk|webwalk|", 
			"WebWalker|WebWalker/1.10|", "WebWatch|WebWatch|", "Wget|Wget/1.4.0|", "whatUseek|whatUseek_winona/3.0|", "Weblog|wlm-1.1|", "w3mir|w3mir|", "WebStolperer|WOLP/1.0|", 
			"WWWC|WWWC/0.25|", "WebZinger|none|", "XGET|XGET/0.7|", "Nederland.zoek|Nederland.zoek|", "boitho.com|boitho.com|", "GreatNews|GreatNews|", "AlestiFeedBot|AlestiFeedBot|", 
			"SummizeFeedReader|SummizeFeedReader|", "FeedBurner|FeedBurner|", "lilina|Lilina|", "BuzzTracker|BuzzTracker|", "kinjabot|kinjabot|", "Krugle|Krugle|", 
			"libwww-perl|libwww-perl|", "Jakarta|Jakarta|", "VadixBot|VadixBot|", "Google Desktop|Google Desktop|", "BlogsNowBot|BlogsNowBot|", "Feedster|Feedster|",
			"WebCopier|WebCopier|", "MSRBOT|MSRBOT|", "Charlotte|Charlotte|", "wp-autoblogSimplePie|SimplePie|", "wikioblogs|wikioblogs|", "Wells Search II|Wells Search II|", 
			"BlogsNowBot|BlogsNowBot|", "NG/2.0|NG/2.0|", "BlogBridge|BlogBridge|", "Drupal|Drupal|", "WebGenBot|WebGenBot|", "CazoodleBot|CazoodleBot|", "MJ12bot|MJ12bot|", 
			"Feedreader|Feedreader|", "Strategic Board Bot|Strategic Board Bot|", "LiteFinder|LiteFinder|", "SurveyBot|SurveyBot|", "Teemer|Teemer|", "NetNewsWire|NetNewsWire|", 
			"disco/Nutch|disco/Nutch", "StackRambler|StackRambler|", "MagpieRSS|MagpieRSS|", "WebAlta|WebAlta|", "NewsAlloy|NewsAlloy|",
			"WikioFeedBot|WikioFeedBot|", "Strategic Board Bot |Strategic Board Bot |", "Mail.ru|Mail.ru|", "OpiDig|OpiDig|", "webcollage|webcollage|", 
			"R6_FeedFetcher|R6_FeedFetcher|", "UniversalFeedParser|UniversalFeedParser|", "Syndic8|Syndic8|", "BlogBot|BlogBot|", "W3C_Validator|W3C_Validator|",
			"Runnk RSS aggregator|Runnk|", "RssBandit|RssBandit|");
	foreach($lines as $line_num => $spider) {
		list($nome,$key)=explode("|",$spider);
		if(@strpos(strtolower($agent),strtolower($key))===FALSE) continue;
		if (@strpos(strtolower($agent), "subscriber")!== FALSE) {
			preg_match("/([0-9]{1,10})(subscriber)/i", $agent, $subscriber);
			$feed[] = $nome;
			$feed[] = $subscriber[1];
			// It's a feedreader with some subscribers
			return $feed;
		} else {
			// find it!
			return $nome;
		}
	}
	return null;
}

//# Check input, $referrer against a list of known spammers and 
//#   return "1" if match found. 
//#   All comparisons are case-insensistive and uses the faster string 
//#   functions (stristr) instead of "regular expression" functions.
function wGetSpamRef($referrer) {
	$referrer=htmlentities(strip_tags(str_replace(" ","",html_entity_decode($referrer))));
	$badhostfile= dirname(__FILE__).'/badhosts.txt';
        $key = null;
      
	if (empty($referrer)) { return null; }	//nothing to check...

	//#Assume any referrer name similar to "viagra/zanax/.."
	//#  is spam and mark as such...
	$lines = array("cialis","viagra","zanax","phentermine");
	foreach ($lines as $badreferrer) {
		if (stristr($referrer, $badreferrer) !== FALSE) { 
			return 1;
		}
	}
	
	$lines = array("1clickholdem.com", "1ps.biz", "24h.to", "4all-credit.com", "4all-prescription.com", "4u-money.com", "6q.org", "88.to", "always-casino.com",
        "always-credit.com", "andipink.com", "antiquemarketplace.net", "artmedia.com.ru", "asstraffic.com", "at.cx", "available-casino.com", "available-credit.com",
        "available-prescription.com", "base-poker.com", "bayfronthomes.net", "bitlocker.net", "black-poker.com", "blest-money.com", "budgethawaii.net", "bwdow.com",
        "cafexml.com", "cameralover.net", "capillarychromatogr.org", "cash-2u.com", "casino-500.com", "casino-bu.com", "casinos4spain.com", "cheat-elite.com", "clan.ws",
        "computerxchange.com", "conjuratia.com", "credit-4me.com", "credit-dreams.com", "cups.cs.cmu.edu", "de.tc", "dietfacts.com", "doctor-here.com", "doctor-test.com",
        "eu.cx", "fidelityfunding.net", "finance-4all.com", "finestrealty.net", "fortexasholdem.com", "freewarechannel.de", "gb.com", "golfshoot.com", "great-finance.com",
        "great-money.com", "health-livening.com", "here.ws", "hu.tc", "iepills.com", "ihomebroker.com", "including-poker.com", "internettexashold.com", "isdrin.de",
        "iwebtool.com", "jaja-jak-globusy.com", "jobruler.com", "jpe.com", "js4.de", "just-pharmacy.com", "learnhowtoplay.com", "mine-betting.com", "new-doctor.com",
        "nonews.ru", "now-cash.com", "online-pills.us", "online.cx", "only-casino.com", "ourtexasholdem.com", "p.cx", "partyshopcentral.com", "petsellers.net",
        "pharmacy-here.com", "pills-only.com", "plenty-cash.com", "poker-check.com", "poker-spanish.com", "pressemitteilung.ws", "quality-poker.com", "reale-amateure.com",
        "realtorx2.com", "rulen.de", "shop.tc", "sp.st", "spanish-casino-4u.com", "standard-poker.com", "start.bg", "take-mortgage.com", "texasholdfun.com",
        "the-discount-store.com", "unique-pills.com", "unixlover.com", "us.tc", "useful-pills.com", "vadoptions.com", "vcats.com", "vinsider.com", "vjackpot.com",
        "vmousetrap.com", "vplaymate.com", "vselling.com", "vsymphony.com", "vthought.com", "walnuttownfireco.org", "white-pills.com", "wkelleylucas.com", "yourpsychic.net",
        "mature-lessons.com", "wrongsideoftown.com", "wildpass.com", "collegefuckfest.com", "brutalblowjobs.com", "livemarket.com.ua", "allinternal.com", "asstraffic.com",
        "progressiveupdate.net","dating-s.net","ua-princeton.com","royalfreehost.com", "www.texas-va-loan.com", "jmhic.com", "whvc.net", "vegas-hair.com", "owned.com",
        "sml338.org", "kredite-kredit", "buy-2005.com", "vrajitor.com", "ro7kalbe.com", "ca-america.com", "udcorp.com", "walnuttownfireco.org", "yx-colorweaving.com",
        "terashells.com", "chat-nett.com", "exitq.com", "cxa.de", "sysrem03.com", "pharmacy.info", "guide.info", "drugstore.info","vpshs.com", "vp888.net", "coresat.com",
        "psxtreme.com", "freakycheats.com", "cool-extreme.com", "pervertedtaboo.com", "crescentarian.net", "texas-holdem", "yelucie.com", "poker-online.com",  
        "findwebhostingnow.com", "smsportali.net", "6q.org", "flowersdeliveredquick.com", "trackerom.com", "andrewsaluk.com", "4u.net", "4u.com", "doobu.com", "isacommie.com",
        "musicbox1.com", "roody.com", "zoomgirls.net", "cialis-gl-pills.com", "fickenfetzt.com");
	foreach($lines as $line_num => $spammer) {
                if(stristr($referrer,$spammer) !== FALSE) {
                        // find it!
                        return 1;
                }
        }
	//#check for a customized spammer list...
	if (file_exists($badhostfile)) {
		$lines = file($badhostfile,FILE_IGNORE_NEW_LINES);
		//$lines2 = file($badhostfile,FILE_IGNORE_NEW_LINES);
		//$lines = array_merge($lines, $lines2);

		foreach($lines as $line_num => $spammer) {
			if(stristr($referrer,trim($spammer)) !== FALSE) {
                        // find it!
			return 1;
			}
		}
	}
	return null;
} //end function wGetSpamRef()

//# Get current session_save_path value and return the pathname portion
//#  - Helene D. 1/14/08.
function wGetSessionpath() {
	$sessionpath = session_save_path();
	if (strpos($sessionpath, ";") !== FALSE) {
  	   $sessionpath = substr($sessionpath, strpos($sessionpath, ";")+1);
	}
	return rtrim($sessionpath,"/");
}

function export_wassup() {
global $wpdb, $table_name;
$table_name = $wpdb->prefix . "wassup";
$filename = 'wassup.' . gmdate('Y-m-d') . '.sql';

//# check for records before exporting...
$numrecords = $wpdb->get_var("SELECT COUNT(wassup_id) FROM $table_name");
if ( $numrecords > 0 ) {
	//TODO: use compressed file transfer when zlib available...
	do_action('export_wassup');
	header('Content-Description: File Transfer');
	header("Content-Disposition: attachment; filename=$filename");
	header('Content-Type: text/plain charset=' . get_option('blog_charset'), true);

	// Function is below
	backup_table($table_name);

	die(); 	//sends output and flushes buffer
} //end if numrecords > 0
} //end function export_wassup()

/**
* Taken partially from wp-db-backup plugin
* Alain Wolf, Zurich - Switzerland
* Website: http://www.ilfilosofo.com/blog/wp-db-backup/
* @param string $table
* @param string $segment
* @return void
*/
function backup_table($table, $segment = 'none') {
	global $wpdb;
	define('ROWS_PER_SEGMENT', 100);

	$table_structure = $wpdb->get_results("DESCRIBE $table");
	if (! $table_structure) {
		$this->error(__('Error getting table details','wassup') . ": $table");
		return FALSE;
	}

	if(($segment == 'none') || ($segment == 0)) {
		// Add SQL statement to drop existing table
		$sql .= "\n\n";
		$sql .= "#\n";
		$sql .= "# " . sprintf(__('Delete any existing table %s','wassup'),$table) . "\n";
		$sql .= "#\n";
		$sql .= "\n";
		$sql .= "#\n";
		$sql .= "# Uncomment if you need\n";
		$sql .= "#DROP TABLE IF EXISTS " . $table . ";\n";
		
		// Table structure
		// Comment in SQL-file
		$sql .= "\n\n";
		$sql .= "#\n";
		$sql .= "# " . sprintf(__('Table structure of table %s','wassup'),$table) . "\n";
		$sql .= "#\n";
		$sql .= "\n";
		$sql .= "#\n";
		$sql .= "# Uncomment if you need\n";
		
		$create_table = $wpdb->get_results("SHOW CREATE TABLE $table", ARRAY_N);
		if (FALSE === $create_table) {
			$err_msg = sprintf(__('Error with SHOW CREATE TABLE for %s.','wassup'), $table);
			print $err_msg;
			$sql .= "#\n# $err_msg\n#\n";
		}
		$sql .= $create_table[0][1] . ' ;';
		
		if (FALSE === $table_structure) {
			$err_msg = sprintf(__('Error getting table structure of %s','wassup'), $table);
			print $err_msg;
			$sql .= "#\n# $err_msg\n#\n";
		}
	
		// Comment in SQL-file
		$sql .= "\n\n";
		$sql .= "#\n";
		$sql .= '# ' . sprintf(__('Data contents of table %s','wassup'),$table) . "\n";
		$sql .= "#\n";
	}
	
	if(($segment == 'none') || ($segment >= 0)) {
		$defs = array();
		$ints = array();
		foreach ($table_structure as $struct) {
			if ( (0 === strpos($struct->Type, 'tinyint')) ||
				(0 === strpos(strtolower($struct->Type), 'smallint')) ||
				(0 === strpos(strtolower($struct->Type), 'mediumint')) ||
				(0 === strpos(strtolower($struct->Type), 'int')) ||
				(0 === strpos(strtolower($struct->Type), 'bigint')) ||
				(0 === strpos(strtolower($struct->Type), 'timestamp')) ) {
					$defs[strtolower($struct->Field)] = $struct->Default;
					$ints[strtolower($struct->Field)] = "1";
			}
		}
		
		// Batch by $row_inc
		
		if($segment == 'none') {
			$row_start = 0;
			$row_inc = ROWS_PER_SEGMENT;
		} else {
			$row_start = $segment * ROWS_PER_SEGMENT;
			$row_inc = ROWS_PER_SEGMENT;
		}
		
		do {	
			if ( !ini_get('safe_mode')) @set_time_limit(15*60);
			$table_data = $wpdb->get_results("SELECT * FROM $table LIMIT {$row_start}, {$row_inc}", ARRAY_A);

			$entries = 'INSERT INTO ' . $table . ' VALUES (';	
			//    \x08\\x09, not required
			$search = array("\x00", "\x0a", "\x0d", "\x1a");
			$replace = array('\0', '\n', '\r', '\Z');
			if($table_data) {
				foreach ($table_data as $row) {
					$values = array();
					foreach ($row as $key => $value) {
						if ($ints[strtolower($key)]) {
							// make sure there are no blank spots in the insert syntax,
							// yet try to avoid quotation marks around integers
							$value = ( '' === $value) ? $defs[strtolower($key)] : $value;
							$values[] = ( '' === $value ) ? "''" : $value;
						} else {
							$values[] = "'" . str_replace($search, $replace, addslashes($value)) . "'";
						}
					}
					$sql .= " \n" . $entries . implode(', ', $values) . ') ;';
				}
				$row_start += $row_inc;
			}
		} while((count($table_data) > 0) and ($segment=='none'));
	}
	
	if(($segment == 'none') || ($segment < 0)) {
		// Create footer/closing comment in SQL-file
		$sql .= "\n";
		$sql .= "#\n";
		$sql .= "# " . sprintf(__('End of data contents of table %s','wp-db-backup'),$table) . "\n";
		$sql .= "# --------------------------------------------------------\n";
		$sql .= "\n";
	}
	print $sql;
} // end backup_table()

function wassup_widget_init() {

        if ( !function_exists('register_sidebar_widget') )
                return;

function wassup_widget($wargs) {
	global $wpdb;
	extract($wargs);
	$wassup_settings = get_option('wassup_settings');
	$wpurl =  get_bloginfo('wpurl');
	$siteurl =  get_bloginfo('siteurl');
	if ($wassup_settings['wassup_widget_title'] != "") $title = $wassup_settings['wassup_widget_title']; else $title = "Visitors Online";
	if ($wassup_settings['wassup_widget_ulclass'] != "") $ulclass = $wassup_settings['wassup_widget_ulclass']; else $ulclass = "links";
	if ($wassup_settings['wassup_widget_chars'] != "") $chars = $wassup_settings['wassup_widget_chars']; else $chars = "18";
	if ($wassup_settings['wassup_widget_searchlimit'] != "") $searchlimit = $wassup_settings['wassup_widget_searchlimit']; else $searchlimit = "5";
	if ($wassup_settings['wassup_widget_reflimit'] != "") $reflimit = $wassup_settings['wassup_widget_reflimit']; else $reflimit = "5";
	if ($wassup_settings['wassup_widget_topbrlimit'] != "") $topbrlimit = $wassup_settings['wassup_widget_topbrlimit']; else $topbrlimit = "5";
	if ($wassup_settings['wassup_widget_toposlimit'] != "") $toposlimit = $wassup_settings['wassup_widget_toposlimit']; else $toposlimit = "5";
	$table_name = $wpdb->prefix . "wassup";
	$to_date = wassup_get_time();
	$from_date = strtotime('-3 minutes', $to_date);

        print $before_widget;

	// Widget TOP Searches
	if ($wassup_settings['wassup_widget_search'] == 1) {
	$query_det = $wpdb->get_results("SELECT search, referrer FROM $table_name WHERE search!='' GROUP BY search ORDER BY timestamp DESC LIMIT $searchlimit");
	if (count($query_det) > 0) {
		print "$before_title Last searched terms $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_det as $sref) {
			print "<li>- <a href='".htmlentities($sref->referrer)."' target='_BLANK'>".stringShortener($sref->search, $chars)."</a></li>";
		}
		print "</ul>";
	}
	}

	// Widget TOP Referers
	if ($wassup_settings['wassup_widget_ref'] == 1) {
	$query_ref = $wpdb->get_results("SELECT referrer FROM $table_name WHERE searchengine='' AND referrer!='' AND referrer NOT LIKE '$wpurl%' GROUP BY referrer ORDER BY timestamp DESC LIMIT $reflimit");
	if (count($query_ref) > 0) {
		print "$before_title Last referers $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_ref as $eref) {
			print "<li>- <a href='".htmlentities($eref->referrer)."' target='_BLANK'>".stringShortener(eregi_replace("http://", "", htmlentities($eref->referrer)), $chars)."</a></li>";
		}
		print "</ul>";
	}
	}

	// Widget TOP Browsers
	if ($wassup_settings['wassup_widget_topbr'] == 1) {
	$query_topbr = $wpdb->get_results("SELECT count(browser) as top_browser, browser FROM $table_name WHERE browser!='' AND browser NOT LIKE '%N/A%' GROUP BY browser ORDER BY top_browser DESC LIMIT $topbrlimit");
	if (count($query_topbr) > 0) {
		print "$before_title Top Browsers $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_topbr as $etopbr) {
			print "<li>- ".stringShortener($etopbr->browser, $chars)."</li>";
		}
		print "</ul>";
	}
	}

	// Widget TOP Oses
	if ($wassup_settings['wassup_widget_topos'] == 1) {
	$query_topos = $wpdb->get_results("SELECT count(os) as top_os, os FROM $table_name WHERE os!='' AND os NOT LIKE '%N/A%' GROUP BY os ORDER BY top_os DESC LIMIT $toposlimit");
	if (count($query_topos) > 0) {
		print "$before_title Top OS $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_topos as $etopos) {
			print "<li>- ".stringShortener($etopos->os, $chars)."</li>";
		}
		print "</ul>";
	}
	}

	// Widget Visitors Online
	print $before_title . $title . $after_title;
	print "<ul class='$ulclass'>";
	$currenttot = $wpdb->get_var("SELECT COUNT(DISTINCT wassup_id) as currenttot FROM $table_name WHERE timestamp BETWEEN $from_date AND $to_date ");
	$currentlogged = $wpdb->get_var("SELECT COUNT(DISTINCT wassup_id) as currentlogged FROM $table_name WHERE username!=''AND timestamp BETWEEN $from_date AND $to_date");
	$currentauth = $wpdb->get_var("SELECT COUNT(DISTINCT wassup_id) as currentauth FROM $table_name WHERE comment_author!='' AND username=''AND timestamp BETWEEN $from_date AND $to_date");
	if ((int)$currenttot < 10) $currenttot = "0".$currenttot;
	print "<li><strong style='padding:0 4px 0 4px;background:#ddd;color:#777'>".$currenttot."</strong> visitor(s) online</li>";
	if ((int)$currentlogged > 0 AND $wassup_settings['wassup_widget_loggedin'] == 1) {
	if ((int)$currentlogged < 10) $currentlogged = "0".$currentlogged;
		print "<li><strong style='padding:0 4px 0 4px;background:#e7f1c8;color:#777'>".$currentlogged."</strong> logged-in user(s)</li>";
	}
	if ((int)$currentauth > 0 AND $wassup_settings['wassup_widget_comauth'] == 1) {
	if ((int)$currentauth < 10) $currentauth = "0".$currentauth;
		print "<li><strong style='padding:0 4px 0 4px;background:#fbf9d3;color:#777'>".$currentauth."</strong> comment author(s)</li>";
	}
	print "<li style='font-size:6pt; color:#bbb;'>powered by <a style='color:#777;' href='http://www.wpwp.org' title='WassUp - Real Time Visitors Tracking'>WassUp</a></li>";
	print "</ul>";
	print $after_widget;
}

function wassup_widget_control() {
	//global $_POST;
	$wassup_settings = get_option('wassup_settings');
	
	if (isset($_POST['submit']))
	{
		$wassup_settings['wassup_widget_title'] = $_POST['wassup_widget_title'];
		$wassup_settings['wassup_widget_ulclass'] = $_POST['wassup_widget_ulclass'];
		$wassup_settings['wassup_widget_chars'] = $_POST['wassup_widget_chars'];
		$wassup_settings['wassup_widget_loggedin'] = $_POST['wassup_widget_loggedin'];
		$wassup_settings['wassup_widget_comauth'] = $_POST['wassup_widget_comauth'];
		$wassup_settings['wassup_widget_search'] = $_POST['wassup_widget_search'];
		$wassup_settings['wassup_widget_searchlimit'] = $_POST['wassup_widget_searchlimit'];
		$wassup_settings['wassup_widget_ref'] = $_POST['wassup_widget_ref'];
		$wassup_settings['wassup_widget_reflimit'] = $_POST['wassup_widget_reflimit'];
		$wassup_settings['wassup_widget_topbr'] = $_POST['wassup_widget_topbr'];
		$wassup_settings['wassup_widget_topbrlimit'] = $_POST['wassup_widget_topbrlimit'];
		$wassup_settings['wassup_widget_topos'] = $_POST['wassup_widget_topos'];
		$wassup_settings['wassup_widget_toposlimit'] = $_POST['wassup_widget_toposlimit'];
		
		update_option('wassup_settings', $wassup_settings);
		$wassup_settings = get_option('wassup_settings');
	}
	
	?>
	<div class="wrap" style="text-align:left">
        <h3>Wassup Widget</h3>
        <form action="" method="post">
        <p style="text-align:left"><input type="text" name="wassup_widget_title" size="20" value="<?php echo $wassup_settings['wassup_widget_title'] ?>" /> What title for the widget (default "Visitors Online")</p>
        <p style="text-align:left"><input type="text" name="wassup_widget_ulclass" size="3" value="<?php echo $wassup_settings['wassup_widget_ulclass'] ?>" /> What style sheet class for &lt;ul&gt; attribute (default "links")</p>
        <p style="text-align:left"><input type="text" name="wassup_widget_chars" size="3" value="<?php echo $wassup_settings['wassup_widget_chars'] ?>" /> How many characters left? (For template compatibility - default 18)</p>
        <p style="text-align:left"><input type="checkbox" name="wassup_widget_loggedin" value="1"<?php if ($wassup_settings['wassup_widget_loggedin'] == 1) echo "CHECKED"; ?> /> Check if you want to show logged-in online users (default Yes)</p>
        <p style="text-align:left"><input type="checkbox" name="wassup_widget_comauth" value="1" <?php if ($wassup_settings['wassup_widget_comauth'] == 1) echo "CHECKED"; ?> /> Check if you want to show comment-author online users (default Yes)</p>
        <p style="text-align:left"><input type="checkbox" name="wassup_widget_search" value="1" <?php if ($wassup_settings['wassup_widget_search'] == 1) echo "CHECKED"; ?> /> Check if you want to show some last search referers (default Yes)</p>
        <p style="text-align:left"><input type="text" name="wassup_widget_searchlimit" size="3" value="<?php echo $wassup_settings['wassup_widget_searchlimit'] ?>" /> How many search referers want to show (default 5)</p>
        <p style="text-align:left"><input type="checkbox" name="wassup_widget_ref" value="1" <?php if ($wassup_settings['wassup_widget_ref'] == 1) echo "CHECKED"; ?> /> Check if you want to show some last external referers (default Yes)</p>
        <p style="text-align:left"><input type="text" name="wassup_widget_reflimit" size="3" value="<?php echo $wassup_settings['wassup_widget_reflimit'] ?>" /> How many external referers want to show (default 5)</p>
        <p style="text-align:left"><input type="checkbox" name="wassup_widget_topbr" value="1" <?php if ($wassup_settings['wassup_widget_topbr'] == 1) echo "CHECKED"; ?> /> Check if you want to show top browsers (default Yes)</p>
        <p style="text-align:left"><input type="text" name="wassup_widget_topbrlimit" size="3" value="<?php echo $wassup_settings['wassup_widget_topbrlimit'] ?>" /> How many top browsers want to show (default 5)</p>
        <p style="text-align:left"><input type="checkbox" name="wassup_widget_topos" value="1" <?php if ($wassup_settings['wassup_widget_topos'] == 1) echo "CHECKED"; ?> /> Check if you want to show top operating systems (default Yes)</p>
        <p style="text-align:left"><input type="text" name="wassup_widget_toposlimit" size="3" value="<?php echo $wassup_settings['wassup_widget_toposlimit'] ?>" /> How many top operating systems want to show (default 5)</p>
        <p style="text-align:left"><input type="submit" name="submit" value="Save Settings" /></p>
        </form>
        </div>
	<?php
}

	$wassup_settings = get_option('wassup_settings');
	if ($wassup_settings['wassup_userlevel'] == "") {
		if ($wassup_settings['wassup_userlevel'] == "") {
			$wassup_settings['wassup_userlevel'] = 8;
			update_option('wassup_settings', $wassup_settings);
		}
		if ($wassup_settings['wassup_refresh'] == "") {
			$wassup_settings['wassup_refresh'] = 3;
			update_option('wassup_settings', $wassup_settings);
		}
	}
		if(function_exists('register_sidebar_widget')) {
			register_sidebar_widget(__('Wassup Widget'), 'wassup_widget'); 
			register_widget_control(array('Wassup Widget', 'widgets'), 'wassup_widget_control', 600, 540);
		}
}

function wassup_sidebar($before_widget='', $after_widget='', $before_title='', $after_title='', $wtitle='', $wulclass='', $wchars='', $wsearch='', $wsearchlimit='', $wref='', $wreflimit='', $wtopbr='', $wtopbrlimit='', $wtopos='', $wtoposlimit='') {
	global $wpdb;
	$wpurl =  get_bloginfo('wpurl');
	$siteurl =  get_bloginfo('siteurl');
	if ($wtitle != "") $title = $wtitle; else $title = "Visitors Online";
	if ($wulclass != "") $ulclass = $wulclass; else $ulclass = "links";
	if ($wchars != "") $chars = $wchars; else $chars = "18";
	if ($wsearchlimit != "") $searchlimit = $wsearchlimit; else $searchlimit = "5";
	if ($wreflimit != "") $reflimit = $wreflimit; else $reflimit = "5";
	if ($wtopbrlimit != "") $topbrlimit = $wtopbrlimit; else $topbrlimit = "5";
	if ($wtoposlimit != "") $toposlimit = $wtoposlimit; else $toposlimit = "5";
	$table_name = $wpdb->prefix . "wassup";
	$to_date = wassup_get_time();
	$from_date = strtotime('-3 minutes', $to_date);

        print $before_widget;
	if ($wsearch == 1) {
	$query_det = $wpdb->get_results("SELECT search, referrer FROM $table_name WHERE search!='' GROUP BY search ORDER BY timestamp DESC LIMIT $searchlimit");
	if (count($query_det) > 0) {
		print "$before_title Last searched terms $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_det as $sref) {
			print "<li>- <a href='".$sref->referrer."' target='_BLANK'>".stringShortener($sref->search, $chars)."</a></li>";
		}
		print "</ul>";
	}
	}

	if ($wref == 1) {
	$query_ref = $wpdb->get_results("SELECT referrer FROM $table_name WHERE searchengine='' AND referrer!='' AND referrer NOT LIKE '$wpurl%' GROUP BY referrer ORDER BY timestamp DESC LIMIT $reflimit");
	if (count($query_ref) > 0) {
		print "$before_title Last referers $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_ref as $eref) {
			print "<li>- <a href='".$eref->referrer."' target='_BLANK'>".stringShortener(eregi_replace("http://", "", $eref->referrer), $chars)."</a></li>";
		}
		print "</ul>";
	}
	}

	if ($wtopbr == 1) {
	$query_topbr = $wpdb->get_results("SELECT count(browser) as top_browser, browser FROM $table_name WHERE browser!='' AND browser NOT LIKE '%N/A%' GROUP BY browser ORDER BY top_browser DESC LIMIT $topbrlimit");
	if (count($query_topbr) > 0) {
		print "$before_title Top Browsers $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_topbr as $etopbr) {
			print "<li>- ".stringShortener($etopbr->browser, $chars)."</li>";
		}
		print "</ul>";
	}
	}

	if ($wtopos == 1) {
	$query_topos = $wpdb->get_results("SELECT count(os) as top_os, os FROM $table_name WHERE os!='' AND os NOT LIKE '%N/A%' GROUP BY os ORDER BY top_os DESC LIMIT $toposlimit");
	if (count($query_topos) > 0) {
		print "$before_title Top OS $after_title";
		print "<ul class='$ulclass'>";
		foreach ($query_topos as $etopos) {
			print "<li>- ".stringShortener($etopos->os, $chars)."</li>";
		}
		print "</ul>";
	}
	}

	print $before_title . $title . $after_title;
	print "<ul class='$ulclass'>";
	$currenttot = $wpdb->get_var("SELECT COUNT(DISTINCT wassup_id) as currenttot FROM $table_name WHERE timestamp BETWEEN $from_date AND $to_date ");
	$currentlogged = $wpdb->get_var("SELECT COUNT(DISTINCT wassup_id) as currentlogged FROM $table_name WHERE username!=''AND timestamp BETWEEN $from_date AND $to_date");
	$currentauth = $wpdb->get_var("SELECT COUNT(DISTINCT wassup_id) as currentauth FROM $table_name WHERE comment_author!='' AND username=''AND timestamp BETWEEN $from_date AND $to_date");
	if ((int)$currenttot < 10) $currenttot = "0".$currenttot;
	print "<li><strong style='padding:0 4px 0 4px;background:#ddd;color:#777'>".$currenttot."</strong> visitor(s) online</li>";
	if ((int)$currentlogged > 0 AND $wassup_settings['wassup_widget_loggedin'] == 1) {
	if ((int)$currentlogged < 10) $currentlogged = "0".$currentlogged;
		print "<li><strong style='padding:0 4px 0 4px;background:#e7f1c8;color:#777'>".$currentlogged."</strong> logged-in user(s)</li>";
	}
	if ((int)$currentauth > 0 AND $wassup_settings['wassup_widget_comauth'] == 1) {

	if ((int)$currentauth < 10) $currentauth = "0".$currentauth;
		print "<li><strong style='padding:0 4px 0 4px;background:#fbf9d3;color:#777'>".$currentauth."</strong> comment author(s)</li>";
	}
	print "<li style='font-size:6pt; color:#bbb;'>powered by <a style='color:#777;' href='http://www.wpwp.org/' title='WassUp - Real Time Visitors Tracking'>WassUp</a></li>";
	print "</ul>";
	print $after_widget;
}

