<?php
/*
Version: 1.6.2
Author: Huseyin Berberoglu
Author URI: http://nxsn.com
*/

define( 'GP_META_KEY', "_gp_followers" );
define( 'GP_USER_OPTION_KEY', "gp_user_options" );
define( 'GP_COOKIE_KEY', "gp-follow-items");

// manage default privacy of users followed items lists by adding this constant to wp-config.php
if ( ! defined( 'GP_DEFAULT_PRIVACY_SETTING' ) ) {
    define( 'GP_DEFAULT_PRIVACY_SETTING', false );
}

$ajax_mode = 1;

function gp_follow_items() {
    if (isset($_REQUEST['wpfpaction'])) {
        global $ajax_mode;
        $ajax_mode = isset($_REQUEST['ajax']) ? $_REQUEST['ajax'] : false;
        if ($_REQUEST['wpfpaction'] == 'add') {
            gp_follow();
        } else if ($_REQUEST['wpfpaction'] == 'remove') {
            gp_unfollow();
        } else if ($_REQUEST['wpfpaction'] == 'clear') {
            if ( gp_clear_followed() ) {
            	gp_die_or_go( '<strong class="no-items-found">' . __( 'All items removed', 'gp_lang' ) . '</strong>' );
            } else {
            	gp_die_or_go( 'Error' );
            }	
        }
    }
}
add_action('wp_loaded', 'gp_follow_items');

function gp_follow( $post_id = '' ) {
	global $gp;
    if ( empty( $post_id ) ) $post_id = $_REQUEST['postid'];
    if ( $gp['hub_following_items'] == 'members' && ! is_user_logged_in() ) {
        gp_die_or_go( __( 'Only registered users can follow items.', 'gp_lang' ) );
        return false;
    }

    if ( gp_do_add_to_list($post_id) ) {
        do_action('gp_after_add', $post_id);
        gp_update_post_meta( $post_id, 1 );   	    
		$str = gp_follow_button( 1, "remove", 0, array( 'post_id' => $post_id ) );
		gp_die_or_go( $str );
    }
}
function gp_do_add_to_list($post_id) {
    if (gp_check_followed($post_id))
        return false;
    if (is_user_logged_in()) {
        return gp_add_to_usermeta($post_id);
    } else {
        return gp_set_cookie($post_id, "added");
    }
}

function gp_unfollow($post_id = "") {
	global $gp;
    if (empty($post_id)) $post_id = $_REQUEST['postid'];
    if (gp_do_unfollow($post_id)) {
        do_action('gp_after_remove', $post_id);
        gp_update_post_meta($post_id, -1);
		if ( isset($_REQUEST['page']) && $_REQUEST['page'] == 1 ) {
			$str = '';
		} else {
			$str = gp_follow_button(1, "add", 0, array( 'post_id' => $post_id ) );
		}
		gp_die_or_go($str);
     
    }
    else return false;
}

function gp_die_or_go( $str ) {
    global $ajax_mode;
    if ( $ajax_mode ) {
        die( $str );
    } else {
        wp_redirect( $_SERVER['HTTP_REFERER'] );
    }
}

function gp_add_to_usermeta($post_id) {
    $gp_followed = gp_get_user_meta();
    $gp_followed[] = $post_id;
    gp_update_user_meta($gp_followed);
    return true;
}

function gp_check_followed($cid) {
    if (is_user_logged_in()) {
        $following_page_ids = gp_get_user_meta();
        if ($following_page_ids)
            foreach ($following_page_ids as $fpost_id)
                if ($fpost_id == $cid) return true;
	} else {
	    if (gp_get_cookie()):
	        foreach (gp_get_cookie() as $fpost_id => $val)
	            if ($fpost_id == $cid) return true;
	    endif;
	}
    return false;
}

function gp_follow_button( $return = 0, $action = "", $show_span = 1, $args = array() ) {
	$post_id = $GLOBALS['gp_post_id'];
    extract($args);
   
    $str = '<span class="wpfp-span">';

    if ($action == "remove"):
        $str .= gp_follow_button_html($post_id, __( 'Unfollow', 'gp_lang' ), "remove");
    elseif ($action == "add"):
        $str .= gp_follow_button_html($post_id, __( 'Follow', 'gp_lang' ), "add");
    elseif (gp_check_followed($post_id)):
        $str .= gp_follow_button_html($post_id, __( 'Unfollow', 'gp_lang' ), "remove");
    else:
        $str .= gp_follow_button_html($post_id, __( 'Follow', 'gp_lang' ), "add");
    endif;
    
    $str .= '</span>';

    if ( $return ) {
    	return $str;
    } else {
    	echo html_entity_decode( $str );
    }
}

function gp_follow_button_html($post_id, $opt, $action) {
    $link = "<a class='wpfp-link follow-item' href='?wpfpaction=".$action."&amp;postid=". $post_id . "' title='". $opt ."' rel='nofollow'>" . gp_loader() . $opt . "</a>";
    $link = apply_filters( 'gp_follow_button_html', $link );
    return $link;
}

function gp_get_users_following($user = "") {
    $following_page_ids = array();

    if (!empty($user)):
        return gp_get_user_meta($user);
    endif;

    # collect favorites from cookie and if user is logged in from database.
    if (is_user_logged_in()):
        $following_page_ids = gp_get_user_meta();
	else:
	    if (gp_get_cookie()):
	        foreach (gp_get_cookie() as $post_id => $post_title) {
	            array_push($following_page_ids, $post_id);
	        }
	    endif;
	endif;
    return $following_page_ids;
}

function gp_list_follow_items( $args = array() ) {
    $user = isset($_REQUEST['user']) ? $_REQUEST['user'] : "";
    extract($args);
    global $following_page_ids;
    if ( !empty($user) ) {
        if ( gp_is_user_favlist_public($user) )
            $following_page_ids = gp_get_users_following($user);

    } else {
        $following_page_ids = gp_get_users_following();
    }

}

function gp_list_most_followed($limit=5) {
    global $wpdb;
    $query = "SELECT post_id, meta_value, post_status FROM $wpdb->postmeta";
    $query .= " LEFT JOIN $wpdb->posts ON post_id=$wpdb->posts.ID";
    $query .= " WHERE post_status='publish' AND meta_key='".GP_META_KEY."' AND meta_value > 0 ORDER BY ROUND(meta_value) DESC LIMIT 0, $limit";
    $results = $wpdb->get_results($query);
    if ($results) {
        echo "<ul>";
        foreach ($results as $o):
            $p = get_post($o->post_id);
            echo "<li>";
            echo "<a href='".get_permalink($o->post_id)."' title='". $p->post_title ."'>" . $p->post_title . "</a> ($o->meta_value)";
            echo "</li>";
        endforeach;
        echo "</ul>";
    }
}

function gp_loader() {
    return '<span class="fa-spin follow-loader"></span>';
}

function gp_clear_followed() {
    if (gp_get_cookie()):
        foreach (gp_get_cookie() as $post_id => $val) {
            gp_set_cookie($post_id, "");
            gp_update_post_meta($post_id, -1);
        }
    endif;
    if (is_user_logged_in()) {
        $following_page_ids = gp_get_user_meta();
        if ($following_page_ids):
            foreach ($following_page_ids as $post_id) {
                gp_update_post_meta($post_id, -1);
            }
        endif;
        if (!delete_user_meta(gp_get_user_id(), GP_META_KEY)) {
            return false;
        }
    }
    return true;
}

function gp_do_unfollow($post_id) {
    if (!gp_check_followed($post_id))
        return true;

    $a = true;
    if (is_user_logged_in()) {
        $user_following = gp_get_user_meta();
        $user_following = array_diff($user_following, array($post_id));
        $user_following = array_values($user_following);
        $a = gp_update_user_meta($user_following);
    }
    if ($a) $a = gp_set_cookie($_REQUEST['postid'], "");
    return $a;
}

function gp_update_user_meta($arr) {
    return update_user_meta(gp_get_user_id(),GP_META_KEY,$arr);
}

function gp_update_post_meta($post_id, $val) {
	$oldval = gp_get_post_meta($post_id);
	if ($val == -1 && $oldval == 0) {
    	$val = 0;
	} else {
		$val = $oldval + $val;
	}
    return add_post_meta($post_id, GP_META_KEY, $val, true) or update_post_meta($post_id, GP_META_KEY, $val);
}

function gp_delete_post_meta($post_id) {
    return delete_post_meta($post_id, GP_META_KEY);
}

function gp_get_cookie() {
    if (!isset($_COOKIE[GP_COOKIE_KEY])) return;
    return $_COOKIE[GP_COOKIE_KEY];
}

function gp_get_user_id() {
    global $current_user;
    get_currentuserinfo();
    return $current_user->ID;
}

function gp_get_user_meta($user = "") {
    if (!empty($user)):
        $userdata = get_user_by( 'login', $user );
        $user_id = $userdata->ID;
        return get_user_meta($user_id, GP_META_KEY, true);
    else:
        return get_user_meta(gp_get_user_id(), GP_META_KEY, true);
    endif;
}

function gp_get_post_meta($post_id) {
    $val = get_post_meta($post_id, GP_META_KEY, true);
    if ($val < 0) $val = 0;
    return $val;
}

function gp_set_cookie($post_id, $str) {
    $expire = time()+60*60*24*30;
    return setcookie("gp-follow-items[$post_id]", $str, $expire, "/");
}

function gp_is_user_favlist_public($user) {
    $user_opts = gp_get_user_options($user);
    if (empty($user_opts)) return GP_DEFAULT_PRIVACY_SETTING;
    if ($user_opts["is_gp_list_public"])
        return true;
    else
        return false;
}

function gp_get_user_options($user) {
    $userdata = get_user_by( 'login', $user );
    $user_id = $userdata->ID;
    return get_user_meta($user_id, GP_USER_OPTION_KEY, true);
}

function gp_is_user_can_edit() {
    if (isset($_REQUEST['user']) && $_REQUEST['user'])
        return false;
    return true;
}

function gp_remove_follow_button( $post_id ) {
    if ( gp_is_user_can_edit() && ( is_page_template( 'following-template.php' ) OR ( isset( $_GET['type'] ) && $_GET['type'] == 'following-template' ) ) ) {
        $link = "<a id='rem_$post_id' class='wpfp-link unfollow-item button' href='?wpfpaction=remove&amp;page=1&amp;postid=". $post_id ."' title='". __( 'Remove', 'gp_lang' ) ."' rel='nofollow'>" . __( 'Remove', 'gp_lang' ) . "</a>";
        $link = apply_filters( 'gp_remove_follow_button', $link );
        echo html_entity_decode( $link );
    }
}

function gp_clear_list_link() {
    if ( gp_is_user_can_edit() ) {
        echo "<a class='wpfp-link unfollow-all-items button' href='?wpfpaction=clear' rel='nofollow'>" . gp_loader() . __( 'Unfollow All Items', 'gp_lang' ) . "</a>";
    }
}

function gp_cookie_warning() {
    if ( ! is_user_logged_in() && ! isset($_GET['user'] ) ) {
        echo '<div class="cookie-notice">' . __( 'If you clear your cookies these items will be deleted. Please login so you can save items to your account.', 'gp_lang' ) . '</div>';
   }
}

?>