/**
 * membership accessible/purchasable contents 
 * 
 * @since 2.6.0
 *
 * @param array|string $membership_types
 * @param string $type ( accessible|purchasable )
 * @param int $user_id
 * @param string $posttype ( post|page|custom_post_type )
 * @param int $limit
 * @return array
 */
function mgm_get_membership_contents($membership_types, $type = 'accessible', $user_id = NULL, $post_type = NULL, $limit = NULL)
{
    global $wpdb;
    // issue #920
    $user = wp_get_current_user();
    $temp_member = new stdClass();
    $extended_protection = mgm_get_class('system')->setting['content_hide_by_membership'];
    // membership types
    if (!is_array($membership_types)) {
        $membership_types = array($membership_types);
    }
    // sql per page
    $limit_per_page = 50;
    $limit_clause = '';
    // limit
    if (!$limit || !isset($_GET['section']) || isset($_GET['section']) && $_GET['section'] != $type) {
        $limit_clause = 'LIMIT ' . $limit_per_page;
    }
    // get types
    $post_types_in = $post_type ? mgm_map_for_in(array($post_type)) : mgm_get_post_types(true);
    // from
    $sql_from = " FROM " . $wpdb->posts . " A JOIN " . $wpdb->postmeta . " B ON (A.ID = B.post_id ) \r\r\n\t\t\t      WHERE post_status = 'publish' AND B.meta_key LIKE '_mgm_post%' AND post_type IN ({$post_types_in}) ";
    // get count first
    $total_post_rows = $wpdb->get_var("SELECT COUNT(* ) AS total_post_rows {$sql_from}");
    // update limit if less posts availble
    if (!empty($limit_clause) && $total_post_rows > $limit_per_page) {
        $limit_clause = 'LIMIT ' . $total_post_rows;
    }
    // get posts
    $results = $wpdb->get_results("SELECT DISTINCT(ID), post_name, post_title, post_date, post_content {$sql_from} ORDER BY post_date DESC {$limit_clause}");
    // for purchasable only, get purchased posts
    if ($type == 'purchasable') {
        // sql
        $sql = $wpdb->prepare("SELECT `post_id` FROM `" . TBL_MGM_POST_PURCHASES . "` WHERE `user_id` = %d", $user_id);
        // purchased
        $purchased = $wpdb->get_results($sql);
        // init
        $purchased_posts = array();
        // check
        if (count($purchased) > 0) {
            // loop
            foreach ($purchased as $id => $obj) {
                // set
                $purchased_posts[] = $obj->post_id;
            }
        }
    }
    // init
    $posts = array();
    // store
    if (count($results) > 0) {
        // set counter
        $total_posts = 0;
        // per page
        $posts_per_page = 5;
        // loop
        foreach ($results as $id => $obj) {
            // post object
            $post_obj = mgm_get_post($obj->ID);
            //access delay - issue #920
            $access_delay = $post_obj->access_delay;
            // post access membership types
            $access_membership_types = $post_obj->get_access_membership_types();
            //issue #1376
            $post_category_access_membership_types = mgm_get_post_category_access_membership_types($obj->ID);
            //merging category access/ post accesss
            $access_membership_types = array_merge($access_membership_types, $post_category_access_membership_types);
            //gettign unique access members
            $access_membership_types = array_unique($access_membership_types);
            // branch
            switch ($type) {
                case 'accessible':
                    // multiple membership level purchase(issue#: 400) modification
                    if (array_diff($access_membership_types, $membership_types) != $access_membership_types) {
                        //if any match found
                        // issue #920
                        $access = true;
                        if ($extended_protection == 'Y') {
                            $temp_member->membership_type = $membership_types[0];
                            if (mgm_check_post_access_delay($temp_member, $user, $access_delay)) {
                                //okey
                            } else {
                                $access = false;
                            }
                        }
                        if ($access) {
                            // increment
                            $total_posts++;
                            // store
                            if ($limit != '' && $total_posts <= $posts_per_page || $limit == '') {
                                $posts[] = $obj;
                            }
                        }
                    }
                    break;
                case 'purchasable':
                    // multiple membership level purchase(issue#: 400) modification
                    if (bool_from_yn($post_obj->purchasable) && array_diff($access_membership_types, $membership_types) == $access_membership_types) {
                        //if no match
                        // not purchased
                        if (!in_array($obj->ID, $purchased_posts)) {
                            // issue #920
                            $access = true;
                            if ($extended_protection == 'Y') {
                                $temp_member->membership_type = $membership_types[0];
                                if (mgm_check_post_access_delay($temp_member, $user, $access_delay)) {
                                    //okey
                                } else {
                                    $access = false;
                                }
                            }
                            if ($access) {
                                // increment
                                $total_posts++;
                                // store
                                if ($limit != '' && $total_posts <= $posts_per_page || $limit == '') {
                                    // fetch post price
                                    $obj->purchase_cost = mgm_convert_to_currency($post_obj->purchase_cost);
                                    // store
                                    $posts[] = $obj;
                                }
                            }
                        }
                    }
                    break;
            }
            // unset
            unset($post_obj);
        }
    }
    // reset total
    if (empty($posts)) {
        $total_posts = 0;
    }
    // pager
    $pager = '';
    /*if($total_post_rows > $limit_per_page){	
    		$pager 	= sprintf('<a href="%s">%s</a>', mgm_get_custom_url('membership_contents', false, array('page'=>2)), __('next','mgm'));
    	}*/
    // return
    return array('total_posts' => $total_posts, 'posts' => $posts, 'total_post_rows' => $total_post_rows, 'pager' => $pager);
}
/**
 * exclude post/pages by membership type
 *
 * @param int $user_id
 * @param string $content_type
 * @return string
 */
function mgm_content_exclude_by_user($user_id = 0, $content_type = 'category')
{
    // not for admin
    if (is_super_admin()) {
        return array();
    }
    // global
    global $wpdb;
    // system
    $system_obj = mgm_get_class('system');
    // protecction
    $content_hide_by_membership = $system_obj->get_setting('content_hide_by_membership');
    // get member
    $member = mgm_get_member($user_id);
    $user = wp_get_current_user();
    $temp_member = new stdClass();
    $membership_type = $member->membership_type;
    // set default
    $membership_type = empty($membership_type) ? 'guest' : $membership_type;
    //get user membership types: multiple level membership issue#: 400 modification
    $arr_mt = mgm_get_subscribed_membershiptypes($user_id, $member);
    // store
    if (!in_array($membership_type, $arr_mt)) {
        $arr_mt[] = $membership_type;
    }
    // on type
    switch ($content_type) {
        case 'category':
        case 'taxonomy':
            // category
            if (!($hide_terms = wp_cache_get($content_type . '_exclusion_' . $user_id, 'users'))) {
                // exclude protected terms
                $hide_terms = array();
                // get post terms settings
                $post_terms = mgm_get_class('post_' . $content_type);
                // loop set
                foreach ($post_terms->get_access_membership_types() as $term_id => $membership_types) {
                    // exclude
                    if ($membership_types) {
                        // not set public access
                        // multiple level membership issue#: 400 modification
                        if (array_diff($membership_types, $arr_mt) != $membership_types) {
                            continue;
                        }
                        // hide
                        $hide_terms[] = $term_id;
                    }
                }
                // set cache
                wp_cache_set($content_type . '_exclusion_' . $user_id, $hide_terms, 'users');
            }
            // return
            return $hide_terms;
            // end check
            break;
        case 'post':
            // post
            // $content_hide_by_membership = $system_obj->get_setting('content_hide_by_membership');
            // no check if not required
            if (!bool_from_yn($content_hide_by_membership)) {
                return array();
            }
            // check
            if (!($hide_posts = wp_cache_get('post_exclusion_' . $user_id, 'users'))) {
                // exclude protected posts
                $hide_posts = array();
                // fetch all posts
                $posts = $wpdb->get_results("SELECT ID FROM `{$wpdb->posts}` WHERE `post_type` NOT IN('revision','attachment')");
                // check
                if ($posts) {
                    // loop
                    foreach ($posts as $post) {
                        // get post
                        $post_obj = mgm_get_post($post->ID);
                        $access_delay = $post_obj->access_delay;
                        // check types
                        if (is_array($post_obj->access_membership_types) && count($post_obj->access_membership_types)) {
                            // default
                            $access = false;
                            // check
                            foreach ($post_obj->access_membership_types as $a_membership_type) {
                                // match
                                // multiple level membership issue#: 400 modification
                                if (in_array($a_membership_type, $arr_mt)) {
                                    // done
                                    $access = true;
                                    // check protection
                                    if (bool_from_yn($content_hide_by_membership)) {
                                        // temp
                                        $temp_member->membership_type = $a_membership_type;
                                        //deny access if delay: issue#: 516
                                        if (mgm_check_post_access_delay($temp_member, $user, $access_delay)) {
                                            //OK:
                                            break;
                                        } else {
                                            $access = false;
                                        }
                                    }
                                }
                            }
                            //issue #841
                            if (bool_from_yn($post_obj->purchasable)) {
                                $access = true;
                            }
                            // protect
                            if (!$access) {
                                $hide_posts[] = $post->ID;
                            }
                        }
                        // unset
                        unset($post_obj);
                    }
                }
                // set cache
                wp_cache_set('post_exclusion_' . $user_id, $hide_posts, 'users');
            }
            // return
            return $hide_posts;
            // end check
            break;
    }
    // empty
    return array();
}
function mgm_content_post_access_delay($args = array())
{
    global $user_data, $wpdb;
    // current user
    $current_user = wp_get_current_user();
    // get user by username
    if (isset($_GET['username']) && isset($_GET['password'])) {
        // ? who did this? and why
        $user = wp_authenticate(strip_tags($_GET['username']), strip_tags($_GET['password']));
    } else {
        if (is_feed() && isset($_GET['token']) && mgm_use_rss_token()) {
            // added feed check while updating iss#676
            // get user by rss token, only for feed
            $user = mgm_get_user_by_token(strip_tags($_GET['token']));
        } else {
            // else get current use if logged in
            $user = $current_user;
        }
    }
    //init
    $access_delay = array();
    //check
    if (isset($args['postdelay']) && !empty($args['postdelay'])) {
        $postdelay_membership_levels = explode(',', $args['postdelay']);
        foreach ($postdelay_membership_levels as $postdelay_membership_level) {
            if ($postdelay_membership_level) {
                $postdelay_membership_level = explode(':', $postdelay_membership_level);
                $access_delay[$postdelay_membership_level[0]] = $postdelay_membership_level[1];
            }
        }
    }
    //check
    if (!empty($access_delay) && !empty($user)) {
        // get member
        $member = mgm_get_member($user->ID);
        //check
        $allowed = mgm_check_post_access_delay($member, $user, $access_delay);
        if (!$allowed) {
            return true;
        }
    }
    // return
    return false;
}