function membership_contents()
 {
     // data
     $data = array();
     // membership level
     $data['membership_level'] = mgm_get_user_membership_type();
     // load template view
     $this->load->template('admin/membership_contents', array('data' => $data));
 }
 function _buy_membership()
 {
     // system
     $system_obj = mgm_get_class('system');
     $s_packs = mgm_get_class('subscription_packs');
     $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
     $dpne = bool_from_yn($system_obj->get_setting('disable_payment_notify_emails'));
     // get passthrough, stop further process if fails to parse
     $custom = $this->_get_transaction_passthrough($_POST['M_custom']);
     // local var
     extract($custom);
     // currency
     if (!$currency) {
         $currency = $this->setting['currency'];
     }
     // find user
     $user = get_userdata($user_id);
     //another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // Get the current AC join date
     if (!($join_date = $member->join_date)) {
         $member->join_date = time();
     }
     // Set current AC join date
     //if there is no duration set in the user object then run the following code
     if (empty($duration_type)) {
         //if there is no duration type then use Months
         $duration_type = 'm';
     }
     // membership type default
     if (empty($membership_type)) {
         //if there is no account type in the custom string then use the existing type
         $membership_type = md5($member->membership_type);
     }
     // validate parent method
     $membership_type_verified = $this->_validate_membership_type($membership_type, 'md5|plain');
     // verified
     if (!$membership_type_verified) {
         if (strtolower($member->membership_type) != 'free') {
             // notify admin, only if gateway emails on
             if (!$dge) {
                 $message = 'Could not read membership type in the following POST data. Please debug or contact magic members to fix the problem making sure to pass on the following data. <br /><br /><pre>' . "\n\n" . print_r($_POST, true) . '</pre>';
                 mgm_mail($system_obj->setting['admin_email'], 'Error in WorldPay membership verification', $message);
             }
             // abort
             return;
         } else {
             $membership_type_verified = $member->membership_type;
         }
     }
     // set
     $membership_type = $membership_type_verified;
     // sub pack
     $subs_pack = $s_packs->get_pack($pack_id);
     // if trial on
     if ($subs_pack['trial_on']) {
         $member->trial_on = $subs_pack['trial_on'];
         $member->trial_cost = $subs_pack['trial_cost'];
         $member->trial_duration = $subs_pack['trial_duration'];
         $member->trial_duration_type = $subs_pack['trial_duration_type'];
         $member->trial_num_cycles = $subs_pack['trial_num_cycles'];
     }
     //pack currency over rides genral setting currency - issue #1602
     if (isset($subs_pack['currency']) && $subs_pack['currency'] != $currency) {
         $currency = $subs_pack['currency'];
     }
     // duration
     $member->duration = $duration;
     $member->duration_type = strtolower($duration_type);
     $member->amount = $amount;
     $member->currency = $currency;
     $member->membership_type = $membership_type;
     $member->pack_id = $pack_id;
     // $member->payment_type = ($_POST['M_payment_type']=='subscription') ?'subscription' : 'one-time';
     $member->active_num_cycles = isset($num_cycles) && !empty($num_cycles) ? $num_cycles : $subs_pack['num_cycles'];
     $member->payment_type = (int) $member->active_num_cycles == 1 ? 'one-time' : 'subscription';
     /*// payment info for unsubscribe		
     		if(!isset($member->payment_info))
     			$member->payment_info    = new stdClass;
     		$member->payment_info->module = $this->code;
     		if(isset($_POST['M_payment_type'])){
     			$member->payment_info->txn_type = $_POST['M_payment_type'];
     		}	
     		if(isset($_POST['futurePayId'])){
     			$member->payment_info->subscr_id = $_POST['futurePayId'];		
     		}	
     		if(isset($_POST['transId'])){	
     			$member->payment_info->txn_id = $_POST['transId'];	
     		}*/
     // tracking fields module_field => post_field, will be used to unsubscribe
     $tracking_fields = array('txn_type' => 'M_payment_type', 'subscr_id' => 'futurePayId', 'txn_id' => 'transId');
     // save tracking fields
     $this->_save_tracking_fields($tracking_fields, $member);
     // mgm transaction id
     $member->transaction_id = $_POST['M_custom'];
     // process PayPal response
     $new_status = $update_role = false;
     // errors
     $errors = array();
     // transStatus
     switch ($_POST['transStatus']) {
         case "Y":
             $new_status = MGM_STATUS_ACTIVE;
             $member->status_str = __('Last payment was successful', 'mgm');
             // old type match
             $old_membership_type = mgm_get_user_membership_type($user_id, 'code');
             if ($old_membership_type != $membership_type) {
                 $member->join_date = time();
                 // type join date as different var
             }
             // old content hide
             $member->hide_old_content = $hide_old_content;
             $time = time();
             $last_pay_date = isset($member->last_pay_date) ? $member->last_pay_date : null;
             $member->last_pay_date = date('Y-m-d', $time);
             // THIS will cause double calculation
             /* ***********************************/
             // check subscription_option
             if (isset($subscription_option)) {
                 // on option
                 switch ($subscription_option) {
                     // @ToDo, apply expire date login
                     case 'create':
                         // expire date will be based on current time
                     // expire date will be based on current time
                     case 'upgrade':
                         // expire date will be based on current time
                         // already on top
                         break;
                     case 'downgrade':
                         // expire date will be based on expire_date if exists, current time other wise
                     // expire date will be based on expire_date if exists, current time other wise
                     case 'extend':
                         // expire date will be based on expire_date if exists, current time other wise
                         // extend/expire date
                         // calc expiry	- issue #1226
                         // membership extend functionality broken if we try to extend the same day so removed && $last_pay_date != date('Y-m-d', $time) check
                         if (!empty($member->expire_date)) {
                             $expiry = strtotime($member->expire_date);
                             if ($expiry > 0 && $expiry > $time) {
                                 $time = $expiry;
                             }
                         }
                         break;
                 }
             }
             /*************************************/
             // type expanded
             $duration_exprs = $s_packs->get_duration_exprs();
             // if not lifetime/date range
             if (in_array($member->duration_type, array_keys($duration_exprs))) {
                 // take only date exprs
                 //consider trial duration if trial period is applicable
                 if (isset($trial_on) && $trial_on == 1) {
                     //Do it only once
                     if (!isset($member->rebilled) && isset($member->active_num_cycles) && $member->active_num_cycles != 1) {
                         $time = strtotime("+{$trial_duration} {$duration_exprs[$trial_duration_type]}", $time);
                     }
                 } else {
                     // time - issue #1068
                     $time = strtotime("+{$member->duration} {$duration_exprs[$member->duration_type]}", $time);
                 }
                 // formatted
                 $time_str = date('Y-m-d', $time);
                 // date extended
                 if (!$member->expire_date || strtotime($time_str) > strtotime($member->expire_date)) {
                     $member->expire_date = $time_str;
                 }
             } else {
                 //if lifetime:
                 if ($member->duration_type == 'l') {
                     // el = lifetime
                     $member->expire_date = '';
                 }
                 //issue #1096
                 if ($member->duration_type == 'dr') {
                     // el = /date range
                     $member->expire_date = $duration_range_end_dt;
                 }
             }
             //update rebill: issue #: 489
             if ($member->active_num_cycles != 1 && (int) $member->rebilled < (int) $member->active_num_cycles) {
                 // rebill
                 $member->rebilled = !$member->rebilled ? 1 : (int) $member->rebilled + 1;
             }
             //cancel previous subscription:
             //issue#: 565
             $this->cancel_recurring_subscription($_POST['M_custom'], null, null, $pack_id);
             // role update
             if ($role) {
                 $update_role = true;
             }
             // transaction_id
             $transaction_id = $this->_get_transaction_id('M_custom');
             // hook args
             $args = array('user_id' => $user_id, 'transaction_id' => $transaction_id);
             // another membership
             if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
                 $args['another_membership'] = $custom['membership_type'];
             }
             // after succesful payment hook
             do_action('mgm_membership_transaction_success', $args);
             // backward compatibility
             do_action('mgm_subscription_purchase_payment_success', $args);
             // new organized name
             break;
         case "C":
             $new_status = MGM_STATUS_NULL;
             $member->status_str = __('Last payment was refunded or denied', 'mgm');
             // error
             $errors[] = $member->status_str;
             break;
         case "F":
             $new_status = MGM_STATUS_PENDING;
             $reason = 'Unknown';
             $member->status_str = sprintf(__('Last payment is pending. Reason: %s', 'mgm'), $reason);
             // error
             $errors[] = $member->status_str;
             break;
         default:
             $new_status = MGM_STATUS_ERROR;
             $member->status_str = sprintf(__('Last payment status: %s', 'mgm'), $_POST['rawAuthMessage']);
             // error
             $errors[] = $member->status_str;
             break;
     }
     // old status
     $old_status = $member->status;
     // set new status
     $member->status = $new_status;
     // whether to acknowledge the user - This should happen only once
     $acknowledge_user = $this->send_payment_email($_POST['M_custom']);
     // whether to subscriber the user to Autoresponder - This should happen only once
     $acknowledge_ar = mgm_subscribe_to_autoresponder($member, $_POST['M_custom']);
     //another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         //issue #1227
         if ($subs_pack['hide_old_content']) {
             $member->hide_old_content = $subs_pack['hide_old_content'];
         }
         mgm_save_another_membership_fields($member, $user_id);
         // Multiple membership upgrade: first time
         if (isset($custom['multiple_upgrade_prev_packid']) && is_numeric($custom['multiple_upgrade_prev_packid'])) {
             mgm_multiple_upgrade_save_memberobject($custom, $member->transaction_id);
         }
     } else {
         $member->save();
     }
     // status change event
     do_action('mgm_user_status_change', $user_id, $new_status, $old_status, 'module_' . $this->module, $member->pack_id);
     //update coupon usage
     do_action('mgm_update_coupon_usage', array('user_id' => $user_id));
     // role
     if ($update_role) {
         $obj_role = new mgm_roles();
         $obj_role->add_user_role($user_id, $role);
     }
     // return action
     do_action('mgm_return_' . $this->module, array('user_id' => $user_id));
     // backward compatibility
     do_action('mgm_return_subscription_payment_' . $this->module, array('user_id' => $user_id));
     // new , individual
     do_action('mgm_return_subscription_payment', array('user_id' => $user_id, 'acknowledge_ar' => $acknowledge_ar, 'mgm_member' => $member));
     // new, global: pass mgm_member object to consider multiple level purchases as well.
     // read member again for internal updates if any
     // another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // transaction status
     mgm_update_transaction_status($member->transaction_id, $member->status, $member->status_str);
     // send email notification to client
     $blogname = get_option('blogname');
     // on status
     switch ($member->status) {
         case MGM_STATUS_ACTIVE:
             //Sending notification email to user - issue #1468
             if ($notify_user && $is_registration == 'Y') {
                 $user_pass = mgm_decrypt_password($member->user_password, $user_id);
                 do_action('mgm_register_user_notification', $user_id, $user_pass);
             }
             //sending upgrade notifaction email to admin
             if (isset($subscription_option) && $subscription_option == 'upgrade') {
                 do_action('mgm_user_upgrade_notification', $user_id);
             }
             // init
             $subscription = '';
             // add trial
             if ($subs_pack['trial_on']) {
                 // trial
                 $subscription = sprintf('%1$s %2$s for the first %3$s %4$s,<br> then ', $member->trial_cost, $member->currency, $member->trial_duration * $member->trial_num_cycles, $s_packs->get_pack_duration($subs_pack, true));
             }
             // subject
             $subject = $system_obj->get_template('payment_success_email_template_subject', array('blogname' => $blogname), true);
             // on type
             if ($member->payment_type == 'subscription') {
                 $payment_type = 'recurring subscription';
                 $subscription = sprintf('%1$s %2$s for each %3$s %4$s, %5$s', $member->amount, $member->currency, $member->duration, $s_packs->get_pack_duration($subs_pack), (int) $member->active_num_cycles > 0 ? sprintf('for %d installments', (int) $member->active_num_cycles) : 'until cancelled');
             } else {
                 $payment_type = 'one-time payment';
                 $subscription = sprintf('%1$s %2$s for %3$s %4$s', $member->amount, $member->currency, $member->duration, $s_packs->get_pack_duration($subs_pack));
             }
             // body
             $message = $system_obj->get_template('payment_success_subscription_email_template_body', array('blogname' => $blogname, 'name' => $user->display_name, 'email' => $user->user_email, 'payment_type' => $payment_type, 'subscription' => $subscription, 'admin_email' => $system_obj->setting['admin_email']), true);
             break;
         case MGM_STATUS_NULL:
             // subject
             $subject = $system_obj->get_template('payment_failed_email_template_subject', array('blogname' => $blogname), true);
             // message
             $message = $system_obj->get_template('payment_failed_email_template_body', array('blogname' => $blogname, 'name' => $user->display_name, 'email' => $user->user_email, 'payment_type' => 'subscription payment', 'reason' => $member->status_str, 'admin_email' => $system_obj->setting['admin_email']), true);
             break;
         case MGM_STATUS_PENDING:
             // subject
             $subject = $system_obj->get_template('payment_pending_email_template_subject', array('blogname' => $blogname), true);
             // body
             $message = $system_obj->get_template('payment_pending_email_template_body', array('blogname' => $blogname, 'name' => $user->display_name, 'email' => $user->user_email, 'reason' => $member->status_str, 'admin_email' => $system_obj->setting['admin_email']), true);
             break;
         case MGM_STATUS_ERROR:
             // subject
             $subject = $system_obj->get_template('payment_error_email_template_subject', array('blogname' => $blogname), true);
             // body
             $message = $system_obj->get_template('payment_error_email_template_body', array('blogname' => $blogname, 'name' => $user->display_name, 'email' => $user->user_email, 'reason' => $member->status_str, 'admin_email' => $system_obj->setting['admin_email']), true);
             break;
     }
     // notify user
     if (!$dpne) {
         if ($acknowledge_user) {
             //issue #862
             $subject = mgm_replace_email_tags($subject, $user_id);
             $message = mgm_replace_email_tags($message, $user_id);
             mgm_mail($user->user_email, $subject, $message);
             //update as email sent
             $this->update_paymentemail_sent($_POST['M_custom']);
         }
     }
     // send email notification to system administrator
     if (!$dge && $acknowledge_user) {
         $subject = "[{$blogname}] {$user->user_email} - {$member->status}";
         $message = "\tUser display name: {$user->display_name}\n\n<br />\r\r\n\t\t\t\t\tUser email: {$user->user_email}\n\n<br />\r\r\n\t\t\t\t\tUser ID: {$user->ID}\n\n<br />\r\r\n\t\t\t\t\tMembership Type: {$membership_type}\n\n<br />\r\r\n\t\t\t\t\tNew status: {$member->status}\n\n<br />\r\r\n\t\t\t\t\tStatus message: {$member->status_str}\n\n<br />\r\r\n\t\t\t\t\tSubscription period: {$member->duration} " . $s_packs->get_pack_duration($subs_pack) . "\n\n<br />\r\r\n\t\t\t\t\tSubscription amount: {$member->amount} {$member->currency}\n<br />\r\r\n\t\t\t\t\tPayment Mode: {$member->payment_type}\n\n<br />\r\r\n\t\t\t\t\tPOST Data was: \n\n<br /><br /><pre>" . print_r($_POST, true) . '</pre>';
         mgm_mail($system_obj->setting['admin_email'], $subject, $message);
     }
     // error condition redirect
     if (count($errors) > 0) {
         // mgm_redirect(add_query_arg(array('status'=>'error', 'errors'=>implode('|', $errors)), $this->_get_thankyou_url()));
         $this->_meta_redirect(add_query_arg(array('status' => 'error', 'errors' => implode('|', $errors)), $this->_get_thankyou_url()));
     }
 }
/**
 * router for url protection, API calls
 * 
 */
function mgm_url_router($wp)
{
    global $wpdb, $route, $window_title;
    // trim
    $current_uri = trim($_SERVER['REQUEST_URI']);
    // pre process hook for url router
    do_action('mgm_url_router_pre_process');
    // proxy protector for all files in mgm/downloads - more will be added later
    if (isset($_GET['protect']) && isset($_GET['file'])) {
        // get method
        $file = strip_tags($_GET['file']);
        // file
        $protect = strip_tags($_GET['protect']);
        // protected folder
        // check
        mgm_stream_file($file, $protect);
        // exit
        exit;
    }
    // check admin
    if (!is_super_admin()) {
        // TODO, improve code for less query, WARNING, not to use direct URI, posibility of SQL injection
        // having all is better to protet all scenario
        // sql
        $sql = "SELECT url,membership_types FROM `" . TBL_MGM_POST_PROTECTED_URL . "` WHERE `post_id` IS NULL ORDER BY LENGTH(`url`) DESC";
        // direct urls
        $direct_urls = $wpdb->get_results($sql);
        // check
        if ($direct_urls) {
            // loop
            foreach ($direct_urls as $direct_url) {
                // url path only
                $uri = trim(parse_url($direct_url->url, PHP_URL_PATH));
                // append end
                if (substr($uri, -1) == '*') {
                    $uri = preg_quote(str_replace('*', '', $uri), '/') . '(.*)';
                } elseif (substr($uri, -4) == ':any') {
                    $uri = preg_quote(str_replace(':any', '', $uri), '/') . '(.*)';
                } else {
                    $uri = preg_quote($uri, '/');
                }
                // pattern
                $uri_pattern = "#{$uri}#i";
                // match
                if (!empty($uri) && (strcasecmp($uri, $current_uri) == 0 || preg_match($uri_pattern, $current_uri))) {
                    // membership types
                    $membership_types = json_decode($direct_url->membership_types, true);
                    // check
                    $current_user = wp_get_current_user();
                    // access
                    $access = false;
                    // check
                    if ($current_user->ID) {
                        // get member
                        $user_membership_types = array();
                        // default
                        $user_membership_types[] = mgm_get_user_membership_type($current_user->ID, 'code');
                        // multiple
                        $user_membership_types[] = mgm_get_subscribed_membershiptypes($current_user->ID);
                        // loop
                        if (is_array($membership_types)) {
                            // loop
                            foreach ($membership_types as $membership_type) {
                                // check
                                if (in_array($membership_type, $user_membership_types)) {
                                    // set
                                    $access = true;
                                    break;
                                }
                            }
                        }
                    } else {
                        //issue #1173
                        if (is_array($membership_types) && !$current_user->ID) {
                            // loop
                            foreach ($membership_types as $membership_type) {
                                // check
                                if ($membership_type == 'guest') {
                                    // set
                                    $access = true;
                                    break;
                                }
                            }
                        }
                    }
                    // add filter
                    if (!$access) {
                        add_filter('the_content', 'mgm_url_content_protection');
                    }
                }
            }
        }
    }
    // rest api request
    if (mgm_is_restapi_request($current_uri) && mgm_api_access_allowed()) {
        // forward to api handler
        mgm_restapi_server::init();
        exit;
    }
    // post process hook for url router
    do_action('mgm_url_router_post_process');
}
 function _buy_membership()
 {
     // system
     $system_obj = mgm_get_class('system');
     $s_packs = mgm_get_class('subscription_packs');
     $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
     $dpne = bool_from_yn($system_obj->get_setting('disable_payment_notify_emails'));
     // get passthrough, stop further process if fails to parse
     $custom = $this->_get_transaction_passthrough($_POST['COMPLUS']);
     // local var
     extract($custom);
     // currency
     if (!$currency) {
         $currency = $system_obj->get_setting('currency');
     }
     // find user
     $user = get_userdata($user_id);
     //another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // Get the current AC join date
     if (!($join_date = $member->join_date)) {
         $member->join_date = time();
     }
     // Set current AC join date
     //if there is no duration set in the user object then run the following code
     if (empty($duration_type)) {
         //if there is no duration type then use Months
         $duration_type = 'm';
     }
     // membership type default
     if (empty($membership_type)) {
         //if there is no account type in the custom string then use the existing type
         $membership_type = md5($member->membership_type);
     }
     // validate parent method
     $membership_type_verified = $this->_validate_membership_type($membership_type, 'md5|plain');
     // verified
     if (!$membership_type_verified) {
         if (strtolower($member->membership_type) != 'free') {
             // notify admin, only if gateway emails on
             if (!$dge) {
                 mgm_notify_admin_membership_verification_failed($this->name);
             }
             // abort
             return;
         } else {
             $membership_type_verified = $member->membership_type;
         }
     }
     // set
     $membership_type = $membership_type_verified;
     // sub pack
     $subs_pack = $s_packs->get_pack($pack_id);
     // if trial on
     if ($subs_pack['trial_on']) {
         $member->trial_on = $subs_pack['trial_on'];
         $member->trial_cost = $subs_pack['trial_cost'];
         $member->trial_duration = $subs_pack['trial_duration'];
         $member->trial_duration_type = $subs_pack['trial_duration_type'];
         $member->trial_num_cycles = $subs_pack['trial_num_cycles'];
     }
     //pack currency over rides genral setting currency - issue #1602
     if (isset($subs_pack['currency']) && $subs_pack['currency'] != $currency) {
         $currency = $subs_pack['currency'];
     }
     // duration
     $member->duration = $duration;
     $member->duration_type = strtolower($duration_type);
     $member->amount = $amount;
     $member->currency = $currency;
     $member->membership_type = $membership_type;
     $member->pack_id = $pack_id;
     // $member->payment_type    = 'subscription' ;
     $member->active_num_cycles = isset($num_cycles) && !empty($num_cycles) ? $num_cycles : $subs_pack['num_cycles'];
     $member->payment_type = (int) $member->active_num_cycles == 1 ? 'one-time' : 'subscription';
     // payment info for unsubscribe
     if (!isset($member->payment_info)) {
         $member->payment_info = new stdClass();
     }
     // module
     $member->payment_info->module = $this->code;
     // transaction vars
     if (isset($_POST['txn_type'])) {
         $member->payment_info->txn_type = $_POST['txn_type'];
     }
     if (isset($_POST['PAYID'])) {
         $member->payment_info->subscr_id = $_POST['PAYID'];
     }
     if (isset($_POST['txn_id'])) {
         $member->payment_info->txn_id = $_POST['txn_id'];
     }
     // mgm transaction id
     $member->transaction_id = $_POST['COMPLUS'];
     // process ABN-AMRO response
     $new_status = $update_role = false;
     // statusid to name
     $payment_status = $this->_parse_payment_status($_POST['STATUS']);
     // status
     switch ($payment_status) {
         //issue#: 360
         case 'Authorized':
         case 'Payment requested':
             //status code will be 9
             $new_status = MGM_STATUS_ACTIVE;
             $member->status_str = __('Last payment was successful', 'mgm');
             // time
             $time = time();
             // old type match
             $old_membership_type = mgm_get_user_membership_type($user_id, 'code');
             if ($old_membership_type != $membership_type) {
                 $member->join_date = $time;
                 // type join date as different var
             }
             // old content hide
             $member->hide_old_content = $hide_old_content;
             $last_pay_date = isset($member->last_pay_date) ? $member->last_pay_date : null;
             // last pay
             $member->last_pay_date = date('Y-m-d', $time);
             // check subscription_option
             if (isset($subscription_option)) {
                 // on option
                 switch ($subscription_option) {
                     // @ToDo, apply expire date login
                     case 'create':
                         // expire date will be based on current time
                     // expire date will be based on current time
                     case 'upgrade':
                         // expire date will be based on current time
                         // already on top
                         break;
                     case 'downgrade':
                         // expire date will be based on expire_date if exists, current time other wise
                     // expire date will be based on expire_date if exists, current time other wise
                     case 'extend':
                         // expire date will be based on expire_date if exists, current time other wise
                         // extend/expire date
                         // calc expiry	- issue #1226
                         // membership extend functionality broken if we try to extend the same day so removed && $last_pay_date != date('Y-m-d', $time) check
                         if (!empty($member->expire_date)) {
                             $expiry = strtotime($member->expire_date);
                             if ($expiry > 0 && $expiry > $time) {
                                 $time = $expiry;
                             }
                         }
                         break;
                 }
             }
             // type expanded
             $duration_exprs = $s_packs->get_duration_exprs();
             // if not lifetime/date range
             if (in_array($member->duration_type, array_keys($duration_exprs))) {
                 // take only date exprs
                 //consider trial duration if trial period is applicable
                 if (isset($trial_on) && $trial_on == 1) {
                     //Do it only once
                     if (!isset($member->rebilled) && isset($member->active_num_cycles) && $member->active_num_cycles != 1) {
                         $time = strtotime("+{$trial_duration} {$duration_exprs[$trial_duration_type]}", $time);
                     }
                 } else {
                     // time - issue #1068
                     $time = strtotime("+{$member->duration} {$duration_exprs[$member->duration_type]}", $time);
                 }
                 // formatted
                 $time_str = date('Y-m-d', $time);
                 // date extended
                 if (!$member->expire_date || strtotime($time_str) > strtotime($member->expire_date)) {
                     $member->expire_date = $time_str;
                 }
             } else {
                 //if lifetime:
                 if ($member->duration_type == 'l') {
                     // el = lifetime
                     $member->expire_date = '';
                 }
                 //issue #1096
                 if ($member->duration_type == 'dr') {
                     // el = /date range
                     $member->expire_date = $duration_range_end_dt;
                 }
             }
             //update rebill: issue #: 489
             if ($member->active_num_cycles != 1 && (int) $member->rebilled < (int) $member->active_num_cycles) {
                 // rebill
                 $member->rebilled = !$member->rebilled ? 1 : (int) $member->rebilled + 1;
             }
             //cancel previous subscription:
             //issue#: 565
             $this->cancel_recurring_subscription($_POST['COMPLUS'], null, null, $pack_id);
             // role update
             if ($role) {
                 $update_role = true;
             }
             // transaction_id
             $transaction_id = $this->_get_transaction_id('COMPLUS');
             // hook args
             $args = array('user_id' => $user_id, 'transaction_id' => $transaction_id);
             // another membership
             if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
                 $args['another_membership'] = $custom['membership_type'];
             }
             // after succesful payment hook
             do_action('mgm_membership_transaction_success', $args);
             // backward compatibility
             do_action('mgm_subscription_purchase_payment_success', $args);
             // new organized name
             break;
         case 'Refund':
         case 'Payment refused':
         case 'Cancelled':
             $new_status = MGM_STATUS_NULL;
             $member->status_str = __('Last payment was refunded or denied', 'mgm');
             break;
         case 'Pending':
         case 'Being processed (intermediate technical status)':
             $new_status = MGM_STATUS_PENDING;
             $reason = $payment_status;
             $member->status_str = sprintf(__('Last payment is pending. Reason: %s', 'mgm'), $reason);
             break;
         default:
             $new_status = MGM_STATUS_ERROR;
             $member->status_str = sprintf(__('Last payment status: %s', 'mgm'), $payment_status);
             break;
     }
     // old status
     $old_status = $member->status;
     // set new status
     $member->status = $new_status;
     // whether to acknowledge the user - This should happen only once
     $acknowledge_user = $this->send_payment_email($_POST['COMPLUS']);
     // whether to subscriber the user to Autoresponder - This should happen only once
     $acknowledge_ar = mgm_subscribe_to_autoresponder($member, $_POST['COMPLUS']);
     //another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         //issue #1227
         if ($subs_pack['hide_old_content']) {
             $member->hide_old_content = $subs_pack['hide_old_content'];
         }
         mgm_save_another_membership_fields($member, $user_id);
         // Multiple membership upgrade: first time
         if (isset($custom['multiple_upgrade_prev_packid']) && is_numeric($custom['multiple_upgrade_prev_packid'])) {
             mgm_multiple_upgrade_save_memberobject($custom, $member->transaction_id);
         }
     } else {
         $member->save();
     }
     // status change event
     do_action('mgm_user_status_change', $user_id, $new_status, $old_status, 'module_' . $this->module, $member->pack_id);
     //update coupon usage
     do_action('mgm_update_coupon_usage', array('user_id' => $user_id));
     // role
     if ($update_role) {
         $obj_role = new mgm_roles();
         $obj_role->add_user_role($user_id, $role);
     }
     // return action
     do_action('mgm_return_' . $this->module, array('user_id' => $user_id));
     // backward compatibility
     do_action('mgm_return_subscription_payment_' . $this->module, array('user_id' => $user_id));
     // new , individual
     do_action('mgm_return_subscription_payment', array('user_id' => $user_id, 'acknowledge_ar' => $acknowledge_ar, 'mgm_member' => $member));
     // new, global: pass mgm_member object to consider multiple level purchases as well.
     // another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // transaction status
     mgm_update_transaction_status($member->transaction_id, $member->status, $member->status_str);
     // send email notification to client
     $blogname = get_option('blogname');
     // notify
     if ($acknowledge_user) {
         // notify user, only if gateway emails on
         if (!$dpne) {
             // notify
             if (mgm_notify_user_membership_purchase($blogname, $user, $member, $custom, $subs_pack, $s_packs, $system_obj)) {
                 // update as email sent
                 $this->update_paymentemail_sent($alt_tran_id);
             }
         }
         // notify admin, only if gateway emails on
         if (!$dge) {
             // pack duration
             $pack_duration = $s_packs->get_pack_duration($subs_pack);
             // notify admin,
             mgm_notify_admin_membership_purchase($blogname, $user, $member, $pack_duration);
         }
     }
     //exit if from Silent Post:
     if (isset($_POST['x_subscription_id'])) {
         exit;
     }
 }
/**
 * create purchase another button
 *
 * @param array userdata
 * @retun string html output
 */
function mgm_get_purchase_another_subscription_button($args = array())
{
    global $wpdb;
    //ceck settings
    $settings = mgm_get_class('system')->get_setting();
    // check
    if (!isset($settings['enable_multiple_level_purchase']) || isset($settings['enable_multiple_level_purchase']) && !bool_from_yn($settings['enable_multiple_level_purchase'])) {
        return;
    }
    // current user
    $user = wp_get_current_user();
    // validate
    if (!$user->ID) {
        // query string
        $user = mgm_get_user_from_querystring();
    }
    // validate
    if (!$user->ID) {
        return __('No such user', 'mgm');
    }
    // userdata
    $username = $user->user_login;
    $mgm_home = get_option('siteurl');
    $member = mgm_get_member($user->ID);
    $system_obj = mgm_get_class('system');
    $membership_type = mgm_get_user_membership_type($user->ID, 'code');
    $packs_obj = mgm_get_class('subscription_packs');
    $packs = $packs_obj->get_packs('upgrade');
    $duration_str = $packs_obj->duration_str;
    $trial_taken = $member->trial_taken;
    // pack_ids
    $pack_ids = mgm_get_members_packids($member);
    $pack_membership_types = mgm_get_subscribed_membershiptypes($user->ID, $member);
    // query_arg
    $form_action = mgm_get_custom_url('transactions', false, array('action' => 'purchase_another', 'username' => $username));
    //issue 1009
    if (isset($settings['membership_details_url'])) {
        $membership_details_url = $settings['membership_details_url'];
    } else {
        $membership_details_url = get_admin_url() . 'profile.php?page=mgm/profile';
    }
    // cancel
    $cancel_url = $membership_details_url;
    // $cancel_url = mgm_get_custom_url('membership_details');
    // active modules
    $a_payment_modules = $system_obj->get_active_modules('payment');
    // 	selected_subscription
    $selected_subs = mgm_get_selected_subscription($args);
    // second step, after post
    if (isset($_POST['submit'])) {
        // verify selected
        if (!isset($_POST['subs_opt'])) {
            // die
            return sprintf(__('Package not selected, <a href="%s">go back</a>.', 'mgm'), $_POST['form_action']);
            exit;
        }
        // get subs data
        $subs_opt_pack = mgm_decode_package($_POST['subs_opt']);
        extract($subs_opt_pack);
        // check
        $valid = false;
        // loop packs
        foreach ($packs as $pack) {
            // check
            //check pack id as well: issue#: 580
            if ($pack['cost'] == $cost && $pack['duration'] == $duration && $pack['duration_type'] == $duration_type && $membership_type == $pack['membership_type'] && $pack_id == $pack['id']) {
                $valid = true;
                break;
            }
        }
        // error
        if (!$valid) {
            return __('Invalid data passed', 'mgm');
            exit;
        }
        // get object
        $member = new mgm_member($user->ID);
        $temp_membership = $member->_default_fields();
        $temp_membership['membership_type'] = $membership_type;
        $temp_membership['pack_id'] = $pack_id;
        //issue #860
        //if (isset($_POST['mgm_upgrade_field']['autoresponder']) && ($_POST['mgm_upgrade_field']['autoresponder'])=='Y') {
        if (isset($_POST['mgm_upgrade_field']['autoresponder']) && substr($_POST['mgm_upgrade_field']['autoresponder'], 0, 1) == 'Y') {
            $temp_membership['subscribed'] = 'Y';
            $temp_membership['autoresponder'] = $system_obj->active_modules['autoresponder'];
        }
        //issue #1236
        if (isset($_POST['mgm_upgrade_field']['coupon']) && !empty($_POST['mgm_upgrade_field']['coupon'])) {
            //issue #1250 - Coupon validation
            if (!empty($_POST['form_action'])) {
                // check if its a valid coupon
                if (!($coupon = mgm_get_coupon_data($_POST['mgm_upgrade_field']['coupon']))) {
                    //redirect back to the form
                    $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'error_field_value' => $_POST['mgm_upgrade_field']['coupon']);
                    $redirect = add_query_arg($q_arg, $_POST['form_action']);
                    // redirect
                    mgm_redirect($redirect);
                    exit;
                } else {
                    // membership type check
                    // get subs
                    if ($subs_pack = mgm_decode_package(mgm_post_var('subs_opt'))) {
                        // values
                        $coupon_values = mgm_get_coupon_values(NULL, $coupon['value'], true);
                        // check
                        if (isset($coupon_values['new_membership_type']) && $coupon_values['new_membership_type'] != $subs_pack['membership_type']) {
                            $new_membership_type = mgm_get_membership_type_name($coupon_values['new_membership_type']);
                            $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'membership_type' => $coupon_values['new_membership_type'], 'error_field_value' => $_POST['mgm_upgrade_field']['coupon']);
                            $redirect = add_query_arg($q_arg, $_POST['form_action']);
                            // redirect
                            mgm_redirect($redirect);
                            exit;
                        }
                    }
                }
            }
        }
        //inserted an incomplete entry for the selected subscription type
        mgm_save_another_membership_fields($temp_membership, $user->ID);
        // save coupon fields and update member object
        $member = mgm_save_partial_fields_purchase_more($user->ID, $membership_type, $cost);
        // coupon
        $purchase_another_coupon = false;
        // array
        if (isset($member->upgrade)) {
            if (is_array($member->upgrade) && isset($member->upgrade['coupon']['id'])) {
                $purchase_another_coupon = $member->upgrade['coupon'];
            } elseif (is_object($member->upgrade) && isset($member->upgrade->coupon->id)) {
                $purchase_another_coupon = mgm_object2array($member->upgrade->coupon);
            }
            // coupon
            mgm_get_purchase_another_coupon_pack($purchase_another_coupon, $pack);
        }
        //save custom fields -issue #1285
        if (isset($_POST['mgm_upgrade_field']) && !empty($_POST['mgm_upgrade_field'])) {
            //member
            $cf_member = mgm_get_member($user->ID);
            //upgrade custom fileds
            $cfu_fileds = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_multiple_membership_level_purchase' => true)));
            //loop fields
            foreach ($cfu_fileds as $cf_filed) {
                //skip coupon and autoresponder
                if (in_array($cf_filed['name'], array('coupon', 'autoresponder'))) {
                    continue;
                }
                //check
                if (isset($_POST['mgm_upgrade_field'][$cf_filed['name']])) {
                    // check upgrae and required
                    if ((bool) $cf_filed['attributes']['required'] === true) {
                        if (empty($_POST['mgm_upgrade_field'][$cf_filed['name']])) {
                            //redirect back to the form
                            $q_arg = array('error_field' => $cf_filed['label'], 'error_type' => 'empty', 'error_field_value' => $_POST['mgm_upgrade_field'][$cf_filed['name']]);
                            $redirect = add_query_arg($q_arg, $_POST['form_action']);
                            mgm_redirect($redirect);
                            exit;
                        }
                    }
                    //appending custom fields
                    if (isset($cf_member->custom_fields->{$cf_filed}['name'])) {
                        $cf_member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                    } else {
                        $cf_member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                    }
                }
            }
            $cf_member->save();
        }
        // start html
        $html = '<div>';
        // free
        if (($pack['cost'] == 0 || $membership_type == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->is_enabled()) {
            $html .= sprintf('<div>%s - %s</div>', __('Create a free account ', 'mgm'), ucwords($membership_type));
            $module = 'mgm_free';
            // payments url
            $payments_url = mgm_get_custom_url('transactions');
            // if tril module selected and cost is 0 and free moduleis not active
            if ($membership_type == 'trial') {
                if (in_array('mgm_trial', $a_payment_modules)) {
                    $module = 'mgm_trial';
                }
            }
            //Purchase Another Membership Level problem : issue #: 752
            $redirect = add_query_arg(array('method' => 'payment_return', 'module' => $module, 'custom' => $user->ID . '_' . $duration . '_' . $duration_type . '_' . $pack_id . '_Y', 'redirector' => $redirector), $payments_url);
            // redirect
            if (!headers_sent()) {
                @header('location: ' . $redirect);
                exit;
            }
            // js redirect
            $html .= sprintf('<script type="text/javascript">window.location = "%s";</script><div>%s</div>', $redirect, $packs_obj->get_pack_desc($pack));
        } else {
            $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $packs_obj->get_pack_desc($pack));
            // coupon
            if (isset($purchase_another_coupon['id'])) {
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', sprintf(__('Using Coupon "%s" - %s', 'mgm'), $purchase_another_coupon['name'], $purchase_another_coupon['description']));
            }
            $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', __('Please Select from Available Payment Gateways', 'mgm'));
        }
        //bypass if payment gateway field is selected -issue #1764
        if ((double) $pack['cost'] > 0 && isset($_POST['mgm_payment_gateways']) && !empty($_POST['mgm_payment_gateways'])) {
            //init
            $tran_id = 0;
            if (!$tran_id) {
                $tran_id = mgm_add_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
            }
            // module
            $mod_obj = mgm_get_module($_POST['mgm_payment_gateways'], 'payment');
            // module end point
            $redirect = $mod_obj->_get_endpoint('html_redirect', false);
            // encode id:
            //encode transaction id
            $encode_tran_id = mgm_encode_id($tran_id);
            //args
            $redirect = add_query_arg(array('tran_id' => $encode_tran_id), $redirect);
            // do the redirect to payment
            mgm_redirect($redirect);
        }
        // init
        $payment_modules = array();
        // when active
        if ($a_payment_modules) {
            // loop
            foreach ($a_payment_modules as $payment_module) {
                // not trial
                if (in_array($payment_module, array('mgm_free', 'mgm_trial'))) {
                    continue;
                }
                //consider only the modules assigned to pack
                if (isset($pack['modules']) && !in_array($payment_module, (array) $pack['modules'])) {
                    continue;
                }
                // store
                $payment_modules[] = $payment_module;
            }
        }
        // loop payment mods if not free
        if (count($payment_modules) && $cost) {
            // transaction
            $tran_id = 0;
            // loop
            foreach ($payment_modules as $module) {
                // module
                $mod_obj = mgm_get_module($module, 'payment');
                // create transaction
                // if(!$tran_id) $tran_id = $mod_obj->_create_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
                if (!$tran_id) {
                    $tran_id = mgm_add_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
                }
                // button
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $mod_obj->get_button_subscribe(array('pack' => $pack, 'tran_id' => $tran_id)));
            }
        } else {
            if ($cost) {
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', __('There are no payment gateways available at this time.', 'mgm'));
            }
        }
        // html
        $html .= '</div>';
    } else {
        // first step show upgrade options
        // html
        $html = sprintf('<p class="message register">%s</p>', __('Please Select from Available Membership Packages', 'mgm'));
        // upgrade_packages
        $upgrade_packages = '';
        // pack to modules
        $pack_modules = array();
        // loop
        foreach ($packs as $pack) {
            // default
            $checked = '';
            // skip already purchased packs
            if (in_array($pack['id'], $pack_ids)) {
                continue;
            }
            //skip same membership level subscriptions
            if (in_array($pack['membership_type'], $pack_membership_types)) {
                continue;
            }
            // do not show trial or free as upgradre
            if ($pack['membership_type'] == 'trial' || $pack['membership_type'] == 'free') {
                continue;
            }
            // reset
            $checked = mgm_select_subscription($pack, $selected_subs);
            // skip other when a package sent as selected
            if ($selected_subs !== false) {
                if (empty($checked)) {
                    continue;
                }
            }
            // checked
            if (!$checked) {
                $checked = (int) $pack['default'] == 1 ? ' checked="checked"' : '';
            }
            // duration
            if ($pack['duration'] == 1) {
                $dur_str = rtrim($duration_str[$pack['duration_type']], 's');
            } else {
                $dur_str = $duration_str[$pack['duration_type']];
            }
            $css_group = mgm_get_css_group();
            // encode pack
            $subs_opt_enc = mgm_encode_package($pack);
            // set
            $pack_modules[$subs_opt_enc] = $pack['modules'];
            //issue #867
            if ($css_group != 'none') {
                //expand this if needed
                $css_link_format = '<link rel="stylesheet" href="%s" type="text/css" media="all" />';
                $css_file = MGM_ASSETS_URL . 'css/' . $css_group . '/mgm.form.fields.css';
                $upgrade_packages .= sprintf($css_link_format, $css_file);
            }
            // free
            if (($pack['cost'] == 0 || strtolower($pack['membership_type']) == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->enabled == 'Y') {
                // input
                $input = sprintf('<input type="radio" %s class="checkbox" name="subs_opt" value="%s" rel="mgm_subscription_options"/>', $checked, $subs_opt_enc);
                // html
                $upgrade_packages .= '  
							<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
								<div class="mgm_subs_option ' . $pack['membership_type'] . '">
									' . $input . '
								</div>
								<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
									' . $packs_obj->get_pack_desc($pack) . '
								</div>
								 <div class="clearfix"></div>
								 <div class="mgm_subs_desc ' . $pack['membership_type'] . '">
									' . mgm_stripslashes_deep($pack['description']) . '
								 </div>
							</div>';
            } else {
                // input
                $input = sprintf('<input type="radio" %s class="checkbox" name="subs_opt" value="%s" rel="mgm_subscription_options"/>', $checked, $subs_opt_enc);
                // html
                $upgrade_packages .= '  
							<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
								<div class="mgm_subs_option ' . $pack['membership_type'] . '">
									' . $input . '
								</div>
								<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
									' . $packs_obj->get_pack_desc($pack) . '
								</div>
								 <div class="clearfix"></div>
								 <div class="mgm_subs_desc ' . $pack['membership_type'] . '">
									' . mgm_stripslashes_deep($pack['description']) . '
								 </div>
							</div>';
            }
        }
        // add pack_modules as json data, may consider jquery data later
        if (!empty($pack_modules)) {
            $html .= sprintf('<script language="javascript">var mgm_pack_modules = %s</script>', json_encode($pack_modules));
        }
        // show error
        if (!$upgrade_packages) {
            // html
            $html .= '<div class="mgm_subs_wrapper">
						<div class="mgm_subs_pack_desc">
							' . __('Sorry, no packages available.', 'mgm') . '
						</div>
					 </div>
					 <p>						
						<input type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '" class="button-primary" />&nbsp;					
					 </p>';
        } else {
            /*			$error_field = mgm_request_var('error_field'); 
            			if(!empty($error_field)) {
            				$errors = new WP_Error();
            				switch (mgm_request_var('error_type')) {
            					case 'empty':
            						$error_string = 'You must provide a ';
            						break;
            					case 'invalid':
            						$error_string = 'Invalid ';
            						break;	
            				}				
            				//issue #703
            				$errors->add( $error_field, __( '<strong>ERROR</strong>: '.$error_string, 'mgm' ).$error_field );
            				$html .= mgm_set_errors($errors, true);					
            			}*/
            // check errors if any:
            $html .= mgm_subscription_purchase_errors();
            // form
            $html .= '<form action="' . $form_action . '" method="post" class="mgm_form"><div class="mgm_get_pack_form_container">';
            $html .= '<input type="hidden" name="form_action" value="' . $form_action . '" />';
            $html .= $upgrade_packages;
            //issue #1285
            $html .= mgm_get_custom_fields($user->ID, array('on_multiple_membership_level_purchase' => true), 'mgm_upgrade_field');
            // html
            $html .= '<input type="hidden" name="ref" value="' . md5($member->amount . '_' . $member->duration . '_' . $member->duration_type . '_' . $member->membership_type) . '" />';
            // set
            $html .= '<p>						
						<input class="button" type="submit" name="submit" value="' . __('Next', 'mgm') . '" />&nbsp;&nbsp;
						<input class="button" type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '"/>&nbsp;					
					  </p>';
            // html
            $html .= '</div></form>';
        }
    }
    // return
    return $html;
}
/**
 * user subscription
 */
function mgm_user_subscription_info($user_id = NULL, $args = array())
{
    // current user
    if (!$user_id) {
        $user = wp_get_current_user();
    } else {
        // by user id
        $user = get_userdata($user_id);
    }
    // return when no user
    if (!isset($user->ID) || isset($user->ID) && (int) $user->ID == 0) {
        return sprintf(__('Please <a href="%s">login</a> to see your subscriptions.', 'mgm'), mgm_get_custom_url('login'));
    }
    // settings
    $settings = mgm_get_class('system')->get_setting();
    // packs
    $subscription_packs = mgm_get_class('subscription_packs');
    $duration_str = $subscription_packs->duration_str;
    //issue #946
    $duration_str_plu = $subscription_packs->duration_str_plu;
    // member
    $member = mgm_get_member($user->ID);
    //mgm_pr($member);
    // pack
    $pack_id = $member->pack_id;
    $pack = $subscription_packs->get_pack($pack_id);
    //mgm_pr($pack);
    $extend_link = '';
    $subs_package = 'N/A';
    // allow renewal
    if ($pack) {
        // dsc
        $subs_package = $pack['description'];
        //issue#: 478
        $num_cycles = isset($member->active_num_cycles) && !empty($member->active_num_cycles) ? $member->active_num_cycles : $pack['num_cycles'];
        // check cycles
        if ($num_cycles > 0 && mgm_pack_extend_allowed($pack)) {
            $extend_link = ' (<a href="' . mgm_get_custom_url('transactions', false, array('action' => 'extend', 'pack_id' => $pack_id, 'username' => $user->user_login)) . '">' . __('Extend', 'mgm') . '</a>)';
        }
    }
    // set others
    $sformat = mgm_get_date_format('date_format_short');
    //issue #946
    // dur, #1452
    if ($member->trial_on) {
        $durstr = $member->trial_duration == 1 ? $duration_str[$member->trial_duration_type] : $duration_str_plu[$member->trial_duration_type];
        $durstr .= ' ( ' . __('Trial', 'mgm') . ' )';
    } else {
        $durstr = $member->duration == 1 ? $duration_str[$member->duration_type] : $duration_str_plu[$member->duration_type];
    }
    // $durstr   = ($member->duration == 1) ? rtrim($duration_str[$member->duration_type]) : $duration_str[$member->duration_type];
    $amount = is_numeric($member->amount) ? sprintf(__('%1$s %2$s', 'mgm'), number_format($member->amount, 2, '.', null), $user->currency) : 'N/A';
    $last_pay = $member->last_pay_date ? date($sformat, strtotime($member->last_pay_date)) : 'N/A';
    $expiry = $member->expire_date ? date($sformat, strtotime($member->expire_date)) : 'N/A';
    //issue #946
    // #1452
    if ($member->trial_on) {
        $duration = $member->trial_duration ? $member->trial_duration_type == 'l' ? $durstr : $member->trial_duration . ' ' . $durstr : 'N/A';
    } else {
        $duration = $member->duration ? $member->duration_type == 'l' ? $durstr : $member->duration . ' ' . $durstr : 'N/A';
    }
    // $duration = $member->duration ? (($member->duration_type == 'l') ? $durstr : $member->duration . ' ' . $durstr .($member->duration > 1 ? 's' :'')): 'N/A';
    $membership_type = $member->membership_type;
    // init
    $html = '';
    // html
    $html .= '<div class="table width100 br">';
    // row counter
    $row_ctr = 0;
    // row
    $html .= '
		<div class="row alternate br_bottom">
			<div class="cell width25 padding10px">
				<strong>' . __('Access Duration', 'mgm') . '</strong>
			</div>
			<div class="cell width2 padding10px"><strong>:</strong></div>
			<div class="cell width73 padding10px">' . esc_html($duration) . '</div>
		</div>
		<div class="row br_bottom">
			<div class="cell width25 padding10px"><strong>' . __('Last Payment Date', 'mgm') . '</strong></div>
			<div class="cell width2 padding10px" ><strong>:</strong></div>
			<div class="cell width73 padding10px">' . esc_html($last_pay) . '</div>
		</div>';
    // counter
    $row_ctr = 2;
    // duration
    if ($member->duration_type != 'l') {
        $html .= '
			<div class="row alternate br_bottom">
				<div class="cell width25 padding10px"><strong>' . __('Expiry Date', 'mgm') . '</strong></div>
				<div class="cell width2 padding10px"><strong>:</strong></div>
				<div class="cell width73 padding10px">' . esc_html($expiry) . $extend_link . '</div>
			</div>';
        // counter
        $row_ctr++;
    }
    // cost
    $html .= '
		<div class="row ' . ($row_ctr++ % 2 == 0 ? 'alternate' : '') . ' br_bottom">
			<div class="cell width25 padding10px"><strong>' . __('Membership Cost', 'mgm') . '</strong></div>
			<div class="cell width2 padding10px"><strong>:</strong></div>
			<div class="cell width73 padding10px">' . ((is_super_admin() ? 'N/A' : esc_html($amount)) . ' ' . mgm_get_class('system')->setting['currency']) . '</div>
		</div>
		
		<div class="row ' . ($row_ctr++ % 2 == 0 ? 'alternate' : '') . ' br_bottom">
			<div class="cell width25 padding10px"><strong>' . __('Membership Level', 'mgm') . '</strong></div>
			<div class="cell width2 padding10px"><strong>:</strong></div>
			<div class="cell width73 padding10px">' . ((is_super_admin() ? 'N/A' : mgm_stripslashes_deep(esc_html(mgm_get_user_membership_type($user->ID)))) . ' (<a href="' . mgm_get_custom_url('transactions', false, array('action' => 'upgrade', 'username' => $user->user_login)) . '">' . __('Upgrade', 'mgm') . '</a>)') . '</div>
		</div>
				
		<div class="row ' . ($row_ctr++ % 2 == 0 ? 'alternate' : '') . ' br_bottom">
			<div class="cell width25 padding10px"><strong>' . __('Subscribed Package', 'mgm') . '</strong></div>
			<div class="cell width2 padding10px"><strong>:</strong></div>
			<div class="cell width73 padding10px">' . mgm_stripslashes_deep(esc_html($subs_package)) . '</div>
		</div>';
    // append
    if (isset($settings['enable_multiple_level_purchase']) && bool_from_yn($settings['enable_multiple_level_purchase']) && mgm_check_purchasable_level_exists($user->ID, $member)) {
        $html .= '
				<div class="row ' . ($row_ctr++ % 2 == 0 ? '' : 'alternate') . ' br_bottom">
					<div class="cell width25 padding10px"><strong>' . __('Other Membership Level(s)', 'mgm') . '</strong></div>
					<div class="cell width2 padding10px"><strong>:</strong></div>
					<div class="cell width73 padding10px">' . (is_super_admin() ? __('N/A', 'mgm') : '<a href="' . mgm_get_custom_url('transactions', false, array("action" => "purchase_another", "username" => $user->user_login)) . '">' . __('Purchase', 'mgm') . ' </a>') . '</div>
				</div>';
    }
    // end
    $html .= '</div>';
    // init
    $unsubscribe = 0;
    // via short code
    if (!empty($args)) {
        $unsubscribe = isset($args['unsubscribe']) ? $args['unsubscribe'] : str_replace('#', '', mgm_array_shift($args));
    }
    // get button
    if ($unsubscribe == 'unsubscribe') {
        // stat
        $html .= '<br/><div class="table width100">';
        // button
        $html .= mgm_get_unsubscribe_status_button($member, $user);
        // end
        $html .= '</div>';
    }
    // apply filter
    return apply_filters('mgm_user_subscription_html', $html, $user->ID);
}
 function _buy_membership()
 {
     // system
     $system_obj = mgm_get_class('system');
     $s_packs = mgm_get_class('subscription_packs');
     $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
     $dpne = bool_from_yn($system_obj->get_setting('disable_payment_notify_emails'));
     // custom var
     $alt_tran_id = $this->_get_alternate_transaction_id();
     // get passthrough, stop further process if fails to parse
     $custom = $this->_get_transaction_passthrough($alt_tran_id);
     // local var
     extract($custom);
     // currency
     if (!$currency) {
         $currency = $system_obj->get_setting('currency');
     }
     // find user
     $user = get_userdata($user_id);
     // another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // Get the current AC join date
     if (!($join_date = $member->join_date)) {
         $member->join_date = time();
     }
     // Set current AC join date\
     // if there is no duration set in the user object then run the following code
     if (empty($duration_type)) {
         // if there is no duration type then use Months
         $duration_type = 'm';
     }
     // membership type default
     if (empty($membership_type)) {
         // if there is no account type in the custom string then use the existing type
         $membership_type = md5($member->membership_type);
     }
     // validate parent method
     $membership_type_verified = $this->_validate_membership_type($membership_type, 'md5|plain');
     // verified
     if (!$membership_type_verified) {
         if (strtolower($member->membership_type) != 'free') {
             // notify admin, only if gateway emails on
             if (!$dge) {
                 mgm_notify_admin_membership_verification_failed($this->name);
             }
             // abort
             return;
         } else {
             $membership_type_verified = $member->membership_type;
         }
     }
     // set
     $membership_type = $membership_type_verified;
     // sub pack
     $subs_pack = $s_packs->get_pack($pack_id);
     // exit flag
     $exitif_subscr_signup = true;
     // if trial on
     if (isset($custom['trial_on']) && $custom['trial_on'] == 1) {
         $member->trial_on = $custom['trial_on'];
         $member->trial_cost = $custom['trial_cost'];
         $member->trial_duration = $custom['trial_duration'];
         $member->trial_duration_type = $custom['trial_duration_type'];
         $member->trial_num_cycles = $custom['trial_num_cycles'];
         // 0 cost trial does not send payment_status, make check here
         // this should be causing trouble for MGA #969, mis firing payment success for failed payment, add support
         if ($member->trial_cost == 0 && !isset($_POST['payment_status'])) {
             // when subscr_id present, treat it as Processed , #287 issue, with trial cost is 0, only subscr_signup is sent without payment_status
             // with trial cost > 0, subscr_signup and subscr_payment sent with payment_status
             if (isset($_POST['subscr_id'])) {
                 $_POST['payment_status'] = 'Processed';
                 $exitif_subscr_signup = false;
             }
         }
     } elseif ($subs_pack['trial_on']) {
         $member->trial_on = $subs_pack['trial_on'];
         $member->trial_cost = $subs_pack['trial_cost'];
         $member->trial_duration = $subs_pack['trial_duration'];
         $member->trial_duration_type = $subs_pack['trial_duration_type'];
         $member->trial_num_cycles = $subs_pack['trial_num_cycles'];
         // 0 cost trial does not send payment_status, make check here
         // this should be causing trouble for MGA #969, mis firing payment success for failed payment, add support
         if ($member->trial_cost == 0 && !isset($_POST['payment_status'])) {
             // when subscr_id present, treat it as Processed , #287 issue, with trial cost is 0, only subscr_signup is sent without payment_status
             // with trial cost > 0, subscr_signup and subscr_payment sent with payment_status
             if (isset($_POST['subscr_id'])) {
                 $_POST['payment_status'] = 'Processed';
                 $exitif_subscr_signup = false;
             }
         }
     }
     // exit scenarios
     if (!isset($_POST['payment_status']) || $exitif_subscr_signup && isset($_POST['txn_type']) && $_POST['txn_type'] == 'subscr_signup') {
         exit;
     }
     // double check txn type for MGA#969, subscr_failed triggers successful payment for trial packs
     if (isset($_POST['txn_type']) && $_POST['txn_type'] == 'subscr_failed') {
         exit;
     }
     //pack currency over rides genral setting currency - issue #1602
     if (isset($subs_pack['currency']) && $subs_pack['currency'] != $currency) {
         $currency = $subs_pack['currency'];
     }
     // member fields
     $member->duration = $duration;
     $member->duration_type = strtolower($duration_type);
     $member->amount = $amount;
     $member->currency = $currency;
     $member->membership_type = $membership_type;
     $member->pack_id = $pack_id;
     $member->active_num_cycles = isset($num_cycles) && !empty($num_cycles) ? $num_cycles : $subs_pack['num_cycles'];
     $member->payment_type = (int) $member->active_num_cycles == 1 ? 'one-time' : 'subscription';
     //one time pack subscription id option become an issue #1507
     if (isset($subs_pack['num_cycles']) == 1 && !isset($_POST['subscr_id'])) {
         $_POST['subscr_id'] = 'ONE-TIME SUBSCRIPTION';
     }
     // tracking fields module_field => post_field, will be used to unsubscribe
     $tracking_fields = array('txn_type' => 'txn_type', 'subscr_id' => 'subscr_id', 'txn_id' => 'txn_id');
     // save tracking fields
     $this->_save_tracking_fields($tracking_fields, $member);
     // check here: ->module is absent in payment_info, its is _save_tracking_fields
     // if (!isset($member->payment_info->module)) $member->payment_info->module = $this->code;
     // set parent transaction id
     $member->transaction_id = $alt_tran_id;
     // process PayPal response
     $new_status = $update_role = false;
     // status
     switch ($_POST['payment_status']) {
         case 'Completed':
         case 'Processed':
             // status
             $new_status = MGM_STATUS_ACTIVE;
             $member->status_str = __('Last payment was successful', 'mgm');
             // old type match
             $old_membership_type = mgm_get_user_membership_type($user_id, 'code');
             // set
             if ($old_membership_type != $membership_type) {
                 $member->join_date = time();
                 // type join date as different var
             }
             // old content hide
             $member->hide_old_content = $hide_old_content;
             $time = time();
             $last_pay_date = isset($member->last_pay_date) ? $member->last_pay_date : null;
             // last pay
             $member->last_pay_date = date('Y-m-d', $time);
             // as per version 1.0, there was chance of double process, with new separation logic for rebill, this is safe
             // check subscription_option
             if (isset($subscription_option)) {
                 // on option
                 switch ($subscription_option) {
                     // @ToDo, apply expire date login
                     case 'create':
                         // expire date will be based on current time
                     // expire date will be based on current time
                     case 'upgrade':
                         // expire date will be based on current time
                         // already on top
                         break;
                     case 'downgrade':
                         // expire date will be based on expire_date if exists, current time other wise
                     // expire date will be based on expire_date if exists, current time other wise
                     case 'extend':
                         // expire date will be based on expire_date if exists, current time other wise
                         // extend/expire date
                         // calc expiry	- issue #1226
                         // membership extend functionality broken if we try to extend the same day so removed && $last_pay_date != date('Y-m-d', $time) check
                         if (!empty($member->expire_date)) {
                             $expiry = strtotime($member->expire_date);
                             if ($expiry > 0 && $expiry > $time) {
                                 $time = $expiry;
                             }
                         }
                         break;
                 }
             }
             // type expanded
             $duration_exprs = $s_packs->get_duration_exprs();
             // if not lifetime/date range
             if (in_array($member->duration_type, array_keys($duration_exprs))) {
                 // take only date exprs
                 // consider trial duration if trial period is applicable
                 if (isset($trial_on) && $trial_on == 1 && (!isset($member->trial_used) || (int) $member->trial_used < (int) $member->trial_num_cycles)) {
                     // is it the root of #1150 issue
                     // Do it only once
                     if (!isset($member->rebilled) && isset($member->active_num_cycles) && $member->active_num_cycles != 1) {
                         // set
                         $time = strtotime("+{$trial_duration} {$duration_exprs[$trial_duration_type]}", $time);
                         // increment trial used, each IPN should increement this and extend
                         $member->trial_used = !$member->trial_used ? 1 : (int) $member->trial_used + 1;
                     }
                 } else {
                     // time - issue #1068
                     $time = strtotime("+{$member->duration} {$duration_exprs[$member->duration_type]}", $time);
                 }
                 // formatted
                 $time_str = date('Y-m-d', $time);
                 // date extended
                 if (!$member->expire_date || strtotime($time_str) > strtotime($member->expire_date)) {
                     $member->expire_date = $time_str;
                 }
             } else {
                 //if lifetime:
                 if ($member->duration_type == 'l') {
                     // el = lifetime
                     $member->expire_date = '';
                 }
                 //issue #1096
                 if ($member->duration_type == 'dr') {
                     // el = /date range
                     $member->expire_date = $duration_range_end_dt;
                 }
             }
             // update rebill: issue #: 489
             if ($member->active_num_cycles != 1 && (int) $member->rebilled < (int) $member->active_num_cycles) {
                 // rebill
                 $member->rebilled = !$member->rebilled ? 1 : (int) $member->rebilled + 1;
             }
             // cancel previous subscription:
             // issue#: 565
             $this->cancel_recurring_subscription($alt_tran_id, null, null, $pack_id);
             // role update
             if ($role) {
                 $update_role = true;
             }
             // transaction_id
             $transaction_id = $this->_get_transaction_id();
             // hook args
             $args = array('user_id' => $user_id, 'transaction_id' => $transaction_id);
             // another membership
             if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
                 $args['another_membership'] = $custom['membership_type'];
             }
             // after succesful payment hook
             do_action('mgm_membership_transaction_success', $args);
             // backward compatibility
             do_action('mgm_subscription_purchase_payment_success', $args);
             // new organized name
             break;
         case 'Reversed':
         case 'Refunded':
         case 'Denied':
             // status
             $new_status = MGM_STATUS_NULL;
             $member->status_str = __('Last payment was refunded or denied', 'mgm');
             break;
         case 'Pending':
             // status
             $new_status = MGM_STATUS_PENDING;
             $reason = 'Unknown';
             $member->status_str = sprintf(__('Last payment is pending. Reason: %s', 'mgm'), $reason);
             break;
         default:
             // status
             $new_status = MGM_STATUS_ERROR;
             $member->status_str = sprintf(__('Last payment status: %s', 'mgm'), $_POST['payment_status']);
             break;
     }
     // handle exceptions from the subscription specific fields
     if ($new_status == MGM_STATUS_ACTIVE && in_array($_POST['txn_type'], array('subscr_failed', 'subscr_eot'))) {
         $new_status = MGM_STATUS_NULL;
         $member->status_str = __('The subscription is not active', 'mgm');
     }
     // old status
     $old_status = $member->status;
     // set new status
     $member->status = $new_status;
     // whether to acknowledge the user - This should happen only once
     $acknowledge_user = $this->send_payment_email($alt_tran_id);
     // whether to subscriber the user to Autoresponder - This should happen only once
     $acknowledge_ar = mgm_subscribe_to_autoresponder($member, $_POST['custom']);
     // another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         //issue #1227
         if ($subs_pack['hide_old_content']) {
             $member->hide_old_content = $subs_pack['hide_old_content'];
         }
         // save
         mgm_save_another_membership_fields($member, $user_id);
         // Multiple membership upgrade: first time
         if (isset($custom['multiple_upgrade_prev_packid']) && is_numeric($custom['multiple_upgrade_prev_packid'])) {
             mgm_multiple_upgrade_save_memberobject($custom, $member->transaction_id);
         }
     } else {
         // save
         $member->save();
     }
     // status change event
     do_action('mgm_user_status_change', $user_id, $new_status, $old_status, 'module_' . $this->module, $member->pack_id);
     //update coupon usage
     do_action('mgm_update_coupon_usage', array('user_id' => $user_id));
     // role update
     if ($update_role) {
         $obj_role = new mgm_roles();
         $obj_role->add_user_role($user_id, $role);
     }
     // return action
     do_action('mgm_return_' . $this->module, array('user_id' => $user_id, 'acknowledge_user' => $acknowledge_user));
     // backward compatibility
     do_action('mgm_return_subscription_payment_' . $this->module, array('user_id' => $user_id));
     // new , individual
     do_action('mgm_return_subscription_payment', array('user_id' => $user_id, 'acknowledge_ar' => $acknowledge_ar, 'mgm_member' => $member));
     // new, global: pass mgm_member object to consider multiple level purchases as well.
     // read member again for internal updates if any
     // another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // transaction status
     mgm_update_transaction_status($member->transaction_id, $member->status, $member->status_str);
     // send email notification to client
     $blogname = get_option('blogname');
     // for paypal only
     if (in_array($_POST['txn_type'], array('subscr_payment', 'subscr_signup', 'web_accept')) && in_array($_POST['payment_status'], array('Processed', 'Completed'))) {
         $acknowledge_user = true;
     } else {
         $acknowledge_user = false;
     }
     // notify
     if ($acknowledge_user) {
         // notify user, only if gateway emails on
         if (!$dpne) {
             // notify
             if (mgm_notify_user_membership_purchase($blogname, $user, $member, $custom, $subs_pack, $s_packs, $system_obj)) {
                 // update as email sent
                 $this->update_paymentemail_sent($alt_tran_id);
             }
         }
         // notify admin, only if gateway emails on
         if (!$dge) {
             // pack duration
             $pack_duration = $s_packs->get_pack_duration($subs_pack);
             // notify admin,
             mgm_notify_admin_membership_purchase($blogname, $user, $member, $pack_duration);
         }
     }
 }