<?php
/**
 *	Kolor
 *
 *	Theme by: Art Ramadani
 *	Developed by: Arlind Nushi
 *
 *	www.mobanbus.cn
 *
 *	WordPress Module for adding 'Like' feature to the posts!
 */


/* Like Portfolio Item */
function like_portfolio_item($post_id, $is_gallery_item = FALSE)
{
	$post = get_post($post_id);
	
	if($is_gallery_item)
		$portfolio_options = get_gallery_options();
	else
		$portfolio_options = get_portfolio_options();
		
	extract($portfolio_options);
	
	if( ! $allow_likes)
		return FALSE;
	
	if($post)
	{			
		$liked_status = is_portfolio_item_liked($post_id, $is_gallery_item);
		
		if($portfolio_unlike_support == 'yes' || $liked_status == -1)
		{
			$post_likes = get_portfolio_item_likes($post_id);
			
			if($portfolio_unlike_support == 'yes' && $liked_status == 1)
			{
				unset($post_likes[LABORATOR_LIKE_ARR_KEY]);
			}
			else
				$post_likes[LABORATOR_LIKE_ARR_KEY] = array('time' => time(), 'ip' => $ip, 'user' => get_current_user_id());
			
			update_post_meta($post_id, 'laborator_post_likes', $post_likes);
			
			return $portfolio_unlike_support == 'yes' && $liked_status == 1 ? -2 : 1;
		}
		else
		{
			return -1;
		}
	}
	
	return 0;
}


/* Check If portfolio item is liked */
function is_portfolio_item_liked($post_id, $is_gallery_item = FALSE)
{
	global $post;
	
	if( ! $post)
		$post = get_post($post_id);
		
	$status = 0;
	
	if($post)
	{
		if($is_gallery_item)
			$portfolio_options = get_gallery_options();
		else
			$portfolio_options = get_portfolio_options();
			
		extract($portfolio_options);
		
		$post_likes = get_portfolio_item_likes($post_id);
			
		$arr_key = '';
		
		$session_id = session_id();
		$ip = $_SERVER['REMOTE_ADDR'];
		
		switch($like_logging_method)
		{
			case 'cookie':
				$arr_key = $session_id;
				
				if( ! $post_likes[$session_id])
				{
					$status = -1;
				}
				else
				{
					$status = 1;
				}
				
				break;
				
			default:
				$arr_key = $ip;
				
				if( ! isset($post_likes[$ip]))
				{
					$status = -1;
				}
				else
				{
					$status = 1;
				}
		}
		
		if( ! defined("LABORATOR_LIKE_ARR_KEY"))
			define("LABORATOR_LIKE_ARR_KEY", $arr_key);
	}
	
	return $status;
}


/* Get Likes for a portfolio item */
function get_portfolio_item_likes($post_id, $count = FALSE)
{
	$post_likes = get_post_meta($post_id, 'laborator_post_likes', TRUE);
		
	if( ! is_array($post_likes))
		$post_likes = array();
	
	if($count)
		return count($post_likes);
	
	return $post_likes;
}



/* Process Actions via admin-ajax.php */
add_action('wp_ajax_portfolio_like_item', 'portfolio_like_item_process');
add_action('wp_ajax_nopriv_portfolio_like_item', 'portfolio_like_item_process');

function portfolio_like_item_process()
{
	$is_gallery_item = $_POST['is_gallery_item'];
	
	if($is_gallery_item)
		check_ajax_referer('LaboratorLikeGalleryItem', 'nonce');
	else
		check_ajax_referer('LaboratorLikePortfolioItem', 'nonce');

	extract($_POST);
	
	
	echo like_portfolio_item($ID, $is_gallery_item);
		
	die();
}