<?php
/*
Copyright 2012 Neil Harvey - wordpressLAB
*/

$wp_sa_setting = get_option( 'wp_sa_setting' );

define('RT_UPLOAD_URL',get_bloginfo('siteurl').'/'.str_replace(ABSPATH, '', $wp_sa_setting['wp_sa_upload_dir_path']));
define('RT_UPLOAD_DIR',$wp_sa_setting['wp_sa_upload_dir_path']);

// Buy Now Image and Text
$buyNowImage = "http://www.paypal.com/en_US/i/btn/btn_buynow_LG.gif";
$subscribeImage = "http://www.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif";

if(strlen($wp_sa_setting['wp_sa_payment_email']) > 0) {
    add_action('submitpost_box', 'rt_wpsa_meta_box');
    add_action('submitpage_box', 'rt_wpsa_meta_box');
    add_action('save_post', 'rt_wpsa_save_meta_box');

    add_filter('the_content', 'rt_wpsa_the_content');
    add_filter('login_redirect','rt_wpsa_login_redirect', 1, 3);
}
add_shortcode('subscription_form', 'rt_wpsa_subscription_form');


/********************************************************************
* Hide content if not allowed.
********************************************************************/

function rt_wpsa_the_content($content) {
    global $post, $user_ID, $current_user, $wpdb, $wp_sa_setting;
        
    $content_visibility = get_post_meta($post->ID, '_Content_Visibility');
    $content_visibility = $content_visibility[0];
        
    if ( is_user_logged_in() ) {
        get_currentuserinfo();
        $array_variable = ( $wp_sa_setting['closed_user_group']) ? $wp_sa_setting['closed_user_group'] : array();
        $capabilities = "{$wpdb->prefix}capabilities";
        
        foreach ( $array_variable as $k => $variable ) {
            if ( $current_user->{$capabilities}[$variable] ) {
                return $content;
            }
        }
    }

    if ( is_single() ) {
        if ( NULL == $content_visibility ) {
            $content_visibility = 'all';
        }
        if ( 'all' === $content_visibility ) {
                //do nothing
        }
        else if ( 'registered' === $content_visibility ) {
            if ( !is_user_logged_in() ) {
                $content = stripslashes( $wp_sa_setting['wp_sa_more_login'] );
                $content .= '<a href="'.wp_login_url( get_permalink() ).'" alt="Login" title="Login"> Click here</a> to login';
            }
        }
        else if ( !rt_wpsa_user_can_access_post(is_user_logged_in() ? $user_ID : 0, $post->ID ) ) {
            $content = stripslashes($wp_sa_setting['wp_sa_access_denied_msg']);
            $content .= ' Not a member? <a href="'.$wp_sa_setting['wp_sa_sub_payment_url'].'" alt="Click here to Signup!" title="Click here to Signup!">Click here</a> to Signup!';
        }

            return $content;
        }

        else {
            //Changed by Nemi
            if ( get_post($post->ID )->post_excerpt!='' )
                return the_excerpt();

            $postexcerpt = strip_tags($content);
            $postexcerpt = strip_shortcodes($content);
            $cont_array = explode(' ',$postexcerpt);
            if(count($cont_array) > 20)
                $postexcerpt = implode(' ',array_slice($cont_array, 0, 20)).'...';
            if(NULL == $content_visibility) {
                $content_visibility = 'all';
            }
            if('all' === $content_visibility) {
                return $content;
                //do nothing
            }else if('registered' === $content_visibility) {
                if(!is_user_logged_in()) {
                    return $postexcerpt;
                }
                else {
                    return $content;
                }
            }else if(!rt_wpsa_user_can_access_post(is_user_logged_in() ? $user_ID : 0, $post->ID)) {
                return $postexcerpt;
            }
            else {
                $output1 = get_post($post->ID );
                if (strlen($output1->post_excerpt)) {
                    return $output1->post_excerpt;
                }else {
                    return $postexcerpt;
                    //change ends here.
                }
            }
        }
   // }
}

function rt_wpsa_user_can_access_post($user_ID, $post_ID) {
    global $wpdb;
    $wp_sa_setting = get_option('wp_sa_setting');
//    print_r($wp_sa_setting['wp_sa_closed_user_group']);
    $userdata = get_userdata( $user_ID);
    
    if ( $wp_sa_setting['wp_sa_closed_user_group']['administrator'] == 'administrator' && $userdata->wp_capabilities['administrator']) return true;
    if ( $wp_sa_setting['wp_sa_closed_user_group']['editor'] == 'editor' && $userdata->wp_capabilities['editor']) return true;
    if ( $wp_sa_setting['wp_sa_closed_user_group']['author'] == 'author' && $userdata->wp_capabilities['author']) return true;
    if ( $wp_sa_setting['wp_sa_closed_user_group']['contributor'] == 'contributor' && $userdata->wp_capabilities['contributor']) return true;
    if ( $wp_sa_setting['wp_sa_closed_user_group']['subscriber'] == 'subscriber' && $userdata->wp_capabilities['subscriber']) return true;
    

    $subscription_log = $wpdb->prefix . "wpsa_subscription_transaction";

    if($user_ID == 0) {  //Probably because the user isn't logged in
        return FALSE;
    }
    $user_subscr_ids = get_usermeta($user_ID, 'subscription_id');
    $user_subscr_ids = explode(',', $user_subscr_ids);
    foreach ($user_subscr_ids as $user_subscr_id) {
        $sub_qry .= $user_subscr_id."','";
    }
    $sub_qry = substr($sub_qry,0,-3);
    $qry = "SELECT item_number FROM $subscription_log WHERE subscriber_id IN ('{$sub_qry}') AND user_ID = '$user_ID' AND subscr_status='active'";
    $user_subscr = $wpdb->get_col($qry);
    if($user_subscr) {
        $user_subscr = implode(',',$user_subscr);
        $subscription_table = $wpdb->prefix . "wpsa_subscriptions";
        $cat_query = "SELECT categories FROM {$subscription_table} WHERE id IN ({$user_subscr})";

        $cat_results = $wpdb->get_results($cat_query);
        foreach ($cat_results as $cat_result) {
            $categories = unserialize($cat_result->categories);
            $post_categories = wp_get_post_categories($post_ID);
            foreach ($post_categories as $post_category) {
                if (in_array($post_category, $categories)) {
                    return TRUE;
                }
            }
        }
        return FALSE;
    }
    else {
        return FALSE;
    }
}

/********************************************************************
 * When user click on subscribe button, a ajax call made to add paypal form
 ********************************************************************/
add_action('wp_ajax_subscription_form', 'rt_wpsa_subscription_form_ajax');
add_action('wp_ajax_nopriv_subscription_form', 'rt_wpsa_subscription_form_ajax');
function rt_wpsa_subscription_form_ajax() {
    die(rt_wpsa_paypal_form($rt_sa_item_number = $_POST['item_id']));
}

/********************************************************************
 * This function is used to display hidden from.
 * This function is called when a user selectes a subscription via radio option.
 * every field will be  hidden.
 ********************************************************************/
function rt_wpsa_paypal_form($rt_sa_item_number) {
    global $user_ID;
    global $wpdb;
    global $wp_sa_setting;
    
    $rt_sa_payment_email = $wp_sa_setting['wp_sa_payment_email'];
    $rt_sa_cancel_return_URL = $wp_sa_setting['wp_sa_sub_payment_url'];
    $rt_sa_return_URL = $wp_sa_setting['wp_sa_thank_you_page'];
    $rt_sa_currency_code = $wp_sa_setting['wp_sa_currency_code'];

    $plugin_url = get_option( 'siteurl' ) . '/wp-content/plugins/' . plugin_basename(dirname(__FILE__)) ;
    $rt_sa_item_name;
    $rt_sa_amount;
    $rt_sa_days_to_add;
    $rt_sa_subscr_interval;
    $rt_sa_user_msg;
    $rt_sa_trial;


    //    LIVE - PayPal Live URL
    $rt_sa_action = "https://www.paypal.com/cgi-bin/webscr";
    
    //    TESTING ONLY - PayPal Sandbox
    empty($rt_sa_test) ? $rt_sa_test = $wp_sa_setting['wp_sa_test']: '';
    if($rt_sa_test == "checked") {
        $rt_sa_action = "https://www.sandbox.paypal.com/cgi-bin/webscr";
    }
   
    //     get subscription info using $rt_sa_item_number   
    $table_name = $wpdb->prefix . "wpsa_subscriptions";    
    $qry = "SELECT * FROM {$table_name} WHERE id = '{$rt_sa_item_number}' LIMIT 1";

    $subscription_info = $wpdb->get_results($qry);
    $subscription_info = $subscription_info[0];

    $rt_sa_form = '<div>';
    $rt_sa_form .= '<form id="rt_sa_subsription_hidden_form" action="'.$rt_sa_action.'" method="post" target="_top" style="text-align:left">';

    //Subscription Code -- Not used due to IPN issues.
    $rt_sa_form .= '<input type="image" src="'.$subscribeImage.'" border="0" name="submit" alt="Make payments with PayPal - it\'s fast, free and secure!">';
    $rt_sa_form .= '<input type="hidden" name="cmd" value="_xclick-subscriptions">';

    if ($subscription_info->amount1 != 0 && $subscription_info->duration1 != 0) {
        $rt_sa_form .= '<input type="hidden" name="a1" value="'.$subscription_info->amount1.'">';

        /*Trial 1 billing cycle. This is the length of the billing cycle. The
            number is modified by the regular billing cycle units (t3, below)
            */
        $rt_sa_form .= '<input type="hidden" name="p1" value="'.$subscription_info->duration1.'">';

        /*[required] Trial 1 billing cycle units. This is the units of the
            regular billing cycle (p3, above) Acceptable values are: D (days),
            W (weeks), M (months), Y (years)
            */
        $rt_sa_form .= '<input type="hidden" name="t1" value="'.$subscription_info->duration_interval1.'">';
    }

    if ($subscription_info->amount1 != 0 && $subscription_info->duration2 != 0) {
        /*Trial 2 This is the price of the subscription        */
        $rt_sa_form .= '<input type="hidden" name="a2" value="'.$subscription_info->amount2.'">';

        /*Trial 2 billing cycle. This is the length of the billing cycle. The
            number is modified by the regular billing cycle units (t3, below) */
        $rt_sa_form .= '<input type="hidden" name="p2" value="'.$subscription_info->duration2.'">';

        /*[required] Trial 2 billing cycle units. This is the units of the regular
            billing cycle (p3, above) Acceptable values are: D (days),W (weeks), M (months), Y (years)*/
        $rt_sa_form .= '<input type="hidden" name="t2" value="'.$subscription_info->duration_interval2.'">';
    }

    /*Regular rate. This is the price of the subscription    */
    $rt_sa_form .= '<input type="hidden" name="a3" value="'.$subscription_info->amount3.'">';

    /*Regular billing cycle. This is the length of the billing cycle. The
     number is modified by the regular billing cycle units (t3, below)    */
    $rt_sa_form .= '<input type="hidden" name="p3" value="'.$subscription_info->duration3.'">';

    /*[required] Regular billing cycle units. This is the units of the
        regular billing cycle (p3, above) Acceptable values are: D (days),W (weeks), M (months), Y (years)    */
    $rt_sa_form .= '<input type="hidden" name="t3" value="'.$subscription_info->duration_interval3.'">';

    /*Recurring payments. If set to ‚Äú1,‚Äù the payment will recur unless your customer cancels the subscription before the end of the
        billing cycle. If omitted, the subscription payment will not recur at the end of the billing cycle    */
    /* 'yes' represents radio's value    */
    if ($_POST['rt_sa_recurring'] == 'yes') { $rt_sa_recurring = 1; }
    else { $rt_sa_recurring = 0; }

    $rt_sa_form .= '<input type="hidden" name="src" value="'.$rt_sa_recurring.'">';

    /*Reattempt on failure. If set to ‚Äú1,‚Äù and the payment fails, the
        payment will be reattempted two more times. After the third
        failure, the subscription will be cancelled. If omitted and the
        payment fails, payment will not be reattempted and the
        subscription will be immediately cancelled
    */
    $rt_sa_form .= '<input type="hidden" name="sra" value="1">';
    //$rt_sa_days_to_add = 9999;
    $rt_sa_form .= '<input type="hidden" name="business" value="'.$rt_sa_payment_email.'">';
    $rt_sa_form .= '<input type="hidden" name="item_name" value="'.$subscription_info->name.'">';
    $rt_sa_form .= '<input type="hidden" name="item_number" value="'.$subscription_info->id.'">';
    $rt_sa_form .= '<input type="hidden" name="currency_code" value="'.$rt_sa_currency_code.'">';

    //check what to do? ipn? refer subscription manual
    $rt_sa_form .= '<input type="hidden" name="return" value="'.$rt_sa_return_URL.'">';
    $rt_sa_form .= '<input type="hidden" name="rm" value="2">';

    $custom_code = microtime(TRUE);
    setcookie('check_time_wpsa', $custom_code, time()+3600, COOKIEPATH, COOKIE_DOMAIN, false, true);
    setcookie('check_type_wpsa', 'sub', time()+3600, COOKIEPATH, COOKIE_DOMAIN, false, true);
    //setcookie('check_type_wpsa', 'sub', time()+3600, COOKIEPATH, COOKIE_DOMAIN, false, true);
//    $_COOKIE['check_time_wpsa'] = $custom_code;
//    $_COOKIE['check_type_wpsa'] = 'sub';
    if(is_user_logged_in())
        $custom_code .= '|'.$user_ID;
    $rt_sa_form .= '<input type="hidden" name="custom" value="'.$custom_code.'">';

    //check this if block SET return url and notify url
    $rt_sa_form .= '<input type="hidden" name="notify_url" value="'.$plugin_url.'/wp-sa-paypal-ipn-handler.php">';
    $rt_sa_form .= '<input type="hidden" name="cancel_return" value="'.$rt_sa_cancel_return_URL.'">';
    $rt_sa_form .= '<input type="hidden" name="no_shipping" value="1">';

    /*
   * This field makes sure your subscriber is not prompted to include a
note with the subscription, a function which PayPal Subscriptions
does not support. This field must be included, and the value must
be set to 1
    */
    $rt_sa_form .= '<input type="hidden" name="no_note" value="1">';

    /*
     * Add additional hidden field if affiliate addon exist.
     * By: Santosh
     * Date: 10-08-10
     */
    if (function_exists( 'wpsa_affiliate_activate' ) ) {
        $rt_sa_form .= '<input type="hidden" name="on0" value="affiliate_ref"/><input type="hidden" name="os0" value="'.$_COOKIE['wpsa-ref'].'">';
    }
    $rt_sa_auth_code= $wp_sa_setting['wp_sa_auth_code'];
    /* MD5 encryption of auth code and date.*/
    $rt_sa_auth_code .= date("Y-m-d", current_time('timestamp', 0));
    $rt_sa_auth_code = md5($rt_sa_auth_code);

    $rt_sa_form .= '</form></div>';

//    die($rt_sa_form);
    return $rt_sa_form;

}

/********************************************************************
 * Short code to add subscription form
 ********************************************************************/
function rt_wpsa_subscription_form() {
    global $wpdb, $subscribeImage, $wp_sa_setting;

    if($wp_sa_setting['wp_sa_subscription_button_image']!='')
        $subscribe_image = $wp_sa_setting['wp_sa_subscription_button_image'];
    else
        $subscribe_image = $subscribeImage;

    $qry = "SELECT * FROM " .$wpdb->prefix. "wpsa_subscriptions WHERE 1";
    $subscriptions_list = $wpdb->get_results($qry);
    
    $subs_option = '<table class="widefat post fixed" id="subscription_form_list" width="100%">
    <thead>
        <tr class="tablemenu">
            <td align="center" width="29px"><img title="Select Option" alt="Select Option" src="' .get_settings('siteurl'). '/wp-content/plugins/' .dirname(dirname(plugin_basename(__FILE__))). '/img/select.gif"/></td>
            <td align="left"><strong>Name</strong></td>
            <td align="left"><strong>Description</strong></td>
            <td align="center"><strong>Price</strong></td>
        </tr>
    </thead>
    <tbody>';
    
        if($subscriptions_list) {
            foreach ($subscriptions_list as $subscription) {
                //Edited to display Day(s), Week(s), ... instead of D, W, M, Y on Subscription Form (for Users) : Nemi
                $durationinterval = $subscription->duration_interval3;
                switch($durationinterval) {
                    case 'D':
                        $durationinterval .= "ay(s)";
                        break;

                    case 'W':
                        $durationinterval .= "eek(s)";
                        break;

                    case 'M':
                        $durationinterval .= "onth(s)";
                        break;

                    case 'Y':
                        $durationinterval .= "ear(s)";
                        break;
                    default:
                        break;
                }
            $subs_option .= '<tr class="read">
                    <td align="center"><input type="radio" name="subscription_radio" value="'. $subscription->id. '" /></td>
                    <td align="left">' .$subscription->name. '</td>
                    <td align="left">' .$subscription->description. '</td>
                    <td align="center">' .$subscription->amount3. '</td>
                </tr>';
        }
    }
    else {
        $subs_option .= '<tr><td colspan=\"4\">No Subscription details added yet.</td></tr>';
    }

    $subs_option .= '</tbody></table>';
    
    if ($wp_sa_setting['wp_sa_display_recurring'] === 'checked') {
        
        $subs_option .= '<b>Recurring Payments</b>
        <input type="radio" class="recurring_select" name="recurring_select" value="yes" checked="checked">Yes
        <input type="radio" class="recurring_select" name="recurring_select" value="no">No<br /><br />';
    }
    else {
        $subs_option .= '<input type="hidden" class="recurring_select" name="recurring_select" value="yes"/>';
    }
    
    $subs_option .= '<div align="center"><input type="image" src="' .$subscribe_image. '" name="submit" alt="Make payments with PayPal - it\'s fast, free and secure!" id="rt_sa_subscription_button"></div>';
    
//    $subs_option =<<<HTML
//
//            $ratio_str
//HTML;

    return $subs_option;
}


/********************************************************************
 * Add "Subscription ID" field to Registration form
 ********************************************************************/
add_action( 'register_form', 'rt_wpsa_add_subsid_to_reg_form');
function rt_wpsa_add_subsid_to_reg_form() {
   // if(isset ($_GET['subscr_id']) && isset ($_GET['txn_id']) && !empty ($_GET['subscr_id']) && !empty ($_GET['txn_id'])) {
    $email_id = urldecode($_GET['email_id']);
     if(isset ($_GET['subscr_id']) && !empty ($_GET['subscr_id']) ){
        ?>
        <p>
            <label>Subscription ID<br />
            <input name="subscr_id" id="subscr_id" size="25" value="<?php echo $_GET['subscr_id']; ?>" type="text" tabindex="20" class="input my_custom_fields" readonly="readonly" /></label>
        </p>
            <?php
    }
    ?>
    <p>
        <label>Transaction ID<br />
        <input name="txn_id" id="txn_id" size="25" value="<?php echo $_GET['txn_id']; ?>" type="text" tabindex="20" class="input my_custom_fields" readonly="readonly" /></label>
    </p>
<style type="text/css">
    .my_custom_fields {
        border:none;
        background:#FBFBFB none repeat scroll 0 0;
        border:1px solid #E5E5E5;
        font-size:24px;
        margin-bottom:16px;
        margin-right:6px;
        margin-top:2px;
        padding:3px;
        width:97%;
    }
</style>
<script type="">
    var email_field = document.getElementById('user_email');
    email_field.value = '<?php echo urldecode($_GET['email_id']); ?>';
</script>
        <?php
   // }
}

/********************************************************************
 * pluggable function override
********************************************************************/
if ( !function_exists('wp_new_user_notification') ) :
    /**
     * Notify the blog admin of a new user, normally via email.
     *
     * @since 2.0
     *
     * @param int $user_id User ID
     * @param string $plaintext_pass Optional. The user's plaintext password
     */    
    function wp_new_user_notification($user_id, $plaintext_pass = '') {
        global $wpdb;
        $table_name = $wpdb->prefix . "wpsa_subscription_transaction";
        if(isset ($_POST['subscr_id']) && !empty ($_POST['subscr_id'])) {
            update_usermeta( $user_id, 'subscription_id', $wpdb->prepare($_POST['subscr_id']));
            $qry = "UPDATE {$table_name} SET `user_ID`='{$user_id}' WHERE `subscriber_id`='{$_POST['subscr_id']}'";
            $wpdb->query($qry);            

            do_action('wpsa_add_suscr_log', $user_id, $_POST['subscr_id']);
        }

        if(isset ($_POST['txn_id']) && !empty ($_POST['txn_id'])) {
            update_usermeta( $user_id, 'transaction_id', $wpdb->prepare($_POST['txn_id']));
        }

        $user = new WP_User($user_id);
        $user_login = stripslashes($user->user_login);
        $user_email = stripslashes($user->user_email);

        $message  = sprintf(__('New user registration on your blog %s:'), get_option('blogname')) . "\r\n\r\n";
        $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
        $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";

        wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname')), $message);

        if ( empty($plaintext_pass) )
            return;

        $message  = sprintf(__('Username: %s'), $user_login) . "\r\n";
        $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
        $message .= wp_login_url() . "\r\n";

        wp_mail($user_email, sprintf(__('[%s] Your username and password'), get_option('blogname')), $message);

}
endif;

/********************************************************************
 * Add Meta box on post add/edit page (Admin side)
 ********************************************************************/
function rt_wpsa_meta_box() {
    add_meta_box('salesautomator-meta-box', 'Content Visibility', 'content_visibility_meta_box', 'post', 'side', 'high');
    //add_meta_box('salesautomator-meta-box', 'Content Visibility', 'content_visibility_meta_box', 'page', 'side', 'high');
}

/********************************************************************
 * Add Meta box on post add/edit page (Admin side)
 ********************************************************************/
function content_visibility_meta_box() {
    $post_id = $_GET['post'];
    $content_visibility = get_post_meta($post_id, '_Content_Visibility');
    if(NULL == $content_visibility[0]) {
        $content_visibility[0] = 'all';
    }
    ?>
<label for="visibility_type"><b>Select visibility for this post</b></label><br /><br />
<input type="radio" name="visibility_type" value="all" <?php echo (($content_visibility[0] == 'all') ? 'checked' : '' ); ?>/> All Users<br />
<input type="radio" name="visibility_type" value="registered" <?php echo (($content_visibility[0] == 'registered') ? 'checked' : '' ); ?>/> Registered Users<br />
<input type="radio" name="visibility_type" value="subscriber" <?php echo (($content_visibility[0] == 'subscriber') ? 'checked' : '' ); ?>/> Subscribers<br />

    <?php
}

/********************************************************************
 * Save Meta box values
 ********************************************************************/
function rt_wpsa_save_meta_box($post_id) {
// verify if this is an auto save routine.

    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
        return $post_id;


    // Check permissions
    if ( 'page' == $_POST['post_type'] ) {
        if ( !current_user_can( 'edit_page', $post_id ) )
            return $post_id;
    }else {
        if ( !current_user_can( 'edit_post', $post_id ) )
            return $post_id;
    }
    if(NULL == $_POST['visibility_type']) {
        //do nothing
    }else {
        $content_visibility = $_POST['visibility_type'];
        update_post_meta($post_id, '_Content_Visibility', $content_visibility);
    }


}

//$redirect_to = apply_filters('login_redirect', $redirect_to, isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '', $user);

/********************************************************************
 * After login user redirected to link specified in wpsa-setting page (Admin side)
 ********************************************************************/
function rt_wpsa_login_redirect($redirect_to, $request_redirect_to, $user) {
    global $wp_sa_setting;

    if($user->caps['administrator'] || is_array($user->error_data)) {
        return $redirect_to;
    }
    if (strlen($wp_sa_setting['wp_sa_login_redirection_url'])) {
        $redirect_to = $wp_sa_setting['wp_sa_login_redirection_url'];
    }else {
        $redirect_to = empty ($redirect_to) ? 'index.php' : $redirect_to;
    }
    return $redirect_to;
}

/********************************************************************
 * Check the HTTP referer and set cookies accordingly
 ********************************************************************/
add_action('init', 'rt_wpsa_get_referer','1');
function rt_wpsa_get_referer() {
    if(!isset ($_COOKIE['referal_url'])) {
        setcookie('referal_url', 'no referer' );
    }
//    $ref_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
    if (isset ($_SERVER['HTTP_REFERER'])) {
        $ref_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
        if($_SERVER['HTTP_HOST'] != $ref_host) {
            $_COOKIE['referal_url'] = $_SERVER['HTTP_REFERER'];
        }
    }
}

/********************************************************************
 * Commented because,
 * right now it doesnt make any sense.
 
add_action( 'thankyou_page', 'rt_wpsa_thank_you_page');
function rt_wpsa_thank_you_page() {
    echo 'Thank you.';
}
 ********************************************************************/

/*------------------------------------------------------------
    ADD USER TO SUBSCRIPTION SALES WHENEVER
 * USER ADDED BY ADMIN OR BY REGISTRATION PROCESS
------------------------------------------------------------*/
add_action('user_register', 'sa_rt_add_user_to_subsc', 10, 1);

function sa_rt_add_user_to_subsc($user_id) {
    global $wpdb;

    if ($_POST['role'] == 'subscriber') {
        $sql = "INSERT INTO {$wpdb->prefix}wpsa_subscription_transaction ( user_ID, subscriber_id,  payer_email, reciever_email, first_name, last_name, subscr_status, subscr_date ) VALUES
                        ( ". $user_id. ", '".$user_id."', '". $_POST['email']. "', '". $_POST['email']. "', '" .$_POST['first_name']. "', '" .$_POST['last_name']. "', 'active', now());";
        $wpdb->query($sql);
    }
}

/**
 * @author Santosh
 * @since   17-03-11
 */
add_action('wp_ajax_nopriv_wpsa_product_reset', 'wpsa_product_reset');
add_action('wp_ajax_wpsa_product_reset', 'wpsa_product_reset');

function wpsa_product_reset() {
    echo '
            <tr style="font-family:Arial; font-size: 14px">
                <td width="30%" align="left"><label id="lemail" for="email">Paypal Email:</label></td>
               <td class="field" width="30%"><input id="email" name="email" type="text" value=""  /></td>
                <td class="status" width="30%"></td>
            </tr>
            <tr>
                <td colspan="3"><br><input type="submit" value=" Reset Download " name="retrive-button"></td>
            </tr>
         ';
    die();
}

/**
 * @author Santosh
 * @since   17-03-11
 */
add_action('init', 'wpsa_download_product');

function wpsa_download_product() {
    if ( !isset ($_GET['wpsa_download'])) {
//    if(is_admin ()) {
       return;
    }
    
    global $wpdb;
    $wud = wp_upload_dir();
    $wp_sa_setting = get_option('wp_sa_setting');

    define('RT_UPLOAD_DIR',$wp_sa_setting['wp_sa_upload_dir_path']);

    $rt_option = get_option('rt_option_products');
    $flag = false;

    if (!isset($_GET['wpsa_key'])) {
            echo  '<br />Ivalid key<br />';
            exit;
    }

    $sql = "SELECT id, `key`, name, count, expire, ip_addr FROM ".$wpdb->prefix."wpsa_download_link WHERE `key` = '{$_GET['wpsa_key']}' LIMIT 1";
    $row = $wpdb->get_row($sql);

    if ( !isset( $row ) ) {
            echo '<p><b>Error:</b> Invalid or expired download link.</p>';
            echo '<p>Go back to <a href="'. get_bloginfo('home') .'">Home</a> or please <a href="'.$wp_sa_setting['wp_sa_reset_dnld_url'].'">reset</a> your product download link.</p>';
            exit;
    }

    $newfile_path = RT_UPLOAD_DIR.$row->name;
    $hours = $wp_sa_setting['rt_mail_option_hours'];

    $t = time();
    $h = $hours * 60 * 60 ;

    $validity_limit = $t + $h;
    $timestamp = strtotime($row->expire);

    if ($timestamp > $validity_limit) {
        echo '<br />Link Expired. Please <a href="'.$wp_sa_setting['wp_sa_reset_dnld_url'].'">reset</a> your product download link. <br />';
        exit;
    }

    if ($row->ip_addr == '') {
        $row->ip_addr = $_SERVER['REMOTE_ADDR'];

        $sql = "UPDATE `{$wpdb->prefix}wpsa_download_link` SET ip_addr = '{$_SERVER['REMOTE_ADDR']}' WHERE `id` = {$row->id} LIMIT 1";
        $row2 = $wpdb->get_row($sql);
    }

    elseif ($row->ip_addr != $_SERVER['REMOTE_ADDR']) {
        echo '<p><b>Error:</b> You are not authorised to access this link<p>';
        echo '<p>Go back to <a href="'. get_bloginfo('home') .'">Home</a>.</p>';
        exit;
    }

    if (!file_exists($newfile_path)) {
        echo '<br />Ivalid link or outdated link<br />';
        exit;
    }

    if ( $row->count < $wp_sa_setting['wp_sa_max_count_limit'] ) {
            $sql = "UPDATE `{$wpdb->prefix}wpsa_download_link` SET `count` = `count` + 1 WHERE `id` = {$row->id} LIMIT 1";
            $row2 = $wpdb->get_row($sql);
            $flag = true;
    }
    elseif ( $row->count >= $wp_sa_setting['wp_sa_max_count_limit'] ) {
            //$sql = "DELETE FROM `{$wpdb->prefix}wpsa_download_link` WHERE `id` = {$row->id} ";
            //$wpdb->query($sql);
            echo '<br />Max download limit has been reached. Please <a href="'.$wp_sa_setting['wp_sa_reset_dnld_url'].'">reset</a> your product download link.<br /> ';
            exit;
    }

    if ($flag) {
            header("Content-type: application/force-download");
            header('Content-Disposition: inline; filename="' . $newfile_path . '"');
            header("Content-Transfer-Encoding: Binary");
            header("Content-length: ".filesize($newfile_path));
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $row->name . '"');

            flush(); // this doesn't really matter.

            $fp = fopen($newfile_path, "r");
            while (!feof($fp)) {
                fread($fp, 65536);
                flush(); // this is essential for large downloads
            }
            fclose($fp);

        readfile("$newfile_path");
    }
    exit;
}
?>