Location: PHPKode > scripts > post - views > post-views/post-views.php
<?php
/*
Plugin Name: post-views
Plugin URI: http://ziming.org/dev/post-views
Description: Record how many times the post have been views and show it. 
Version: 1.6.1
Author: Suny Tse
Author URI: http://ziming.org
*/

/*  Copyright 2010  Suny Tse  (email : hide@address.com)

    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
*/
global $table_prefix;
$table_prefix = ( isset( $table_prefix ) ) ? $table_prefix : $wpdb->prefix;
define('WP_POST_VIEWS_TABLE', $table_prefix . 'post_views');
define('PV_ADMIN_URL', 'options-general.php?page=post-views');

add_action('init', 'post_views_textdomain');
add_action('init', 'post_views_cookie');
add_action('admin_menu', 'post_views_menu');
add_action('wp_head', 'process_post_views');
add_action('widgets_init', 'widget_post_views_init');
add_filter('query_vars', 'post_views_variables');
add_action('pre_get_posts', 'post_views_sorting');
add_action('delete_post', 'delete_post_views');

register_activation_hook(__FILE__,'check_post_views_install');


### Create Text Domain For Translations
function post_views_textdomain() {
	load_plugin_textdomain('post-views', false, 'post-views/lang');
}

function post_views_cookie(){
	$pv_options = get_option('post_view_options');
	$timeout = $pv_options['pv_cookie_timeout'];
	$cookie = strtotime(date('Y-m-d H:i:s'));
	$pv_url = md5($_SERVER['REQUEST_URI']);
	setcookie($pv_url, $cookie, time()+60*$timeout,"/");
}

### Add Option Menu
function post_views_menu() {
	if (function_exists('add_options_page')) {
	  add_options_page('Post-Views', __('Post Views','post-views'),8, 'post-views', 'post_views');
	}
}

### Init WP-PostViews Widget
function widget_post_views_init() {
	register_widget('WP_Widget_Post_Views');
}

### Check the installation
function check_post_views_install(){ 

  global $wpdb,$table_prefix;
  $post_views_table_exists = false;

/************************ Check which table not exist *********************/

  $tables = $wpdb->get_results("show tables");
  foreach ( $tables as $table ){
      foreach ( $table as $value ){
	  			if ( $value == WP_POST_VIEWS_TABLE ){
	      			$post_views_table_exists = true;
	    		}
  		}
  }
  
  if(!$post_views_table_exists){
  	  $sql = "CREATE TABLE ". WP_POST_VIEWS_TABLE ." (
  	  			 										view_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                                post_id BIGINT(20) UNSIGNED NOT NULL,
                                view_type varchar(10) NOT NULL,
                                post_views_today BIGINT(20) UNSIGNED NOT NULL,
                                post_views_week BIGINT(20) UNSIGNED NOT NULL,
                                post_views_month BIGINT(20) UNSIGNED NOT NULL,
                                post_views_halfyear BIGINT(20) UNSIGNED NOT NULL,
                                post_views_year BIGINT(20) UNSIGNED NOT NULL,
                                post_views_total BIGINT(20) UNSIGNED NOT NULL,
                                latest_view_time timestamp NOT NULL default CURRENT_TIMESTAMP,
                                PRIMARY KEY (view_id),
                                KEY post_id (post_id)
                        ) DEFAULT CHARSET=utf8;";
      $wpdb->get_results($sql);	
      
  		$old__views_data = $wpdb->get_results("select * from ".$table_prefix."postmeta where meta_key='views' ");
  		if(count($old__views_data)){
  				foreach ( $old__views_data as $old_views ){
  					  $wpdb->get_results("insert into ".WP_POST_VIEWS_TABLE." set post_id = ".$old_views->post_id.", view_type = 'normal', post_views_halfyear = ".$old_views->meta_value.", post_views_year = ".$old_views->meta_value.", post_views_total = ".$old_views->meta_value.", latest_view_time='".gmdate("Y-n-d H:i:s")."'");	
  				}
  		}
  		
  		$old_robotviews_data = $wpdb->get_results("select * from ".$table_prefix."postmeta where meta_key='bot_views' ");
  		if(count($old_robotviews_data)){
  				foreach ( $old_robotviews_data as $old_robotviews ){
  					  $wpdb->get_results("insert into ".WP_POST_VIEWS_TABLE." set post_id = ".$old_robotviews->post_id.", view_type= 'robot', post_views_halfyear = ".$old_views->meta_value.", post_views_year = ".$old_views->meta_value.", post_views_total = ".$old_robotviews->meta_value.", latest_view_time='".gmdate("Y-n-d H:i:s")."'");	
  				}
  		}
  }
  
  $pv_options['pv_perpage'] = '10';
  $pv_options['pv_dh_mode'] = 'both';
  $pv_options['pv_dh_cat'] = 0;
	$pv_options['pv_dh_catid'] = 0;
	$pv_options['pv_rec_option'] = 0;
	$pv_options['pv_rec_cookie'] = 0;
	$pv_options['pv_cookie_timeout'] = 60;
			
  if(!update_option('post_view_options', $pv_options)){
    		add_option('post_view_options',$pv_options);
  }
  
}

### Option Page
function post_views(){
	$pv_menu = '<div><a href="'.PV_ADMIN_URL.'">'.__('Normal Views Ranking List','post-views').'</a> &nbsp;|&nbsp;
									 <a href="'.PV_ADMIN_URL.'&pv_page=robot">'.__('Robot Views Ranking List','post-views').'</a> &nbsp;|&nbsp;
									 <a href="'.PV_ADMIN_URL.'&pv_page=time">'.__('Visit Time Ranking List','post-views').'</a> &nbsp;|&nbsp;
	                 <a href="'.PV_ADMIN_URL.'&pv_page=options">'.__('Views Option','post-views').'</a>';
	if(isset($_GET['pv_page'])){
		if($_GET['pv_page'] == 'options'){
			echo $pv_menu;
		 	post_views_options();
		}else if($_GET['pv_page'] == 'robot'){
			echo $pv_menu;
		 	post_views_list('robot','views');
		}else if($_GET['pv_page'] == 'time'){
			echo $pv_menu;
		 	post_views_list('normal','time');
		}
		
	}else{
		echo $pv_menu;
		post_views_list('normal','views');
	}
}

function post_views_options(){
	$pv_options = get_option('post_view_options');
	if (isset($_POST['update_setting'])) {
			$pv_options['pv_perpage'] = $_POST['pv_perpage'];
			$pv_options['pv_dh_mode'] = $_POST['pv_dh_mode'];
			$pv_options['pv_dh_cat'] = $_POST['pv_dh_cat'];
			$pv_options['pv_dh_catid'] = $_POST['pv_dh_catid'];
			$pv_options['pv_rec_option'] = intval($_POST['pv_rec_option']);
			$pv_options['pv_rec_cookie'] = intval($_POST['pv_rec_cookie']);
			$pv_options['pv_cookie_timeout'] = intval($_POST['pv_cookie_timeout']);

			update_option('post_view_options', $pv_options);
			echo '<div id="message" class="updated fade"><p>';
			echo _e('Setting Updated...','post-views');
			echo '</p></div>';
	}else if (isset($_POST['set_default'])) {
			$pv_options['pv_perpage'] = '10';
			$pv_options['pv_dh_mode'] = 'both';
			$pv_options['pv_dh_cat'] = 0;
			$pv_options['pv_dh_catid'] = 0;
			$pv_options['pv_rec_option'] = 0;
			$pv_options['pv_rec_cookie'] = 0;
			$pv_options['pv_cookie_timeout'] = 60;
			update_option('post_view_options', $pv_options);
			echo '<div id="message" class="updated fade"><p>';
			echo _e('Default setting loaded...','post-views');
			echo '</p></div>';		    
	}		
?>
<div class="wrap">
<form method="post">
<p><h3><?php _e('Dashboard Ranking List Options :', 'post-views'); ?></h3></p>
	 <p><?php _e('Ranking List Number :', 'post-views'); ?> <input type="text" name="pv_perpage" size="10" value="<?php echo $pv_options['pv_perpage'];?>"/ ></p>
	 <p><?php _e('Include Post/Page :', 'post-views'); ?>
			<select name="pv_dh_mode" size="1">
					<option value="both"<?php selected('both', $pv_options['pv_dh_mode']); ?>><?php _e('Both', 'post-views'); ?></option>
					<option value="post"<?php selected('post', $pv_options['pv_dh_mode']); ?>><?php _e('Post Only', 'post-views'); ?></option>
					<option value="page"<?php selected('page', $pv_options['pv_dh_mode']); ?>><?php _e('Page Only', 'post-views'); ?></option>
			</select>
	 	</p>
	 <p>
			<?php _e('By Category / Tag :', 'post-views'); ?>
			<select name="pv_dh_cat" size="1">
					<option value="0"<?php selected('0', $pv_options['pv_dh_cat']); ?>><?php _e('Not Use', 'post-views'); ?></option>
					<option value="1"<?php selected('1', $pv_options['pv_dh_cat']); ?>><?php _e('By Category', 'post-views'); ?></option>
					<option value="2"<?php selected('2', $pv_options['pv_dh_cat']); ?>><?php _e('By Tag', 'post-views'); ?></option>
			</select>
			<?php _e('Category / Tag IDs:', 'post-views'); ?>
			<input type="text" name="pv_dh_catid" size="40" value="<?php echo $pv_options['pv_dh_catid'];?>"/ >
		</p>
<br /><p><h3><?php _e('Post Views Logging Options :', 'post-views'); ?></h3></p>

		<p>
			<?php _e('Logging include :', 'post-views'); ?>
			<select name="pv_rec_option" size="1">
					<option value="0"<?php selected('0', $pv_options['pv_rec_option']); ?>><?php _e('Everyone', 'post-views'); ?></option>
					<option value="1"<?php selected('1', $pv_options['pv_rec_option']); ?>><?php _e('Guests Only', 'post-views'); ?></option>
					<option value="2"<?php selected('2', $pv_options['pv_rec_option']); ?>><?php _e('Registered Users Only', 'post-views'); ?></option>
			</select>
		</p>
		<p>
			<?php _e('Use Cookie :', 'post-views'); ?>
			<select name="pv_rec_cookie" size="1">
				<option value="0"<?php selected('0', $pv_options['pv_rec_cookie']); ?>><?php _e('Not', 'post-views'); ?></option>
				<option value="1"<?php selected('1', $pv_options['pv_rec_cookie']); ?>><?php _e('Yes', 'post-views'); ?></option>
			</select>
			<?php _e('Cookie Timeout :', 'post-views'); ?>
			<input type="text" name="pv_cookie_timeout" size="10" value="<?php echo $pv_options['pv_cookie_timeout'];?>"/ ><?php _e('minutes', 'post-views'); ?>
		</p>
	<div class="submit">
		<input type="submit" name="set_default" value="<?php _e('Load Default', 'post-views'); ?>" />
		<input type="submit" name="update_setting" value="<?php _e('Update Setting', 'post-views'); ?>" />
	</div>
</form>
</div>
<?php
}

function post_views_list($v_type = 'normal', $s_type = 'views'){
	global $wpdb;
	$pv_options = get_option('post_view_options');
	$pv_perpage = $pv_options['pv_perpage'];
	$mode =	$pv_options['pv_dh_mode'];
	$cat_or_tag =	$pv_options['pv_dh_cat'];
	$cat_or_tag_ids = $pv_options['pv_dh_catid'];
	if($cat_or_tag == 1){
		$catid = explode(',',$pv_options['pv_dh_catid']);;
		$tagid = 0;
	}else if($cat_or_tag == 2){
		$catid = 0;
		$tagid = explode(',',$pv_options['pv_dh_catid']);;
	}else{
		$catid = 0;
		$tagid = 0;
	}
	
	echo '<table class="widefat" cellspacing="0">';
	
  if($s_type == 'views'){
 	  $pv_total_desc = get_post_views_list($mode, $v_type, 'total','views','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_year_desc = get_post_views_list($mode, $v_type, 'year','views','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_halfyear_desc = get_post_views_list($mode, $v_type, 'halfyear','views','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_month_desc = get_post_views_list($mode, $v_type, 'month','views','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_week_desc = get_post_views_list($mode, $v_type, 'week','views','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_today_desc = get_post_views_list($mode, $v_type, 'today','views','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_total_asc = get_post_views_list($mode, $v_type, 'total','views','ASC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_year_asc = get_post_views_list($mode, $v_type, 'year','views','ASC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_halfyear_asc = get_post_views_list($mode, $v_type, 'halfyear','views','ASC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_month_asc = get_post_views_list($mode, $v_type, 'month','views','ASC', $pv_perpage, 40, $catid, $tagid);
    $pv_week_asc = get_post_views_list($mode, $v_type, 'week','views','ASC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_today_asc = get_post_views_list($mode, $v_type, 'today','views','ASC', $pv_perpage, 40, $catid, $tagid);

	  echo '<thead><tr><th>'.__('Most By Total','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Most By Year','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Most By Half Year','post-views').'</th><th>'.__('Views','post-views').'</th></tr></thead>';
    
 	  for($i=0;$i < $pv_perpage;$i++){
 	  	if(!empty($pv_total_desc[$i]['views']) || !empty($pv_year_desc[$i]['views']) || !empty($pv_halfyear_desc[$i]['views'])){
 	  		echo '<tr><td>'.$pv_total_desc[$i]['title'].'</td><td>'.$pv_total_desc[$i]['views'].'</td><td>'.$pv_year_desc[$i]['title'].'</td><td>'.$pv_year_desc[$i]['views'].'</td><td>'.$pv_halfyear_desc[$i]['title'].'</td><td>'.$pv_halfyear_desc[$i]['views'].'</td></tr>';
 	  	}
 	  }
 	  echo '<thead><tr><th>'.__('Most By Month','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Most By Week','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Most By Today','post-views').'</th><th>'.__('Views','post-views').'</th></tr></thead>';
 	  for($i=0;$i < $pv_perpage;$i++){
 	  	if(!empty($pv_month_desc[$i]['views']) || !empty($pv_week_desc[$i]['views']) || !empty($pv_today_desc[$i]['views'])){
 	  		echo '<tr><td>'.$pv_month_desc[$i]['title'].'</td><td>'.$pv_month_desc[$i]['views'].'</td><td>'.$pv_week_desc[$i]['title'].'</td><td>'.$pv_week_desc[$i]['views'].'</td><td>'.$pv_today_desc[$i]['title'].'</td><td>'.$pv_today_desc[$i]['views'].'</td></tr>';
      }
 	  }
 	  
 	  echo '<thead><tr><th>'.__('Least By Total','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Least By Year','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Least By Half Year','post-views').'</th><th>'.__('Views','post-views').'</th></tr></thead>';
	  for($i=0;$i < $pv_perpage;$i++){
 	  	if(!empty($pv_total_asc[$i]['views']) || !empty($pv_year_asc[$i]['views']) || !empty($pv_halfyear_asc[$i]['views'])){
 	  		echo '<tr><td>'.$pv_total_asc[$i]['title'].'</td><td>'.$pv_total_asc[$i]['views'].'</td><td>'.$pv_year_asc[$i]['title'].'</td><td>'.$pv_year_asc[$i]['views'].'</td><td>'.$pv_halfyear_asc[$i]['title'].'</td><td>'.$pv_halfyear_asc[$i]['views'].'</td></tr>';
 	  	}
 	  }
 	  
 	  echo '<thead><tr><th>'.__('Least By Month','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Least By Week','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Least By Today','post-views').'</th><th>'.__('Views','post-views').'</th></tr></thead>';
	  for($i=0;$i < $pv_perpage;$i++){
	  	if(!empty($pv_month_asc[$i]['views']) || !empty($pv_week_asc[$i]['views']) || !empty($pv_today_asc[$i]['views'])){
				echo '<tr><td>'.$pv_month_asc[$i]['title'].'</td><td>'.$pv_month_asc[$i]['views'].'</td><td>'.$pv_week_asc[$i]['title'].'</td><td>'.$pv_week_asc[$i]['views'].'</td><td>'.$pv_today_asc[$i]['title'].'</td><td>'.$pv_today_asc[$i]['views'].'</td></tr>';
    	}
 	  }
	}else if($s_type == 'time'){
	  $pv_latest_views = get_post_views_list($mode, 'normal', 'week','latest_view_time','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_oldest_views = get_post_views_list($mode, 'normal', 'today','latest_view_time','ASC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_latest_robot_views = get_post_views_list($mode, 'robot', 'week','latest_view_time','DESC', $pv_perpage, 40, $catid, $tagid);
 	  $pv_oldest_robot_views = get_post_views_list($mode, 'robot', 'today','latest_view_time','ASC', $pv_perpage, 40, $catid, $tagid);
 	  
 	  echo '<thead><tr><th>'.__('Latest Normal Views','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Visit Time','post-views').'</th><th>'.__('Latest Robot Views','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Visit Time','post-views').'</th></tr></thead>';
		for($i=0;$i < $pv_perpage;$i++){
		  if(!empty($pv_latest_views[$i]['views']) || !empty($pv_latest_robot_views[$i]['views'])){
 	  		echo '<tr><td>'.$pv_latest_views[$i]['title'].'</td><td>'.$pv_latest_views[$i]['views'].'</td><td>'.$pv_latest_views[$i]['time'].'</td><td>'.$pv_latest_robot_views[$i]['title'].'</td><td>'.$pv_latest_robot_views[$i]['views'].'</td><td>'.$pv_latest_robot_views[$i]['time'].'</td></tr>';
    	}
    }
    
    echo '<thead><tr><th>'.__('Oldest Normal Views','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Visit Time','post-views').'</th><th>'.__('Oldest Robot Views','post-views').'</th><th>'.__('Views','post-views').'</th><th>'.__('Visit Time','post-views').'</th></tr></thead>';
		for($i=0;$i < $pv_perpage;$i++){
			if(!empty($pv_oldest_views[$i]['views']) || !empty($pv_oldest_robot_views[$i]['views'])){
 	  		echo '<tr><td>'.$pv_oldest_views[$i]['title'].'</td><td>'.$pv_oldest_views[$i]['views'].'</td><td>'.$pv_oldest_views[$i]['time'].'</td><td>'.$pv_oldest_robot_views[$i]['title'].'</td><td>'.$pv_oldest_robot_views[$i]['views'].'</td><td>'.$pv_oldest_robot_views[$i]['time'].'</td></tr>';
    	}
 	  }
	}
 
	echo '</table>';
}

function process_post_views() {
	global $wpdb,$post,$user_ID;
	if(!wp_is_post_revision($post)) {
			if(is_single() || is_page()) {
					$agent = $_SERVER['HTTP_USER_AGENT'];
					$pv_is_rec = false;
					
					$pv_options = get_option('post_view_options');
					$pv_rec_option = $pv_options['pv_rec_option'];
					$is_usecookie = $pv_options['pv_rec_cookie'];
					if($is_usecookie == 1){
							$pv_url = md5($_SERVER['REQUEST_URI']);	
							$pv_cookie = $_COOKIE[$pv_url];
		
							if(empty($pv_cookie)){
									if($pv_rec_option == 1){
											if(intval($user_ID) == 0) {
													$pv_is_rec = true;
											}
									}else	if($pv_rec_option == 2){
											if(intval($user_ID) > 0) {
													$pv_is_rec = true;
											}
									}else{
											$pv_is_rec = true;
									}
							}
					}else{					
							if($pv_rec_option == 1){
									if(intval($user_ID) == 0) {
											$pv_is_rec = true;
									}
							}else	if($pv_rec_option == 2){
									if(intval($user_ID) > 0) {
											$pv_is_rec = true;
									}
							}else{
									$pv_is_rec = true;
							}
					}
	
					if(is_robot($agent)){
							post_views_update('robot');
					}else{
							if($pv_is_rec){
									post_views_update('normal');
							}
					}
			}
	}
}

function post_views_last_viewd_update(){
		global $wpdb,$post,$last_visited_time;
		$id = intval($post->ID);
		$last_visited_time['normal'] = $wpdb->get_var($wpdb->prepare("SELECT latest_view_time FROM ".WP_POST_VIEWS_TABLE." where view_type='normal' and post_id=".$id));
		$last_visited_time['robot'] = $wpdb->get_var($wpdb->prepare("SELECT latest_view_time FROM ".WP_POST_VIEWS_TABLE." where view_type='robot' and post_id=".$id));
}
function post_views_update($v_type){
	global $wpdb,$post;
	$id = intval($post->ID);
	$latest_view_time = $wpdb->get_var($wpdb->prepare("SELECT latest_view_time FROM ".WP_POST_VIEWS_TABLE." where view_type='".$v_type."' and post_id=".$id));
	post_views_last_viewd_update();
	if(!$latest_view_time){
			$wpdb->get_results("insert into ".WP_POST_VIEWS_TABLE." set post_id=$id, view_type='".$v_type."', post_views_today=1,post_views_week = 1, post_views_month = 1, post_views_halfyear = 1, post_views_year = 1, post_views_total = 1, latest_view_time='".gmdate("Y-n-d H:i:s")."'");					
	}else{
			$time_span = get_time_span($latest_view_time);
		  
			// only add once, coz, if diff_w, must diff_d,so wont add twice or more 
			if($time_span['diff_d']){
					$wpdb->get_results("update ".WP_POST_VIEWS_TABLE." set post_views_today = 1, post_views_week = post_views_week + 1, post_views_month = post_views_month + 1, post_views_halfyear = post_views_halfyear + 1, post_views_year = post_views_year + 1, post_views_total = post_views_total + 1, latest_view_time='".gmdate("Y-n-d H:i:s")."' where view_type='".$v_type."' and post_id=$id");
			}else{
					$wpdb->get_results("update ".WP_POST_VIEWS_TABLE." set post_views_today = post_views_today + 1, post_views_week = post_views_week + 1, post_views_month = post_views_month + 1, post_views_halfyear = post_views_halfyear + 1, post_views_year = post_views_year + 1, post_views_total = post_views_total + 1, latest_view_time='".gmdate("Y-n-d H:i:s")."' where view_type='".$v_type."' and post_id=$id");
			}
			
			if($time_span['diff_w']){
					$wpdb->get_results("update ".WP_POST_VIEWS_TABLE." set post_views_today = 1, post_views_week = 1, latest_view_time='".gmdate("Y-n-d H:i:s")."' where view_type='".$v_type."' and post_id=$id");
			}
	
			if($time_span['diff_m']){
					$wpdb->get_results("update ".WP_POST_VIEWS_TABLE." set post_views_today = 1, post_views_week = 1, post_views_month = 1, latest_view_time='".gmdate("Y-n-d H:i:s")."' where view_type='".$v_type."' and post_id=$id");
			}
	
			if($time_span['diff_hy']){
					$wpdb->get_results("update ".WP_POST_VIEWS_TABLE." set post_views_today = 1, post_views_week = 1, post_views_month = 1, post_views_halfyear = 1, latest_view_time='".gmdate("Y-n-d H:i:s")."' where view_type='".$v_type."' and post_id=$id");
			}	
	
			if($time_span['diff_y']){
					$wpdb->get_results("update ".WP_POST_VIEWS_TABLE." set post_views_today = 1, post_views_week = 1, post_views_month = 1, post_views_halfyear = 1, post_views_year = 1, latest_view_time='".gmdate("Y-n-d H:i:s")."' where view_type='".$v_type."' and post_id=$id");
			}	
	}
	
}

function delete_post_views($post_ID) {
	global $wpdb;
	if(!wp_is_post_revision($post_ID)) {
			$wpdb->get_results("delete from ".WP_POST_VIEWS_TABLE." where post_id=".$post_ID);
	}
}

### Function: Sort Views Posts
function post_views_sorting($local_wp_query) {

	//if(($local_wp_query->get('v_sortby') == 'views') || ($local_wp_query->get('v_sortby') == 'robot_views')) {
	if($local_wp_query->get('v_sortby') == 'views') {
		add_filter('posts_fields', 'post_views_fields');
		add_filter('posts_join', 'post_views_join');
		add_filter('posts_where', 'post_views_where');
		add_filter('posts_orderby', 'post_views_orderby');
	} else {
		remove_filter('posts_fields', 'post_views_fields');
		remove_filter('posts_join', 'post_views_join');
		remove_filter('posts_where', 'post_views_where');
		remove_filter('posts_orderby', 'post_views_orderby');
	}
	
}

function post_views_variables($public_query_vars) {
	$public_query_vars[] = 'v_sortby';
	$public_query_vars[] = 'v_timespan';
	$public_query_vars[] = 'v_ordertype';
	$public_query_vars[] = 'v_orderby';
	return $public_query_vars;
}

function post_views_fields($content) {
	global $wpdb;
	$v_timespan = trim(addslashes(get_query_var('v_timespan')));
	if($v_timespan == 'today') {
    	$v_timespan = 'post_views_today';
	}else if($v_timespan == 'week') {
    	$v_timespan = 'post_views_week';
	}else if($v_timespan == 'month') {
    	$v_timespan = 'post_views_month';
	}else if($v_timespan == 'halfyear') {
    	$v_timespan = 'post_views_halfyear';
	}else if($v_timespan == 'year') {
    	$v_timespan = 'post_views_year';
	}else{
	 		$v_timespan = 'post_views_total';
	}
	
	$v_visit_time = trim(addslashes(get_query_var('v_ordertype')));
	if($v_visit_time == 'latest_view_time') {
		$v_visit_time = ' , latest_view_time';
	}else{
		$v_visit_time = '';
	}
	
	$content .= ", (".WP_POST_VIEWS_TABLE.".".$v_timespan." + 0) AS views $v_visit_time";
	return $content;
}
function post_views_join($content) {
	global $wpdb;
	$content .= " LEFT JOIN ".WP_POST_VIEWS_TABLE." ON ".WP_POST_VIEWS_TABLE.".post_id = $wpdb->posts.ID";	
	return $content;
}
function post_views_where($content) {
	global $wpdb;
		
	$v_sortby = trim(addslashes(get_query_var('v_sortby')));
	if($v_sortby == 'robot_views') {
    	$v_sortby = 'robot';
	}else{
	 		$v_sortby = 'normal';
	}
	
	$v_timespan = trim(addslashes(get_query_var('v_timespan')));
	if($v_timespan == 'today') {
    	$v_timespan = 'post_views_today';
	}else if($v_timespan == 'week') {
    	$v_timespan = 'post_views_week';
	}else if($v_timespan == 'month') {
    	$v_timespan = 'post_views_month';
	}else if($v_timespan == 'halfyear') {
    	$v_timespan = 'post_views_halfyear';
	}else if($v_timespan == 'year') {
    	$v_timespan = 'post_views_year';
	}else{
	 		$v_timespan = 'post_views_total';
	}

	$content .= " AND ".WP_POST_VIEWS_TABLE.".view_type = '".$v_sortby."' AND ".WP_POST_VIEWS_TABLE.".".$v_timespan." != 0 ";
	return $content;
}

function post_views_orderby($content) {
	$ordertype = trim(addslashes(get_query_var('v_ordertype')));
	if(empty($ordertype) || ($ordertype != 'latest_view_time' && $ordertype != 'views')) {
		$ordertype = 'views';
	}
	
	$orderby = strtolower(trim(addslashes(get_query_var('v_orderby'))));
	if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
		$orderby = 'desc';
	}
	$content = " $ordertype  $orderby";
	return $content;
}


class WP_Widget_Post_Views extends WP_Widget {
	// Constructor
	function WP_Widget_Post_Views() {
		$widget_ops = array('description' => __('Post Views', 'post-views'));
		$this->WP_Widget('post-views', __('Post Views', 'post-views'), $widget_ops);
	}

	// Display Widget
	function widget($args, $instance) {
		extract($args);
		$title = apply_filters('widget_title', esc_attr($instance['title']));
		$type = esc_attr($instance['type']);
		$view_type = esc_attr($instance['view_type']);
		$time_span = esc_attr($instance['time_span']);
		$mode = esc_attr($instance['mode']);
		$limit = intval($instance['limit']);
		$chars = intval($instance['chars']);
		if(esc_attr($instance['cat_or_tag_ids'])==0){
				$cat_or_tag_ids =	0;
		}else{
				$cat_or_tag_ids = explode(',', esc_attr($instance['cat_or_tag_ids']));
		}

		echo $before_widget.$before_title.$title.$after_title;
		echo '<ul>'."\n";
		switch($type) {   //($mode = '', $view_type = 'normal', $time_span = 'total_views', $order_type = 'DESC', $limit = 10, $chars = 0, $category_id = 0,$tag_id = 0)
			case 'most_viewed':
				show_post_views_list($mode, $view_type, $time_span,'views','DESC', $limit, $chars);
				break;
			case 'most_viewed_category':
				show_post_views_list($mode, $view_type, $time_span,'views','DESC', $limit, $chars, $cat_or_tag_ids,0);
				break;
			case 'most_viewed_tag':
				show_post_views_list($mode, $view_type, $time_span,'views','DESC', $limit, $chars,0, $cat_or_tag_ids);
				break;
				
			case 'least_viewed':
				show_post_views_list($mode, $view_type, $time_span,'views','ASC', $limit, $chars);
				break;
			case 'least_viewed_category':
				show_post_views_list($mode, $view_type, $time_span,'views','ASC',$limit, $chars, $cat_or_tag_ids,0);
				break;
			case 'least_viewed_tag':
				show_post_views_list($mode, $view_type, $time_span,'views','ASC', $limit, $chars,0, $cat_or_tag_ids);
				break;
			
			case 'latest_viewed':
				show_post_views_list($mode, $view_type, $time_span,'latest_view_time','DESC', $limit, $chars);
				break;
			case 'latest_viewed_category':
				show_post_views_list($mode, $view_type, $time_span,'latest_view_time','DESC',$limit, $chars, $cat_or_tag_ids,0);
				break;
			case 'latest_viewed_tag':
				show_post_views_list($mode, $view_type, $time_span,'latest_view_time','DESC', $limit, $chars,0, $cat_or_tag_ids);
				break;
				
			case 'oldest_viewed':
				show_post_views_list($mode, $view_type, $time_span,'latest_view_time','ASC', $limit, $chars);
				break;
			case 'oldest_viewed_category':
				show_post_views_list($mode, $view_type, $time_span,'latest_view_time','ASC',$limit, $chars, $cat_or_tag_ids,0);
				break;
			case 'oldest_viewed_tag':
				show_post_views_list($mode, $view_type, $time_span,'latest_view_time','ASC', $limit, $chars,0, $cat_or_tag_ids);
				break;
		}
		echo '</ul>'."\n";
		echo $after_widget;
	}

	// When Widget Control Form Is Posted
	function update($new_instance, $old_instance) {
		if (!isset($new_instance['submit'])) {
			return false;
		}
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['type'] = strip_tags($new_instance['type']);
		$instance['view_type'] = strip_tags($new_instance['view_type']);
		$instance['time_span'] = strip_tags($new_instance['time_span']);
		$instance['mode'] = strip_tags($new_instance['mode']);
		$instance['limit'] = intval($new_instance['limit']);
		$instance['chars'] = intval($new_instance['chars']);
		$instance['cat_or_tag_ids'] = strip_tags($new_instance['cat_or_tag_ids']);
		return $instance;
	}

	// DIsplay Widget Control Form
	function form($instance) {
		global $wpdb;
		$instance = wp_parse_args((array) $instance, array('title' => __('Post Views', 'post-views'), 'type' => 'most_viewed', 'view_type' => 'normal', 'time_span' => 'total', 'mode' => 'both', 'limit' => 10, 'chars' => 20, 'cat_or_tag_ids' => '0'));
		$title = esc_attr($instance['title']);
		$type = esc_attr($instance['type']);
		$view_type = esc_attr($instance['view_type']);
		$time_span = esc_attr($instance['time_span']);
		$mode = esc_attr($instance['mode']);
		$limit = intval($instance['limit']);
		$chars = intval($instance['chars']);
		$cat_or_tag_ids = esc_attr($instance['cat_or_tag_ids']);

?>	
		<p>
			<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'post-views'); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></label>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('type'); ?>"><?php _e('Statistics Type:', 'post-views'); ?>
				<select name="<?php echo $this->get_field_name('type'); ?>" id="<?php echo $this->get_field_id('type'); ?>" class="widefat" onchange="<?php echo $rand_js; ?>">
					<option value="least_viewed"<?php selected('least_viewed', $type); ?>><?php _e('Least Viewed', 'post-views'); ?></option>
					<option value="least_viewed_tag"<?php selected('least_viewed_tag', $type); ?>><?php _e('Least Viewed By Tag', 'post-views'); ?></option>
					<option value="least_viewed_category"<?php selected('least_viewed_category', $type); ?>><?php _e('Least Viewed By Category', 'post-views'); ?></option>
					<optgroup>--------------</optgroup>
					<option value="most_viewed"<?php selected('most_viewed', $type); ?>><?php _e('Most Viewed', 'post-views'); ?></option>
					<option value="most_viewed_tag"<?php selected('most_viewed_tag', $type); ?>><?php _e('Most Viewed By Tag', 'post-views'); ?></option>
					<option value="most_viewed_category"<?php selected('most_viewed_category', $type); ?>><?php _e('Most Viewed By Category', 'post-views'); ?></option>
					<optgroup>--------------</optgroup>
					<option value="latest_viewed"<?php selected('latest_viewed', $type); ?>><?php _e('Latest Viewed', 'post-views'); ?></option>
					<option value="latest_viewed_tag"<?php selected('latest_viewed_tag', $type); ?>><?php _e('Latest Viewed By Tag', 'post-views'); ?></option>
					<option value="latest_viewed_category"<?php selected('latest_viewed_category', $type); ?>><?php _e('Latest Viewed By Category', 'post-views'); ?></option>
					<optgroup>--------------</optgroup>
					<option value="oldest_viewed"<?php selected('oldest_viewed', $type); ?>><?php _e('Oldest Viewed', 'post-views'); ?></option>
					<option value="oldest_viewed_tag"<?php selected('oldest_viewed_tag', $type); ?>><?php _e('Oldest Viewed By Tag', 'post-views'); ?></option>
					<option value="oldest_viewed_category"<?php selected('oldest_viewed_category', $type); ?>><?php _e('Oldest Viewed By Category', 'post-views'); ?></option>				
				</select>
			</label>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('time_span'); ?>"><?php _e('Time Span:', 'post-views'); ?>
				<select name="<?php echo $this->get_field_name('time_span'); ?>" id="<?php echo $this->get_field_id('time_span'); ?>" class="widefat">
					<option value="today"<?php selected('today', $time_span); ?>><?php _e('By Today Views', 'post-views'); ?></option>
					<option value="week"<?php selected('week', $time_span); ?>><?php _e('By Week Views', 'post-views'); ?></option>
					<option value="month"<?php selected('month', $time_span); ?>><?php _e('By Month Views', 'post-views'); ?></option>
					<option value="halfyear"<?php selected('halfyear', $time_span); ?>><?php _e('By Half Year Views', 'post-views'); ?></option>
					<option value="year"<?php selected('year', $time_span); ?>><?php _e('By Year Views', 'post-views'); ?></option>
					<option value="total"<?php selected('total', $time_span); ?>><?php _e('By Total Views', 'post-views'); ?></option>
				</select>
			</label>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('view_type'); ?>"><?php _e('View Type:', 'post-views'); ?>
				<select name="<?php echo $this->get_field_name('view_type'); ?>" id="<?php echo $this->get_field_id('view_type'); ?>" class="widefat">
					<option value="normal"<?php selected('normal', $view_type); ?>><?php _e('Normal Visitor Viewed', 'post-views'); ?></option>
					<option value="robot"<?php selected('robot', $view_type); ?>><?php _e('Robot Viewed', 'post-views'); ?></option>
				</select>
			</label>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('mode'); ?>"><?php _e('Include Views From:', 'post-views'); ?>
				<select name="<?php echo $this->get_field_name('mode'); ?>" id="<?php echo $this->get_field_id('mode'); ?>" class="widefat">
					<option value="both"<?php selected('both', $mode); ?>><?php _e('Posts &amp; Pages', 'post-views'); ?></option>
					<option value="post"<?php selected('post', $mode); ?>><?php _e('Posts Only', 'post-views'); ?></option>
					<option value="page"<?php selected('page', $mode); ?>><?php _e('Pages Only', 'post-views'); ?></option>
				</select>
			</label>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('limit'); ?>"><?php _e('Records To Show:', 'post-views'); ?> <input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="<?php echo $limit; ?>" /></label>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('chars'); ?>"><?php _e('Maximum Title Length:', 'post-views'); ?> <input class="widefat" id="<?php echo $this->get_field_id('chars'); ?>" name="<?php echo $this->get_field_name('chars'); ?>" type="text" value="<?php echo $chars; ?>" /></label><br />
			<small><?php _e('<strong>0</strong> to disable.', 'post-views'); ?></small>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('cat_or_tag_ids'); ?>"><?php _e('Category / Tag IDs:', 'post-views'); ?> <span style="color: red;">*</span> <input class="widefat" id="<?php echo $this->get_field_id('cat_or_tag_ids'); ?>" name="<?php echo $this->get_field_name('cat_or_tag_ids'); ?>" type="text" value="<?php echo $cat_or_tag_ids; ?>" /></label><br />
			<small><?php _e('Seperate mutiple categories/tags with commas, positive to include and \'-\' to exlude(if not using \'* by category/tag\' ignore it).', 'post-views'); ?></small>
		</p>
		<input type="hidden" id="<?php echo $this->get_field_id('submit'); ?>" name="<?php echo $this->get_field_name('submit'); ?>" value="1" />
<?php
	}
}

function show_post_views_list($mode = '', $view_type = 'normal', $time_span = 'total', $order_type = 'views', $order_by = 'DESC', $limit = 10, $chars = 0, $category_id = 0, $tag_id = 0, $before = '<li>', $after = '</li>'){
		$output='';
		$post_views_list = get_post_views_list($mode, $view_type, $time_span, $order_type, $order_by, $limit, $chars, $category_id, $tag_id);
		for($i=0;$i < $limit;$i++){
			 if(!empty($post_views_list[$i]['views']) && ($post_views_list[$i]['views'] != 0)){
			 		$output .= $before.' '.$post_views_list[$i]['title'].' '.$after;
			 }
		}
		echo $output;
	
}
function get_post_views_list($mode = '', $view_type = 'normal', $time_span = 'total', $order_type = 'views', $order_by = 'DESC', $limit = 10, $chars = 0, $category_id = 0, $tag_id = 0){
		global $wpdb, $post;
		for($i=0;$i < $limit;$i++){
				$pv_views[$i] = array('title' => '', 'views' => '', 'time' => '' );
		}
		
		if(!empty($mode) && $mode != 'both') {
			$mode = "post_type = '$mode'";
		} else {
			$mode = '1=1';
		}
		if($time_span == 'today'){
			$time_span = 'post_views_today';
		}else if($time_span == 'week'){
			$time_span = 'post_views_week';
		}else if($time_span == 'month'){
			$time_span = 'post_views_month';
		}else if($time_span == 'halfyear'){
			$time_span = 'post_views_halfyear';
		}else if($time_span == 'year'){
			$time_span = 'post_views_year';
		}else{
			$time_span = 'post_views_total';
		}

		if($category_id != 0){
			$user_cat_tag = "INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
			if(is_array($category_id)) {
				  foreach($category_id as $catid){
				  	 $catid = intval($catid);
				  	 if($catid > 0){
				  	 		$include_ids[] = $catid;
				  	 }else{
				  	 	  $exlude_ids[] = -$catid;
				  	 }
				  }
				  if(!empty($include_ids)){
				  	 if(count($include_ids) != 1){
				  	 	 $cat_or_tag_include_sql = " $wpdb->term_taxonomy.term_id IN (".join(',', $include_ids).") ";
				  	 }else{
				  	 	 $cat_or_tag_include_sql = " $wpdb->term_taxonomy.term_id = $include_ids[0] ";
				  	 }
				  }else{
				  	 $cat_or_tag_include_sql = " 1=1 ";
				  }
				  if(!empty($exlude_ids)){
				  	 if(count($exlude_ids) != 1){
				  	 	 $cat_or_tag_exlude_sql = " $wpdb->term_taxonomy.term_id NOT IN (".join(',', $exlude_ids).") ";
				  	 }else{
				  	 	 $cat_or_tag_exlude_sql = " $wpdb->term_taxonomy.term_id != $exlude_ids[0] ";
				  	 }
				  }else{
				  	 $cat_or_tag_exlude_sql = " 1=1 ";
				  }
				  
				  $cat_or_tag_sql = " $wpdb->term_taxonomy.taxonomy = 'category' AND ".$cat_or_tag_include_sql." AND ".$cat_or_tag_exlude_sql;
			}else {
				  $catid = intval($category_id);
				  if($catid > 0){
							$cat_or_tag_sql = " $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id = $catid ";
				  }else{
				  	 	$catid = -$catid;
				  	 	$cat_or_tag_sql = " $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id != $catid ";
				  }
			}
		}else if($tag_id!=0){
				$user_cat_tag = "INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
				if(is_array($tag_id)) {
					foreach($tag_id as $tagid){
				  	 $tagid = intval($tagid);
				  	 if($tagid > 0){
				  	 		$include_ids[] = $tagid;
				  	 }else{
				  	 	  $exlude_ids[] = -$tagid;
				  	 }
					}
					
					if(!empty($include_ids)){
				  	 if(count($include_ids) != 1){
				  	 	 $cat_or_tag_include_sql = " $wpdb->term_taxonomy.term_id IN (".join(',', $include_ids).") ";
				  	 }else{
				  	 	 $cat_or_tag_include_sql = " $wpdb->term_taxonomy.term_id = $include_ids[0] ";
				  	 }
				  }else{
				  	 $cat_or_tag_include_sql = " 1=1 ";
				  }
				  if(!empty($exlude_ids)){
				  	 if(count($exlude_ids) != 1){
				  	 	 $cat_or_tag_exlude_sql = " $wpdb->term_taxonomy.term_id NOT IN (".join(',', $exlude_ids).") ";
				  	 }else{
				  	 	 $cat_or_tag_exlude_sql = " $wpdb->term_taxonomy.term_id != $exlude_ids[0] ";
				  	 }
				  }else{
				  	 $cat_or_tag_exlude_sql = " 1=1 ";
				  }
				  
				  $cat_or_tag_sql = " $wpdb->term_taxonomy.taxonomy = 'post_tag' AND ".$cat_or_tag_include_sql." AND ".$cat_or_tag_exlude_sql;
		 		}else{
		 	 	$tagid = intval($tag_id);
				if($tagid > 0){
						$cat_or_tag_sql = " $wpdb->term_taxonomy.taxonomy = 'post_tag' AND $wpdb->term_taxonomy.term_id = $tagid ";
				}else{
				  	$tagid = -$tagid;
				  	$cat_or_tag_sql = " $wpdb->term_taxonomy.taxonomy = 'post_tag' AND $wpdb->term_taxonomy.term_id != $tagid ";
				}
		 		}
		}else{
			    $user_cat_tag= '';
				  $cat_or_tag_sql = '1=1';
		}
		$order_by = strtolower($order_by);
		if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
				$orderby = 'desc';
		}
	
		$sql= "SELECT DISTINCT $wpdb->posts.*, (".$time_span." + 0) AS views, latest_view_time FROM $wpdb->posts LEFT JOIN ".WP_POST_VIEWS_TABLE." ON ".WP_POST_VIEWS_TABLE.".post_id = $wpdb->posts.ID   $user_cat_tag  WHERE post_date < '".current_time('mysql')."' AND post_status = 'publish' AND $cat_or_tag_sql AND view_type = '$view_type' AND $mode AND $time_span != 0 AND post_password = '' ORDER  BY $order_type $order_by LIMIT $limit";
		$post_viewed = $wpdb->get_results($sql);
		$count=0;
		
		if($post_viewed) {
			foreach ($post_viewed as $post) {
				$post_views = intval($post->views);
				$post_title = get_the_title();		
				$view_time = post_views_localtime($post->latest_view_time,post_views_timezone());
				if($chars > 0) {
						if(!function_exists('cut_str')){
								$post_title = snippet_text($post_title, $chars);
						}else{
								$post_title = cut_str($post_title, $chars);
						}
				}
				$pv_views[$count] = array('title' => '<a href="'.get_permalink().'"  class="with_bottom_a" >'.$post_title.'</a>', 'views' => number_format($post_views), 'time' => $view_time );
				$count++;
			}
		}
		return $pv_views;
}

function get_post_views($type = 'normal',$timespan = 'total') {
	global $wpdb,$post;
	
	if($timespan == 'today') {
    	$timespan = 'post_views_today';
	}else if($timespan == 'week') {
    	$timespan = 'post_views_week';
	}else if($timespan == 'month') {
    	$timespan = 'post_views_month';
	}else if($timespan == 'halfyear') {
    	$timespan = 'post_views_halfyear';
	}else if($timespan == 'year') {
    	$timespan = 'post_views_year';
	}else{
	 		$timespan = 'post_views_total';
	}
	
	$post_views =  intval($wpdb->get_var($wpdb->prepare("SELECT ".$timespan." FROM ".WP_POST_VIEWS_TABLE." where view_type='normal' and post_id=".$post->ID)));
	$post_robot_views =  intval($wpdb->get_var($wpdb->prepare("SELECT ".$timespan." FROM ".WP_POST_VIEWS_TABLE." where view_type='robot' and post_id=".$post->ID)));
	
	if ($type == 'robot') {
			return number_format($post_robot_views);
	}else {
			return number_format($post_views);
	}
}

function get_post_views_time($type = 'normal',$format='Y-m-d H:i:s'){
	global $wpdb,$post,$last_visited_time;

	if ($type == 'robot') {
		 if(empty($last_visited_time['robot'])){
		 	 	return _e('Hasn\'t been indexed before.','post-views');
		 }else{
		 	 	return post_views_localtime2($last_visited_time['robot'],post_views_timezone(),$format);
		 }		
	}else{
		 if(empty($last_visited_time['normal'])){
		 	 	return _e('Hasn\'t been viewed before.','post-views');
		 }else{
		 	 	return post_views_localtime2($last_visited_time['normal'],post_views_timezone(),$format);
		 }
	}
}

function get_post_views_total($type = 'normal',$timespan = 'total') {
	global $wpdb;
	
	if($timespan == 'today') {
    	$timespan = 'post_views_today';
	}else if($timespan == 'week') {
    	$timespan = 'post_views_week';
	}else if($timespan == 'month') {
    	$timespan = 'post_views_month';
	}else if($timespan == 'halfyear') {
    	$timespan = 'post_views_halfyear';
	}else if($timespan == 'year') {
    	$timespan = 'post_views_year';
	}else{
	 		$timespan = 'post_views_total';
	}
	if($type == 'normal') {
			$total_views = intval($wpdb->get_var("SELECT SUM(".$timespan.") FROM ".WP_POST_VIEWS_TABLE." WHERE view_type = 'normal'"));
			echo number_format($total_views);
	}else if($type = 'robot') {
			$total_robot_views = intval($wpdb->get_var("SELECT SUM(".$timespan.") FROM ".WP_POST_VIEWS_TABLE." WHERE view_type = 'robot'"));
			return number_format($total_robot_views);
	}
}

if(!function_exists('snippet_text')) {
	function snippet_text($text, $length = 0) {
		if (defined('MB_OVERLOAD_STRING')) {
		  $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
		 	if (mb_strlen($text) > $length) {
				return htmlentities(mb_substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
		 	} else {
				return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
		 	}
		} else {
			$text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
		 	if (strlen($text) > $length) {
				return htmlentities(substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
		 	} else {
				return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
		 	}
		}
	}
}

if(!function_exists(is_robot)){
	function is_robot($agent) {
		
		$is_robot = false;		
		if ($agent ==''){
			$is_robot = true;
		}
		if (strlen($agent) < 50){
			$is_robot = true;
		}
		$robots = array('Google Bot' => 'google', 'MSN Bot' => 'msn', 'Baidu Bot' => 'baidu', 'YaHoo Bot' => 'yahoo', 'Alexa' =>'alexa','SoSo Bot' => 'soso', 'Sogou Bot' => 'sogou', 'Spider Bot' => 'spider', 'Bot' => 'bot', 'Search Bot' => 'search', 'Alexa' => 'alexa');
		foreach ($robots as $name => $lookfor) { 
			if (stristr($agent, $lookfor) !== false) { 
					$is_robot = true;
					break;
			}
		}
		return $is_robot;
	}
}

function post_views_timezone(){
	$timezone = get_option('timezone_string');
	if (empty($timezone)){
		$x = floor(get_option('gmt_offset'));
		if ($x>0) $x="-$x";
		$timezone = "Etc/GMT$x";
	}
	return $timezone;
}

function post_views_localtime($utcTime,$timeZone){
	$dateTime = new DateTime($utcTime);
	$dateTime->setTimezone(new DateTimeZone($timeZone));
	return $dateTime->format("Y-m-d H:i:s");
}

function post_views_localtime2($utcTime,$timeZone,$format){
	$dateTime = new DateTime($utcTime);
	$dateTime->setTimezone(new DateTimeZone($timeZone));
	return $dateTime->format($format);
}


function get_time_span($latest_view_time){
		
	 $time_span['diff_d'] = false;
	 $time_span['diff_w'] = false;
	 $time_span['diff_m'] = false;
	 $time_span['diff_hy'] = false;
	 $time_span['diff_y'] = false;
	
	 $timezone = post_views_timezone();
	 $dateTime1 = new DateTime(date('Y-m-d H:i:s'));
	 $dateTime2 = new DateTime($latest_view_time);
	 
	 $dateTime1->setTimezone(new DateTimeZone($timezone));
	 $dateTime2->setTimezone(new DateTimeZone($timezone));
	 
	 $date1 =  (int)($dateTime1->format("z"));
	 $date2 =  (int)($dateTime2->format("z"));
	 $diff = $date1 - $date2;
	 if($diff > 0 )	$time_span['diff_d'] = true;

	 
	 $date1 =  (int)($dateTime1->format("W"));			
	 $date2 =  (int)($dateTime2->format("W"));
	 $diff = $date1 - $date2;
	 if($diff > 0 ) $time_span['diff_w'] = true;
	 
	 $date1 =  (int)($dateTime1->format("n"));			
	 $date2 =  (int)($dateTime2->format("n"));
	 $diff = $date1 - $date2;
	 if($diff > 0 ) $time_span['diff_m'] = true;
	 
	 $diff_1 = $date1 - 6;
	 $diff_2 = $date2 - 6;
	 // no need to judge whether is 12, for it has pass year!
	 if(($diff_1 > 0) && ($diff_2 < 1)) $time_span['diff_hy'] = true;
	 
	 $date1 =  (int)($dateTime1->format("Y"));			
	 $date2 =  (int)($dateTime2->format("Y"));
	 $diff = $date1 - $date2;
	 if($diff > 0 ) $time_span['diff_y'] = true;
	 
	 return $time_span;
}
?>
Return current item: post - views