Skip to content

Instantly share code, notes, and snippets.

Created December 12, 2011 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1469300 to your computer and use it in GitHub Desktop.
Save anonymous/1469300 to your computer and use it in GitHub Desktop.
Stats Plugin
<?php
session_start();
/*
Plugin Name: Visitors Statistics Plugin
Description: Information about visitors on your site.
Version: 1.1
Author: Ankur Taxali
Licence: GPLv2
Copyright 2011 Ankur Taxali. This program is free software; you can
redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
register_activation_hook ( __FILE__, 'vsp_plugin_install' );
/**
* Plugin activation function
*
* This function fires after the plugin is installed
* and creates two tables, if needed.
*
*/
function vsp_plugin_install() {
global $wpdb;
$visits_table = $wpdb->prefix . "vsp_visits";
$hits_table = $wpdb->prefix . "vsp_hits";
$wpdb->show_errors();
$sql = "CREATE TABLE IF NOT EXISTS `$visits_table` (
`id` int(11) unsigned NOT NULL auto_increment,
`ip` char(30) default NULL,
`date` timestamp NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$wpdb->query( $sql );
$hits_sql = "CREATE TABLE IF NOT EXISTS `$hits_table` (
`id` int(11) unsigned NOT NULL auto_increment,
`visit_id` int(11) default NULL,
`date` timestamp NULL default CURRENT_TIMESTAMP,
`post_id` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$wpdb->query( $hits_sql );
}
add_action ( 'template_redirect', 'vsp_process_visitor' );
/**
* Process visitor
*
* Checks whether used is "logged" or not,
* Adds the user to the unique table if not logged,
* adds a hit using the user_id if she is logged
*
*/
function vsp_process_visitor() {
global $wpdb;
$visits_table = $wpdb->prefix . "vsp_visits";
if ( vsp_visitor_logged_in() ) {
vsp_update_count();
}
if ( !vsp_visitor_logged_in() ) {
vsp_new_record( $visits_table );
}
}
/**
* Checks user state
*
* Checks whether a user session is set
* Logged in if set
*
*/
function vsp_visitor_logged_in() {
$logged_in = false;
if ( isset( $_SESSION[ 'vsp_user' ] ) ) {
$logged_in = true;
}
return $logged_in;
}
/**
* Creates new unique and hit
*
* Inserts data into the unique table and the
* hits table, if allowed.
*
*/
function vsp_new_record( $table ) {
$ip = get_ip();
global $wpdb;
$hits_table = $wpdb->prefix . "vsp_hits";
/*
Insert data into the visitors table
*/
$data = array ( 'ip' => $ip );
if ( valid_time($table) ) {
$wpdb->insert ( $table, $data );
}
$userID = $wpdb->get_var( 'select `id` from ' . $table . ' where `ip` = "' . $ip . '" order by `id` desc limit 1;');
$_SESSION[ 'vsp_user' ] = $userID;
/*
Insert data into the hits table
*/
$data = array( 'visit_id' => $userID );
if ( valid_time($hits_table) ) {
$wpdb->insert ( $hits_table, $data );
}
}
/**
* Determine if OK to write
*
* Checks the time of the last write, returns false if difference < than 10 seconds
*
*/
function valid_time( $table ) {
global $wpdb;
$wpdb->show_errors();
// get the last row
$sql = 'select `date` from ' . $table . ' where `id` = (select max(`id`) from ' . $table . ');';
$row= $wpdb->get_row( $sql );
// get the last row time stamp
$timestamp = $row->date;
// convert it into a unix timestamp
$old_value = $wpdb->get_var( "select UNIX_TIMESTAMP('$timestamp');" );
//compare old and new
if ( $old_value > time() ) {
return FALSE;
} if ( time() > $old_value ) {
$diff = time() - $old_value;
if ( $diff > 10 ) {
return TRUE;
} else {
return FALSE;
}
}
}
/**
* Only updates the hits table
*
* If user is logged in, this function is called to
* add a hit based on the logged in user's ID
*
*/
function vsp_update_count() {
global $wpdb;
$wpdb->show_errors();
$hits_table = $wpdb->prefix . "vsp_hits";
$userID = $_SESSION[ 'vsp_user' ];
$postID = get_page_id();
$data = array( 'visit_id' => $userID, 'post_id' => $postID );
if ( valid_time($hits_table) ) {
$wpdb->insert ( $hits_table, $data );
}
}
/**
* Get the ID of the current page or post
*
*/
function get_page_id() {
global $post;
if($post->post_type == 'page'){
$postID = $post->ID;
} elseif($post->post_type == 'post') {
$postID = $post->ID;
}
return intval($postID);
}
/**
* Returns IP Address of client/user
*
*/
function get_ip() {
if(array_key_exists("HTTP_CLIENT_IP",$_SERVER)
&& !empty($_SERVER["HTTP_CLIENT_IP"])) {
return $_SERVER["HTTP_CLIENT_IP"];
}
else if(array_key_exists("X_FORWARDED_FOR",$_SERVER)
&& !empty($_SERVER["X_FORWARDED_FOR"])) {
return $_SERVER["X_FORWARDED_FOR"];
}
else {
return $_SERVER["REMOTE_ADDR"];
}
}
/**
* Given a table name, returns the count
*
*/
function get_total_count( $table_name ) {
global $wpdb;
$count = $wpdb->get_var( "select count(*) from $table_name;" );
return $count;
}
/**
* The following functions deal with displaying the data
*
*/
add_action ( 'admin_menu', 'vsp_create_menu' );
function vsp_create_menu() {
add_menu_page( 'Visitors Statistics', 'Visitors Statistics', 'edit_posts', 'vsp_settings_page', 'vsp_settings_page_function', plugins_url( '/images/icon.png', __FILE__ ) );
add_submenu_page( 'vsp_settings_page', 'Visitors Statistics', 'Hits', 'edit_posts', 'vsp_hits_submenu_page', 'vsp_hits_func' );
}
function vsp_settings_page_function() {
if ( !current_user_can( 'edit_posts' ) ) {
wp_die( __('You do not have sufficient permissions to be here. Please log in with a different user account, then try again.' ) );
}
global $wpdb;
$visits_table = $wpdb->prefix . "vsp_visits";
$hits_table = $wpdb->prefix . "vsp_hits";
$count = get_total_count( $visits_table );
echo '<div class="wrap" id="vsp_plugin_main_page">';
echo '<h2>Recent Visits</h2>';
pagination();
global $pageNum;
if ( !is_nan( $pageNum ) && is_int( $pageNum ) ) {
if ( $pageNum === 1 ) {
$sql_limit_clause = 0;
} elseif ( $pageNum > 1 ) {
$sql_limit_clause = ($pageNum*10)-9; // eg. 2 would become 11, so limit clause would be 11, 10, the second page
} else {
$sql_limit_clause = 0;
}
}
echo '<table class=\'widefat\'>';
echo '<thead>';
echo '<th>IP Address</th>';
echo '<th>Day</th>';
echo '<th>Time</th>';
echo '<th>Hits</th>';
echo '</thead>';
echo '<tbody>';
$sql = "select visits.ip, UNIX_TIMESTAMP(visits.date), count(*) from $hits_table hits INNER JOIN $visits_table visits ON hits.visit_id = visits.id group by hits.visit_id order by visits.date desc limit $sql_limit_clause, 10;";
$uniques = $wpdb->get_results( $sql, ARRAY_N );
foreach ( $uniques as $u ) {
$day = date( 'j', $u[1] );
$month = date( 'M', $u[1] );
$year = date( 'y', $u[1] );
$hour = date( 'g', $u[1] );
$min = date( 'i', $u[1] );
$pmam = date( 'a', $u[1] );
echo "<tr><td>{$u[0]}</td>";
echo "<td>$day/$month/$year</td>";
echo "<td><span class='time'>$hour<span>: $min $pmam</td>";
echo "<td>$u[2]</td></tr>";
}
echo '</tbody>';
echo '</table>';
$message = "Displaying: $sql_limit_clause to " . ($sql_limit_clause + 9);
echo "<h3>Total Visitors: $count</h3>";
echo "<p>$message</p>";
echo '</div>';
}
function vsp_hits_func() {
if ( !current_user_can( 'edit_posts' ) ) {
wp_die( __('You do not have sufficient permissions to be here. Please log in with a different user account, then try again.' ) );
}
echo '<div class="wrap" id="vsp_plugin_main_page">';
echo '<h2>Recent Hits</h2>';
pagination();
global $pageNum;
if ( !is_nan( $pageNum ) && is_int( $pageNum ) ) {
if ( $pageNum === 1 ) {
$sql_limit_clause = 0;
} elseif ( $pageNum > 1 ) {
$sql_limit_clause = ($pageNum*10)-9; // eg. 2 would become 11, so limit clause would be 11, 10, the second page
} else {
$sql_limit_clause = 0;
}
}
echo '<table class=\'widefat\'>';
echo '<thead>';
echo '<th>Date</th>';
echo '<th>Page ID</th>';
echo '<th>Page Title</th>';
echo '<th>IP Address</th>';
echo '</thead>';
echo '<tbody>';
global $wpdb;
$visits_table = $wpdb->prefix . "vsp_visits";
$hits_table = $wpdb->prefix . "vsp_hits";
$sql = "select UNIX_TIMESTAMP(hits.date), hits.post_id, visits.ip from $hits_table hits, $visits_table visits where visits.id = hits.visit_id order by hits.date desc limit $sql_limit_clause, 10;";
$uniques = $wpdb->get_results( $sql, ARRAY_N );
foreach ( $uniques as $u ) {
$day = date( 'j', $u[0] );
$month = date( 'M', $u[0] );
$year = date( 'y', $u[0] );
$hour = date( 'g', $u[0] );
$min = date( 'i', $u[0] );
$pmam = date( 'a', $u[0] );
echo "<tr><td>$day/$month/$year $hour:$min $pmam</td>";
echo "<td>$u[1]</td>";
$pageID = $u[1];
$page = get_post($pageID);
echo "<td>$page->post_title</td>";
echo "<td>$u[2]</td></tr>";
}
echo '</tbody>';
echo '</table>';
$message = "Displaying: $sql_limit_clause to " . ($sql_limit_clause + 9);
$count = get_total_count( $hits_table );
echo "<h3>Total Hits: $count</h3>";
echo "<p>$message</p>";
echo '</div>';
}
function pagination() {
global $pageNum;
global $stats_per_page;
if ( $_POST['page_num'] ) {
$pageNum = $_POST['page_num'];
$pageNum = intval( $pageNum );
} else {
$pageNum = 1;
}
?>
<form name="vsp_pagination" method="post" action="">
<p>Go to page: <input type='text' size='2' id='page_num' name='page_num' value='<?php if ( $pageNum ) { echo $pageNum; } else { echo '1'; }?>' /> <input type='submit' id='submit' name='submit' class='button-primary' /> </p>
</form>
<?php
}
/**
* The following functions deal with administrative work
*
*/
function admin_register_head() {
$siteurl = get_option('siteurl');
$url = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/vsp_styles.css';
echo "<link rel='stylesheet' type='text/css' href='$url' />\n";
}
add_action('admin_head', 'admin_register_head');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment