Amy-Mir / inc / interaction-system.php
interaction-system.php
Raw
<?php
/**
 * Custom functions that is dependent of the theme styles
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Register the stylesheets for the public-facing side of the site.
 */
add_action( 'wp_enqueue_scripts', 'sl_enqueue_scripts' );

function sl_enqueue_scripts() {
	wp_enqueue_script( 'simple-likes-public-js', get_template_directory_uri() . '/js/simple-likes-public.js', array( 'jquery' ), '0.5', false );
	wp_localize_script( 'simple-likes-public-js', 'simpleLikes', array(
		'ajaxurl' => admin_url( 'admin-ajax.php' ),
		'like' => __( 'Like', 'AMY-MIR-JRDESIGN-RUSH2DI' ),
		'unlike' => __( 'Unlike', 'AMY-MIR-JRDESIGN-RUSH2DI' )
	) ); 
}

/**
 * Processes like/unlike
 */
add_action( 'wp_ajax_nopriv_process_simple_like', 'process_simple_like' );
add_action( 'wp_ajax_process_simple_like', 'process_simple_like' );

function process_simple_like() {
	// Security
	$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( $_REQUEST['nonce'] ) : 0;
	if ( !wp_verify_nonce( $nonce, 'simple-likes-nonce' ) ) {
		exit( __( 'Not permitted', 'AMY-MIR-JRDESIGN-RUSH2DI' ) );
	}
	// Test if javascript is disabled
	$disabled = ( isset( $_REQUEST['disabled'] ) && $_REQUEST['disabled'] == true ) ? true : false;
	// Base variables
	$post_id = ( isset( $_REQUEST['post_id'] ) && is_numeric( $_REQUEST['post_id'] ) ) ? $_REQUEST['post_id'] : '';
	$result = array();
	$post_users = NULL;
	$like_count = 0;
	// Get plugin options
	if ( $post_id != '' ) {
		$count = get_post_meta( $post_id, "_post_like_count", true ); // like count
		$count = ( isset( $count ) && is_numeric( $count ) ) ? $count : 0;
		if ( !already_liked( $post_id ) ) { // Like the post
			if ( is_user_logged_in() ) { // user is logged in
				$user_id = get_current_user_id();
				$post_users = post_user_likes( $user_id, $post_id );

				// Update User & Post
				$user_like_count = get_user_option( "_user_like_count", $user_id );
				$user_like_count =  ( isset( $user_like_count ) && is_numeric( $user_like_count ) ) ? $user_like_count : 0;
				update_user_option( $user_id, "_user_like_count", ++$user_like_count );
				if ( $post_users ) {
					update_post_meta( $post_id, "_user_liked", $post_users );
				}

			} else { // user is anonymous
				$user_ip = sl_get_ip();
				$post_users = post_ip_likes( $user_ip, $post_id );
				// Update Post
				if ( $post_users ) {
					update_post_meta( $post_id, "_user_IP", $post_users );
				}
			}
			$like_count = ++$count;
			$response['status'] = "liked";
			$response['icon'] = get_liked_icon();
		} else { // Unlike the post
			if ( is_user_logged_in() ) { // user is logged in
				$user_id = get_current_user_id();
				$post_users = post_user_likes( $user_id, $post_id );
				// Update User
				$user_like_count = get_user_option( "_user_like_count", $user_id );
				$user_like_count =  ( isset( $user_like_count ) && is_numeric( $user_like_count ) ) ? $user_like_count : 0;
				if ( $user_like_count > 0 ) {
					update_user_option( $user_id, '_user_like_count', --$user_like_count );
				}
				// Update Post
				if ( $post_users ) {	
					$uid_key = array_search( $user_id, $post_users );
					unset( $post_users[$uid_key] );
					update_post_meta( $post_id, "_user_liked", $post_users );
				}
			} else { // user is anonymous
				$user_ip = sl_get_ip();
				$post_users = post_ip_likes( $user_ip, $post_id );
				// Update Post
				if ( $post_users ) {
					$uip_key = array_search( $user_ip, $post_users );
					unset( $post_users[$uip_key] );
					update_post_meta( $post_id, "_user_IP", $post_users );
				}
			}
			$like_count = ( $count > 0 ) ? --$count : 0; // Prevent negative number
			$response['status'] = "unliked";
			$response['icon'] = get_unliked_icon();
		}

		update_post_meta( $post_id, "_post_like_count", $like_count );
		update_post_meta( $post_id, "_post_like_modified", date( 'Y-m-d H:i:s' ) );

		$response['count'] = get_like_count( $like_count );
		if ( $disabled == true ) {
			wp_redirect( get_permalink( $post_id ) );
			exit();
		} else {
			wp_send_json( $response );
		}
	}
}

/**
 * Utility to test if the post is already liked
 * @since    0.5
 */
function already_liked( $post_id ) {
	$post_users = NULL;
	$user_id = NULL;
	if ( is_user_logged_in() ) { // user is logged in
		$user_id = get_current_user_id();
		$post_meta_users = get_post_meta( $post_id, "_user_liked" );
		if ( count( $post_meta_users ) != 0 ) {
			$post_users = $post_meta_users[0];
		}
	} else { // user is anonymous
		$user_id = sl_get_ip();
		$post_meta_users = get_post_meta( $post_id, "_user_IP" ); 
		if ( count( $post_meta_users ) != 0 ) { // meta exists, set up values
			$post_users = $post_meta_users[0];
		}
	}
	if ( is_array( $post_users ) && in_array( $user_id, $post_users ) ) {
		return true;
	} else {
		return false;
	}
} // already_liked()

/**
 * Output the like button
 */
function get_simple_likes_button( $post_id, $template = NULL ) {
	$output = '';
	$nonce = wp_create_nonce( 'simple-likes-nonce' ); // Security
	
	$post_id_class = esc_attr( ' sl-button-' . $post_id );
	$comment_class = esc_attr( '' );
	$like_count = get_post_meta( $post_id, "_post_like_count", true );
	$like_count = ( isset( $like_count ) && is_numeric( $like_count ) ) ? $like_count : 0;
	
	$count = get_like_count( $like_count );
	$icon_empty = get_unliked_icon();
	$icon_full = get_liked_icon();
	$loader = '<span id="inter__loader"></span>';
	$icon_cmnt = '<span class="far fa-comment-alt"></span>';
	$cmnt_count = '<span class="inter__count">' . get_comment_count($post_id)["approved"] . '</span>';
	$cmnt_wrapper = '<div>' . $icon_cmnt . $cmnt_count . '</div>';
	// Liked/Unliked Variables
	if ( already_liked( $post_id ) ) {
		$class = esc_attr( ' liked' );
		$title = __( 'Unlike', 'AMY-MIR-JRDESIGN-RUSH2DI' );
		$icon = $icon_full;
	} else {
		$class = '';
		$title = __( '0', 'AMY-MIR-JRDESIGN-RUSH2DI' );
		$icon = $icon_empty;
	}
	$template = $template !== NULL ? $template : "";
	$output = '<div class="inter__wrapper ' . $template. '"><a href="' . admin_url( 'admin-ajax.php?action=process_simple_like' . '&post_id=' . $post_id . '&nonce=' . $nonce . '&disabled=true' ) . '" class="sl-button' . $post_id_class . $class . $comment_class . '" data-nonce="' . $nonce . '" data-post-id="' . $post_id  . '" title="' . $title . '">' . $icon . $count . '</a>' . $cmnt_wrapper . $loader . '</div>';
	return $output;
} 

/**
 * Processes shortcode to manually add the button to posts
 */
add_shortcode( 'jmliker', 'sl_shortcode' );
function sl_shortcode() {
	return get_simple_likes_button( get_the_ID(), 0 );
} // shortcode()

/**
 * Utility retrieves post meta user likes (user id array), 
 * then adds new user id to retrieved array
 */
function post_user_likes( $user_id, $post_id ) {
	$post_users = '';
	$post_meta_users = get_post_meta( $post_id, "_user_liked" );
	if ( count( $post_meta_users ) != 0 ) {
		$post_users = $post_meta_users[0];
	}
	if ( !is_array( $post_users ) ) {
		$post_users = array();
	}
	if ( !in_array( $user_id, $post_users ) ) {
		$post_users['user-' . $user_id] = $user_id;
	}
	return $post_users;
} // post_user_likes()

/**
 * Utility retrieves post meta ip likes (ip array), 
 * then adds new ip to retrieved array
 */
function post_ip_likes( $user_ip, $post_id ) {
	$post_users = '';
	$post_meta_users = get_post_meta( $post_id, "_user_IP" );
	// Retrieve post information
	if ( count( $post_meta_users ) != 0 ) {
		$post_users = $post_meta_users[0];
	}
	if ( !is_array( $post_users ) ) {
		$post_users = array();
	}
	if ( !in_array( $user_ip, $post_users ) ) {
		$post_users['ip-' . $user_ip] = $user_ip;
	}
	return $post_users;
} 

/**
 * Utility to retrieve IP address
 */
function sl_get_ip() {
	if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) && ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) && ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
		$ip = ( isset( $_SERVER['REMOTE_ADDR'] ) ) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
	}
	$ip = filter_var( $ip, FILTER_VALIDATE_IP );
	$ip = ( $ip === false ) ? '0.0.0.0' : $ip;
	return $ip;
} 

/**
 * Utility returns the button icon for "like" action
 */
function get_liked_icon() {
	/* If already using Font Awesome with your theme, replace svg with: <i class="fa fa-heart"></i> */
	$icon = '<span class="fas fa-heart"></span>';
	return $icon;
}

/**
 * Utility returns the button icon for "unlike" action
 */
function get_unliked_icon() {
	/* If already using Font Awesome with your theme, replace svg with: <i class="fa fa-heart-o"></i> */
	$icon = '<span class="far fa-heart"></span>';
	return $icon;
}

/**
 * Utility function to format the button count,
 * appending "K" if one thousand or greater,
 * "M" if one million or greater,
 * and "B" if one billion or greater (unlikely).
 * $precision = how many decimal points to display (1.25K)
 */
function sl_format_count( $number ) {
	$precision = 2;
	if ( $number >= 1000 && $number < 1000000 ) {
		$formatted = number_format( $number/1000, $precision ).'K';
	} else if ( $number >= 1000000 && $number < 1000000000 ) {
		$formatted = number_format( $number/1000000, $precision ).'M';
	} else if ( $number >= 1000000000 ) {
		$formatted = number_format( $number/1000000000, $precision ).'B';
	} else {
		$formatted = $number; // Number is less than 1000
	}
	$formatted = str_replace( '.00', '', $formatted );
	return $formatted;
} // sl_format_count()

/**
 * Utility retrieves count plus count options, 
 * returns appropriate format based on options
 * @since    0.5
 */
function get_like_count( $like_count ) {
	$like_text = __( '0', 'AMY-MIR-JRDESIGN-RUSH2DI' );
	if ( is_numeric( $like_count ) && $like_count > 0 ) { 
		$number = sl_format_count( $like_count );
	} else {
		$number = $like_text;
	}
	$count = '<span class="inter__count">' . $number . '</span>';
	return $count;
} // get_like_count()

// User Profile List
add_action( 'show_user_profile', 'show_user_likes' );
add_action( 'edit_user_profile', 'show_user_likes' );

function show_user_likes( $user ) { ?>
<table class="form-table">
    <tr>
        <th><label for="user_likes"><?php _e( 'You Like:', 'AMY-MIR-JRDESIGN-RUSH2DI' ); ?></label></th>
        <td>
            <?php
			$types = get_post_types( array( 'public' => true ) );
			$args = array(
			  'numberposts' => -1,
			  'post_type' => $types,
			  'meta_query' => array (
				array (
				  'key' => '_user_liked',
				  'value' => $user->ID,
				  'compare' => 'LIKE'
				)
			  ) );		
			$sep = '';
			$like_query = new WP_Query( $args );
			if ( $like_query->have_posts() ) : ?>
            <p>
                <?php while ( $like_query->have_posts() ) : $like_query->the_post(); 
			echo $sep; ?><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
                <?php
			$sep = ' &middot; ';
			endwhile; 
			?>
            </p>
            <?php else : ?>
            <p><?php _e( 'You do not like anything yet.', 'AMY-MIR-JRDESIGN-RUSH2DI' ); ?></p>
            <?php 
			endif; 
			wp_reset_postdata(); 
			?>
        </td>
    </tr>
</table>
<?php } // show_user_likes()