File: /home/kashmira/public_html/razitahir.com/wp-content/plugins/upress-widgets/inc/db.php
<?php
if ( ! defined( 'ABSPATH' ) ) {
	// Exit if accessed directly.
	exit;
}
function upress_post_views_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upress_post_views';
    if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE {$table_name} (
            ID INT(11) NOT NULL AUTO_INCREMENT,
            post_id INT(11) NOT NULL,
            post_type VARCHAR(255) NOT NULL,
            ip VARCHAR(255) NOT NULL,
            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (ID)
        ) {$charset_collate};";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
}
function upress_store_views($post_id, $type = 'post') {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upress_post_views';
    $post_type = $type;
    // Get the visitor's IP address
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip_address = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip_address = $_SERVER['REMOTE_ADDR'];
    }
    // Check if the current IP already exists for the given post ID
    $existing_view = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT ID FROM {$table_name} WHERE post_id = %d AND ip = %s",
            $post_id,
            $ip_address,
        )
    );
    // If the IP does not exist, insert a new row with the post ID and IP
    if (!$existing_view) {
        $wpdb->insert(
            $table_name,
            array(
                'post_id' => $post_id,
                'ip'      => $ip_address,
                'post_type' => $post_type,
            ),
            array('%d', '%s', '%s')
        );
    }
}
function upress_get_views_count($post_id) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upress_post_views';
    $views_count = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$table_name} WHERE post_id = %d",
            $post_id
        )
    );
    return $views_count;
}
function upress_most_viewed_posts($limit = 10, $type = 'post') {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upress_post_views';
    $post_type = $type;
    //print_r($interval);
    $post_ids = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT post_id, COUNT(*) AS view_count
            FROM {$table_name}
            WHERE post_type = %s
            GROUP BY post_id
            ORDER BY view_count DESC
            LIMIT %d",
            $post_type,
            $limit,
        )
    );
    return $post_ids;
}