/**
 * check protection
 *
 * @param string $content
 * @param string $type
 * @return string $content
 */
function mgm_content_protection_check($content, $type = 'excerpt')
{
    global $wpdb, $post;
    // system
    $system_obj = mgm_get_class('system');
    // by pass content protection for excerpt if setting is off
    // get user
    $user = wp_get_current_user();
    // to disable showing multiple private messages on home page listing(issue#: 384), disabled due to #429
    // $show_message = true; // (is_home() && $type == 'content')  ? false : true;
    // filter first
    $content = mgm_replace_message_tags($content);
    // filter payment messages
    $content = mgm_replace_payment_message_tags($content);
    // no check for admin or if user has access or user logged in
    if (is_super_admin() || mgm_user_has_access()) {
        return $content;
    }
    //comments protection check
    if ($system_obj->setting['enable_comments_protection'] == 'Y') {
        //hook
        add_filter('comments_template', 'mgm_hide_comments');
    }
    //to honour MORE(<!--more-tag-->) tag: issue#: 671
    //case: home page listing,category listing,archives
    if ($type == 'excerpt' || !is_single() && $type == 'content' && (is_archive() || is_home() || is_search())) {
        //check the content has more tag: eg: The link: http://magicmediagroup.com/ppp/#more-540
        if (preg_match("/\\/#more-" . $post->ID . "/", $content) || preg_match("/<!--more-->/", $content)) {
            return $content;
        }
        // if excerpt display and enable_excerpt_protection is disbled , bypass protection:issue#: 887
        if (!bool_from_yn($system_obj->get_setting('enable_excerpt_protection'))) {
            return $content;
        }
    }
    // for full / or part protection, honor manual private tag setting via post interface or , mgm settings
    // protection level
    $protection_level = $system_obj->setting['content_protection'];
    // no check for post/page set as no access redirect, custom register/login urls
    if ($post->ID) {
        // get permalink
        $permalink = get_permalink($post->ID);
        // no_access_urls
        $no_access_urls = array('no_access_redirect_loggedin_users', 'no_access_redirect_loggedout_users');
        // init
        $return = false;
        // loop
        foreach ($no_access_urls as $no_access_url) {
            // get setting
            $no_access_url_is = $system_obj->setting[$no_access_url];
            // match
            if (!empty($no_access_url_is) && $permalink == trailingslashit($no_access_url_is)) {
                // set flag
                $return = true;
                break;
            }
        }
        // return
        if ($return) {
            return $content;
        }
        // check urls
        $custom_pages_url = $system_obj->get_custom_pages_url();
        // check
        foreach ($custom_pages_url as $key => $page_url) {
            // match
            if (!empty($page_url) && $permalink == trailingslashit($page_url)) {
                // set flag
                $return = true;
                break;
            }
        }
        // return
        if ($return) {
            return $content;
        }
        // get post object
        $post_obj = mgm_get_post($post->ID);
    }
    // post_is_purchasable
    $post_is_purchasable = mgm_post_is_purchasable();
    // is post_is_purchasable and expired
    if ($post_is_purchasable && $user->ID && mgm_is_user_purchased_post_expired($post->ID, $user->ID)) {
        $protected_message = __('Purchased Post expired, Please re-purchase to access the post', 'mgm');
    } else {
        // message code
        if ($user->ID) {
            // logged in user
            $message_code = $post_is_purchasable ? 'private_text_purchasable' : 'private_text_no_access';
        } else {
            // logged out/guest user
            $message_code = $post_is_purchasable ? 'private_text_purchasable_login' : 'private_text';
        }
        // protected_message
        $protected_message = sprintf('<div class="mgm_private_no_access">%s</div>', mgm_private_text_tags(mgm_stripslashes_deep($system_obj->get_template($message_code, array(), true))));
        // filter message
        $protected_message = mgm_replace_message_tags($protected_message);
    }
    // return $content;
    // check
    switch ($protection_level) {
        case 'full':
            // full protection
            // check redirect condition
            // Skip content protection if manually protected:(To honour private tags)
            // Double check as the next line was removed before
            if (!mgm_is_manually_protected($content)) {
                // had redirect
                if (!mgm_check_redirect_condition($system_obj)) {
                    $content = $protected_message;
                } else {
                    // default
                    $content = mgm_no_access_redirect($system_obj);
                }
            }
            break;
        case 'partly':
            // partly protection
            // Skip content protection if manually protected:(To honour private tags)
            // Double check as the next line was removed before
            if (!mgm_is_manually_protected($content)) {
                // check if custom page is loaded
                $custompage_loaded = mgm_is_custompage_loaded();
                // how many words to allow
                $allowed_word_limit = (int) $system_obj->get_setting('public_content_words');
                $allow_html = bool_from_yn($system_obj->get_setting('content_protection_allow_html'));
                // apply if only more than 0
                if (!$custompage_loaded && $allowed_word_limit > 0) {
                    // #125 iss / issue#: 510
                    // check redirect condition
                    if (!mgm_check_redirect_condition($system_obj)) {
                        // redirect if set
                        // on type
                        switch ($type) {
                            case 'excerpt':
                                //issue #1059
                                $content_post = get_post($post->ID);
                                $my_content = $content_post->post_content;
                                if (preg_match("/<!--nextpage-->/", $my_content)) {
                                    $content = str_replace('<!--nextpage-->', '', $my_content);
                                }
                                // already parsed by shortcode
                                if (preg_match('#<div class="mgm_private_no_access">(.*?)<\\/div\\>#s', $content, $match)) {
                                    // get message only
                                    $prev_message = $match[0];
                                    // remove message
                                    $content = preg_replace('#<div class="mgm_private_no_access">(.*?)<\\/div\\>#s', '', $content);
                                    // get words
                                    $content = mgm_words_from_content($content, $allowed_word_limit, $allow_html);
                                    // append
                                    if ($allowed_word_limit < 50) {
                                        $content .= $prev_message;
                                    }
                                } else {
                                    // not processed
                                    // get words
                                    $content = mgm_words_from_content($content, $allowed_word_limit, $allow_html);
                                    // append
                                    if ($allowed_word_limit < 50) {
                                        $content .= $protected_message;
                                    }
                                }
                                break;
                            case 'content':
                                //issue #1059
                                $content_post = get_post($post->ID);
                                $my_content = $content_post->post_content;
                                if (preg_match("/<!--nextpage-->/", $my_content)) {
                                    $content = str_replace('<!--nextpage-->', '', $my_content);
                                }
                                // already parsed by shortcode
                                // issue #: 450
                                if (preg_match('#<div class="mgm_private_no_access">(.*?)<\\/div\\>#s', $content, $match)) {
                                    // get message only
                                    $prev_message = $match[0];
                                    // remove message
                                    $content = preg_replace('#<div class="mgm_private_no_access">(.*?)<\\/div\\>#s', '', $content);
                                    // get words
                                    $content = mgm_words_from_content($content, $allowed_word_limit, $allow_html);
                                    // add message
                                    $content .= $prev_message;
                                } else {
                                    // get words
                                    $content = mgm_words_from_content($content, $allowed_word_limit, $allow_html) . $protected_message;
                                }
                                break;
                        }
                    } else {
                        // default
                        $content = mgm_no_access_redirect($system_obj);
                    }
                }
            }
            break;
        case 'none':
            // no protection, trim all private tags, honor [private] tags
            // just check purchasable, other wise trim
            if (!$post_is_purchasable) {
                // remove tags
                $content = str_replace(array('[private]', '[/private]', '[private_or]', '[/private_or]', '[private_and]', '[/private_and]'), '', $content);
            }
            break;
        default:
            // disable protection
            $content = str_replace(array('[private]', '[/private]', '[private_or]', '[/private_or]', '[private_and]', '[/private_and]'), '', $content);
            break;
    }
    // issue#: 450
    if ($post_is_purchasable && !mgm_is_buynow_form_included($content)) {
        //issue #1397
        if (mgm_is_manually_protected($content) ? false : true) {
            $return = mgm_parse_post_template($post->ID);
        } else {
            //issue #1537
            if (is_super_admin() || $user->ID) {
                $return = mgm_get_post_purchase_button($post->ID, mgm_is_manually_protected($content) ? false : true);
            }
        }
        // get button
        // replace message tags if any
        $return = mgm_replace_message_tags($return);
        // wrap with css class
        $content .= sprintf('<div class="mgm_private_no_access">%s</div>', $return);
    }
    // return
    return $content;
}
/**
 * Magic Members verify file download
 *
 * @package MagicMembers
 * @since 2.5
 * @desc verify file download
 * @param string download code
 * @return none
 */
function mgm_download_file($code)
{
    global $wpdb;
    // current_user
    $current_user = wp_get_current_user();
    // system
    $system_obj = mgm_get_class('system');
    // url
    $no_access_redirect_download = $system_obj->get_setting('no_access_redirect_download');
    // redirect
    $do_redirect = empty($no_access_redirect_download) ? false : true;
    // allow default
    $allow_download = true;
    // data fetch
    if ($download = mgm_get_download_data($code)) {
        // for members
        if (bool_from_yn($download->members_only)) {
            // reset as restricted
            $allow_download = false;
            // user check
            if ($current_user->ID) {
                // allow admin
                if (is_super_admin()) {
                    // is_super_admin
                    $allow_download = true;
                } else {
                    // get post mapped
                    $posts = mgm_get_download_post_ids($download->id);
                    // loop
                    foreach ($posts as $post_id) {
                        // only  when user has access to mapped post
                        if (mgm_user_has_access($post_id)) {
                            // set access
                            $allow_download = true;
                            // skip
                            break;
                        }
                    }
                    //check download included in guest restrict via post/page access issue #1609
                    if (!$allow_download && isset($_REQUEST['guest_token']) && isset($_REQUEST['post_id'])) {
                        // only  when user has access to mapped post
                        if (mgm_user_has_access($_REQUEST['post_id'])) {
                            // set access
                            $allow_download = true;
                        }
                    }
                    // download limit user member access issue #902
                    if (!empty($download->download_limit) && (int) $download->download_limit > 0 && $allow_download) {
                        $download_limit = mgm_download_user_limit_check($download->id);
                        if (empty($download_limit)) {
                            mgm_download_user_limit_insert($download->id);
                        } else {
                            if ($download_limit->count < $download->download_limit) {
                                // count
                                $count = $download_limit->count + 1;
                                // update
                                mgm_download_user_limit_update($download->id, $count);
                            } else {
                                $allow_download = false;
                                // redirect
                                if ($do_redirect) {
                                    mgm_redirect(add_query_arg(array('error_code' => 1), $no_access_redirect_download));
                                }
                                // show mesage if redirect does not set
                                mgm_download_error(1);
                                exit;
                            }
                        }
                    }
                }
            } else {
                //check download included in guest restrict via post/page access issue #1609
                if (!$allow_download && isset($_REQUEST['guest_token']) && isset($_REQUEST['post_id'])) {
                    // only  when user has access to mapped post
                    if (mgm_user_has_access($_REQUEST['post_id'])) {
                        // set access
                        $allow_download = true;
                    }
                }
            }
            // end member restriction check
        } else {
            // download limit user member access issue #902
            if ($current_user->ID) {
                // download limit user member access issue #902
                if (!empty($download->download_limit) && (int) $download->download_limit > 0) {
                    $download_limit = mgm_download_user_limit_check($download->id);
                    if (empty($download_limit)) {
                        mgm_download_user_limit_insert($download->id);
                    } else {
                        if ($download_limit->count < $download->download_limit) {
                            $count = $download_limit->count + 1;
                            mgm_download_user_limit_update($download->id, $count);
                        } else {
                            $allow_download = false;
                            // redirect
                            if ($do_redirect) {
                                mgm_redirect(add_query_arg(array('error_code' => 1), $no_access_redirect_download));
                            }
                            // show mesage if redirect does not set
                            mgm_download_error(1);
                            exit;
                        }
                    }
                }
            } else {
                if (bool_from_yn($download->restrict_acces_ip)) {
                    // download limit ip member access issue #902
                    if (!empty($download->download_limit) && (int) $download->download_limit > 0) {
                        $download_limit = mgm_download_ip_limit_check($download->id);
                        if (empty($download_limit)) {
                            mgm_download_ip_limit_insert($download->id);
                        } else {
                            if ($download_limit->count < $download->download_limit) {
                                $count = $download_limit->count + 1;
                                mgm_download_ip_limit_update($download->id, $count);
                            } else {
                                $allow_download = false;
                                // redirect
                                if ($do_redirect) {
                                    mgm_redirect(add_query_arg(array('error_code' => 1), $no_access_redirect_download));
                                }
                                // show mesage if redirect does not set
                                mgm_download_error(1);
                                exit;
                            }
                        }
                    }
                }
            }
        }
        // check expire
        $download_expired = false;
        // allowed alreay
        if ($allow_download) {
            // expire date
            if (!is_null($download->expire_dt)) {
                // expired
                if (intval($download->expire_dt) && time() > strtotime($download->expire_dt)) {
                    $download_expired = true;
                }
            }
        }
        // allowed
        if ($allow_download && !$download_expired) {
            // check if s3 resource
            if (mgm_is_s3_file($download->filename)) {
                //decode - issue #1727
                $download->filename = urldecode($download->filename);
                // expired
                $aws_qsa_expires = $system_obj->get_setting('aws_qsa_expires', '1 HOUR');
                // check if torrent
                if (bool_from_yn($download->is_s3_torrent)) {
                    // redirect to amazon secure url
                    if ($torent_url = mgm_get_s3torent_url($download->filename, $aws_qsa_expires)) {
                        wp_redirect($torent_url);
                        exit;
                    }
                } else {
                    // check
                    if (bool_from_yn($system_obj->get_setting('aws_enable_qsa', 'N'))) {
                        // redirect to amazon secure url
                        if ($token_url = mgm_get_s3token_url($download->filename, $aws_qsa_expires)) {
                            wp_redirect($token_url);
                            exit;
                        }
                    }
                }
                // download as usual
                mgm_stream_download_s3($download->filename);
                exit;
            } else {
                // filepath
                $filepath = mgm_get_abs_file($download->filename);
                // check
                if (file_exists($filepath)) {
                    // do the  download
                    mgm_stream_download($filepath);
                    // delete if s3 file
                    if (mgm_is_s3_file($filepath)) {
                        // old code kept
                        // delete
                        mgm_delete_file($filepath);
                    }
                    // exit
                    exit;
                } else {
                    // redirect
                    if ($do_redirect) {
                        mgm_redirect(add_query_arg(array('error_code' => 2), $no_access_redirect_download));
                    }
                    // show mesage if redirect does not set
                    mgm_download_error(2);
                    exit;
                }
            }
        } else {
            // redirect
            $code = $download_expired ? '3' : '4';
            // redirect
            if ($do_redirect) {
                mgm_redirect(add_query_arg(array('error_code' => $code), $no_access_redirect_download));
            }
            // show mesage if redirect does not set
            mgm_download_error($code);
            exit;
        }
    } else {
        // redirect
        if ($do_redirect) {
            mgm_redirect(add_query_arg(array('error_code' => 4), $no_access_redirect_download));
        }
        // show mesage if redirect does not set
        mgm_download_error(4);
        exit;
    }
}