/**
 * 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;
}
 function _member_update_subscription(&$member, $user_id, $system_obj, $previous_membership)
 {
     // return
     $return = array();
     // getpack
     $subs_pack = mgm_decode_package(mgm_post_var('upd_subscription_pack'));
     $pack_obj = mgm_get_class('subscription_packs');
     $packdetails = $pack_obj->get_pack($subs_pack['pack_id']);
     // if trial on
     if (isset($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'];
     }
     // duration
     $member->duration = $subs_pack['duration'];
     $member->duration_type = strtolower($subs_pack['duration_type']);
     $member->active_num_cycles = $packdetails['num_cycles'];
     $member->amount = $subs_pack['cost'];
     $member->currency = $system_obj->setting['currency'];
     $member->membership_type = $subs_pack['membership_type'];
     $member->pack_id = $subs_pack['pack_id'];
     // old status
     $return['old_status'] = $member->status;
     // set new status
     $member->status = $return['new_status'] = MGM_STATUS_ACTIVE;
     // set status str
     $member->status_str = __('Subscription update successful', 'mgm');
     // old type match and join date update
     // $old_membership_type = mgm_get_user_membership_type($user_id, 'code');
     // update if new subscription  OR guest user
     /*
     $is_new_pack = (   strtolower($previous_membership->membership_type) == 'guest' 
                     || (mgm_post_var('insert_new_level') == 'new') 
     				|| (isset($previous_membership->pack_id) && $previous_membership->pack_id != strtolower($member->pack_id)) 
     				|| empty($member->join_date) 
     			   );
     */
     $is_new_pack = empty($member->join_date) || 'new' == mgm_post_var('insert_new_level');
     // if new subscription pack is assigned
     // update join date
     if ($is_new_pack) {
         $member->join_date = time();
         // type join date as different var
     }
     // old content hide
     //$member->hide_old_content = $subs_pack['hide_old_content'];
     //issue #1100
     $member->hide_old_content = $packdetails['hide_old_content'];
     // time
     $time = time();
     // last pay date
     if (!isset($member->last_pay_date)) {
         $member->last_pay_date = date('Y-m-d', $time);
     }
     // expiration date
     if (!bool_from_yn(mgm_post_var('no_expiration_date_update', 'N'))) {
         // expire
         if ($member->expire_date && $member->last_pay_date != date('Y-m-d', $time)) {
             // expiry
             $expiry = strtotime($member->expire_date);
             // greater
             if ($expiry > 0) {
                 // time check
                 if ($expiry > $time) {
                     // update
                     $time = $expiry;
                 }
             }
         }
         // duration types expanded
         $duration_exprs = $pack_obj->get_duration_exprs();
         // time
         if (in_array($member->duration_type, array_keys($duration_exprs))) {
             // take only date exprs
             // time
             $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) || mgm_post_var('insert_new_level') == 'new') {
                 // This is to make sure that expire date is not copied from the selected members if any
                 $member->expire_date = $time_str;
             }
         }
         //date range - issue #1190
         if ($member->duration_type == 'dr') {
             // el = /date range
             if (time() < strtotime($packdetails['duration_range_start_dt']) || time() > strtotime($packdetails['duration_range_end_dt'])) {
                 $member->status = MGM_STATUS_EXPIRED;
             }
             $member->expire_date = $packdetails['duration_range_end_dt'];
         }
     }
     // if lifetime:
     if ($subs_pack['duration_type'] == 'l' && $member->status == MGM_STATUS_ACTIVE) {
         $member->expire_date = '';
         if (isset($member->status_reset_on)) {
             unset($member->status_reset_on);
         }
         if (isset($member->status_reset_as)) {
             unset($member->status_reset_as);
         }
     }
     // autoresponder - issue #1266
     if (!bool_from_yn(mgm_post_var('subscribe_to_autoresponder', 'N')) && isset($_POST['subscribe_to_autoresponder'])) {
         // set
         $member->subscribed = 'Y';
         $member->autoresponder = $system_obj->active_modules['autoresponder'];
         // call
         mgm_autoresponder_send_subscribe($user_id, $member);
     }
     // return
     return $return;
 }
/**
 * register post process
 *
 * @param int $user_id 
 * @return void or int $user_id
 */
function mgm_register($user_id)
{
    global $wpdb, $post;
    // check import in action and skip, tools->import calls mgm_register via "user_register" hook, this will help skip
    if (defined('MGM_DOING_USERS_IMPORT') && MGM_DOING_USERS_IMPORT == TRUE) {
        // return
        return $user_id;
    }
    // get mgm_system
    $system_obj = mgm_get_class('system');
    // hide
    $hide_custom_fields = $system_obj->get_setting('hide_custom_fields');
    // packs
    $packs = mgm_get_class('subscription_packs');
    // members object
    $member = mgm_get_member($user_id);
    // set status
    $member->set_field('status', MGM_STATUS_NULL);
    // get custom fields
    $cf_register_page = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true)));
    // mgm_subscription
    $mgm_subscription = mgm_post_var('mgm_subscription');
    // get subs
    $subs_pack = mgm_decode_package($mgm_subscription);
    // extract
    extract($subs_pack);
    // payment_gateways if set:
    $mgm_payment_gateways = mgm_post_var('mgm_payment_gateways');
    // Eg: $_POST['mgm_payment_gateways'] = mgm_paypal
    $cf_payment_gateways = !empty($mgm_payment_gateways) ? $mgm_payment_gateways : NULL;
    // init
    $member_custom_fields = array();
    // wordpress register
    $wordpres_form = mgm_check_wordpress_login();
    // system - issue #1237
    $short_format = !empty($system_obj->setting['date_format_short']) ? $system_obj->setting['date_format_short'] : MGM_DATE_FORMAT_SHORT;
    // loop
    foreach ($cf_register_page as $field) {
        // skip custom fields by settings call
        if ($hide_custom_fields == 'Y' || $hide_custom_fields == 'W' && $wordpres_form || $hide_custom_fields == 'C' && !$wordpres_form) {
            // if($hide_custom_fields && $field['name'] != 'subscription_options') continue;
            if (!in_array($field['name'], array('subscription_options', 'payment_gateways'))) {
                continue;
            }
        }
        //skip if payment_gateways custom field
        if ($field['name'] == 'payment_gateways') {
            continue;
        }
        //
        // do not save html
        if ($field['type'] == 'html' || $field['type'] == 'label') {
            continue;
        }
        // save
        switch ($field['name']) {
            case 'username':
                // #739
                if (isset($_POST[$field['attributes']['capture_field_alias']])) {
                    $member_custom_fields[$field['name']] = @$_POST[$field['attributes']['capture_field_alias']];
                } else {
                    $member_custom_fields[$field['name']] = @$_POST['user_login'];
                }
                break;
            case 'email':
                // #739
                if (isset($_POST[$field['attributes']['capture_field_alias']])) {
                    $member_custom_fields[$field['name']] = @$_POST[$field['attributes']['capture_field_alias']];
                } else {
                    $member_custom_fields[$field['name']] = @$_POST['user_email'];
                }
                break;
            case 'password':
                // #739
                // check
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    if (!empty($_POST[$field['attributes']['capture_field_alias']])) {
                        $user_password = @$_POST[$field['attributes']['capture_field_alias']];
                        $member_custom_fields[$field['name']] = mgm_encrypt_password($user_password, $user_id);
                    }
                } else {
                    if (!empty($_POST['user_password'])) {
                        $user_password = $_POST['user_password'];
                        $member_custom_fields[$field['name']] = mgm_encrypt_password($user_password, $user_id);
                    }
                }
                break;
            case 'autoresponder':
                // #739
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    // checked issue #839
                    // if(in_array(strtolower($_POST[$field['attributes']['capture_field_alias']]), array('y','yes'))){
                    if (!empty($_POST[$field['attributes']['capture_field_alias']]) && $_POST['mgm_register_field'][$field['name']] == $field['value']) {
                        $member->subscribed = 'Y';
                        $member->autoresponder = $system_obj->active_modules['autoresponder'];
                    }
                } else {
                    // checked issue #839
                    // if(in_array(strtolower($_POST['mgm_register_field'][$field['name']]), array('y','yes'))){
                    if (!empty($_POST['mgm_register_field'][$field['name']]) && $_POST['mgm_register_field'][$field['name']] == $field['value']) {
                        // set to member, to be used on payment
                        $member->subscribed = 'Y';
                        $member->autoresponder = $system_obj->active_modules['autoresponder'];
                    }
                }
                break;
            case 'coupon':
                // #739
                // check alias
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    // check
                    if (!empty($_POST[$field['attributes']['capture_field_alias']])) {
                        // validate
                        if ($coupon = mgm_validate_coupon($_POST[$field['attributes']['capture_field_alias']], $cost)) {
                            // set
                            $member->coupon = $coupon;
                            // update coupon usage
                            mgm_update_coupon_usage($coupon['id'], 'register');
                        }
                    }
                } else {
                    // check primary
                    if (isset($_POST['mgm_register_field'][$field['name']]) && !empty($_POST['mgm_register_field'][$field['name']])) {
                        // validate
                        if ($coupon = mgm_validate_coupon($_POST['mgm_register_field'][$field['name']], $cost)) {
                            // set
                            $member->coupon = $coupon;
                            // update coupon usage
                            mgm_update_coupon_usage($coupon['id'], 'register');
                        }
                    }
                }
                break;
            case 'birthdate':
                // #739
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    //issue #1237
                    $member_custom_fields[$field['name']] = mgm_format_inputdate_to_mysql($_POST[$field['attributes']['capture_field_alias']], $short_format);
                } else {
                    //convert from short date format to mysql format - issue #1237
                    $member_custom_fields[$field['name']] = mgm_format_inputdate_to_mysql($_POST['mgm_register_field'][$field['name']], $short_format);
                }
                break;
            default:
                // #739
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    $member_custom_fields[$field['name']] = @$_POST[$field['attributes']['capture_field_alias']];
                } elseif ($field['type'] == 'checkbox' && is_array(@$_POST['mgm_register_field'][$field['name']])) {
                    //$member_custom_fields[$field['name']] = implode(" ", @$_POST['mgm_register_field'][$field['name']]);
                    //issue #1070
                    $val = @$_POST['mgm_register_field'][$field['name']];
                    $member_custom_fields[$field['name']] = serialize($val);
                } else {
                    $member_custom_fields[$field['name']] = @$_POST['mgm_register_field'][$field['name']];
                }
                break;
        }
    }
    // end fields save
    // user password not provided
    /*
    	if (!isset( $user_password )){
    		$user_password = (isset($_POST['pass1']) && !empty($_POST['pass1'])) ? trim($_POST['pass1']) : substr(md5(uniqid(microtime())), 0, 7);		
    	}*/
    // user password not provided
    if (!isset($user_password)) {
        // take custom password fields, iss#717, consider BP custom password field
        $password_fields = array('pass1', 'signup_password');
        // loop
        foreach ($password_fields as $password_field) {
            // check if set
            if (isset($_POST[$password_field]) && !empty($_POST[$password_field])) {
                $user_password = trim($_POST[$password_field]);
                break;
            }
        }
    }
    // auto generate if still missing
    if (!isset($user_password)) {
        $user_password = substr(md5(uniqid(microtime())), 0, 7);
    }
    //encrypt password and save in
    $member->user_password = mgm_encrypt_password($user_password, $user_id);
    // md5
    $user_password_hash = wp_hash_password($user_password);
    // db update
    $wpdb->query($wpdb->prepare("UPDATE `{$wpdb->users}` SET `user_pass` = %s WHERE ID = %d", $user_password_hash, $user_id));
    // unset label fields
    if (isset($member_custom_fields['password_conf'])) {
        unset($member_custom_fields['password_conf']);
    }
    // set custom
    $member->set_custom_fields($member_custom_fields);
    // set pack
    if ($pack_id) {
        // pack
        $pack = $packs->get_pack($pack_id);
        // set
        $member->amount = $pack['cost'];
        $member->duration = $pack['duration'];
        $member->duration_type = $pack['duration_type'];
        $member->active_num_cycles = $pack['num_cycles'];
        // set membership type
        $member->membership_type = $membership_type;
        // from mgm_subscription
        // set in member
        $member->pack_id = $pack_id;
        // from mgm_subscription
    }
    // set status
    $member->status = MGM_STATUS_NULL;
    // update option
    $member->save();
    // update user firstname/last name
    mgm_update_default_userdata($user_id);
    // admin check
    $is_admin = is_admin();
    //&& current_user_can('manage_options');
    // send
    $notify_user = true;
    // Block registration emails if Buddypress is enabled and disable_registration_email_bp value is Yes
    $block_reg_email = bool_from_yn(mgm_get_class('system')->get_setting('disable_registration_email_bp'));
    // send notification, bp active, do not send password, #739
    if (!isset($_POST['send_password']) && $is_admin || mgm_is_plugin_active('buddypress/bp-loader.php') && $block_reg_email) {
        $notify_user = false;
    }
    // send notification - issue #1468
    if ($system_obj->setting['enable_new_user_email_notifiction_after_user_active'] == 'N') {
        if ($notify_user) {
            mgm_new_user_notification($user_id, $user_password, $is_admin ? false : true);
        }
        $notify_user = false;
    }
    // hook for other plugin who wishes to use default "user_register"
    do_action('mgm_user_register', $user_id);
    // process payment only when registered from site, not when user added by admin
    if ($is_admin) {
        // unset
        unset($_POST['send_password']);
        //prevent sending user email again
        // assign default pack
        do_action('mgm_admin_user_register', $user_id, $notify_user);
        // return id
        return $user_id;
    }
    // if on wordpress page or custompage
    $post_id = get_the_ID();
    // post custom register
    if ($post_id > 0 && $post->post_type == 'post') {
        $redirect = get_permalink($post_id);
    } else {
        $redirect = mgm_get_custom_url('transactions');
    }
    // if buddypress url replace by register url : issue#: 791
    $redirect = apply_filters('mgm_bp_register_url', $redirect);
    // userdata
    $userdata = get_userdata($user_id);
    // note this fix VERY IMPORTANT, needed for PAYPAL PRO CC POST
    $redirect = add_query_arg(array('username' => urlencode($userdata->user_login)), $redirect);
    // add redirect
    if ($redirector = mgm_request_var('mgm_redirector', mgm_request_var('redirect_to', '', true), true)) {
        $redirect = add_query_arg(array('redirector' => $redirector), $redirect);
    }
    // with subscription
    if ($mgm_subscription) {
        $redirect = add_query_arg(array('subs' => $mgm_subscription, 'method' => 'payment_subscribe'), $redirect);
    }
    // bypass step2 if payment gateway is submitted: issue #: 469
    if (!is_null($cf_payment_gateways)) {
        // pack
        $packs_obj = mgm_get_class('subscription_packs');
        // validate
        $pack = $packs_obj->validate_pack($cost, $duration, $duration_type, $membership_type, $pack_id);
        // error
        if ($pack != false) {
            // get pack
            mgm_get_register_coupon_pack($member, $pack);
            // cost
            if ((double) $pack['cost'] > 0) {
                //get an object of the payment gateway:
                $mod_obj = mgm_get_module($cf_payment_gateways, 'payment');
                // tran options
                $tran_options = array('is_registration' => true, 'user_id' => $user_id, 'notify_user' => $notify_user);
                // is register & purchase
                if (isset($_POST['post_id'])) {
                    $tran_options['post_id'] = (int) $_POST['post_id'];
                }
                // is register & purchase postpack
                if (isset($_POST['postpack_post_id']) && isset($_POST['postpack_id'])) {
                    $tran_options['postpack_post_id'] = (int) $_POST['postpack_post_id'];
                    $tran_options['postpack_id'] = (int) $_POST['postpack_id'];
                }
                // create transaction
                // $tran_id = $mod_obj->_create_transaction($pack, $tran_options);
                $tran_id = mgm_add_transaction($pack, $tran_options);
                //bypass directly to process return if manual payment:
                if ($cf_payment_gateways == 'mgm_manualpay') {
                    // set
                    $_POST['custom'] = $tran_id;
                    // direct call to module return function:
                    $mod_obj->process_return();
                    // exit
                    exit;
                }
                // encode id:
                $tran_id = mgm_encode_id($tran_id);
                // redirect - if on wordpress page or custompage - issue #1648
                if ($post_id > 0 && $post->post_type == 'post') {
                    $redirect = $mod_obj->_get_endpoint('html_redirect', true);
                } else {
                    $redirect = $mod_obj->_get_endpoint('html_redirect', false);
                }
                // if buddypress url replace by register url : issue#: 791
                $redirect = add_query_arg(array('tran_id' => $tran_id), apply_filters('mgm_bp_register_url', $redirect));
            } else {
                // issue #1468
                $redirect = add_query_arg(array('notify_user' => $notify_user), $redirect);
            }
        }
    }
    // ends custom payment gateway bypassing
    // is register & purchase
    if (isset($_POST['post_id'])) {
        $redirect = add_query_arg(array('post_id' => (int) $_POST['post_id']), $redirect);
    }
    // is register & purchase postpack
    if (isset($_POST['postpack_post_id']) && isset($_POST['postpack_id'])) {
        $redirect = add_query_arg(array('postpack_id' => (int) $_POST['postpack_id'], 'postpack_post_id' => (int) $_POST['postpack_post_id']), $redirect);
    }
    // redirect filter, returing a false can stop the redirect
    $redirect = apply_filters('mgm_after_regiter_redirect', mgm_site_url($redirect));
    // redirect
    if ($redirect !== FALSE) {
        // do the redirect to payment
        mgm_redirect($redirect);
        // this goes to subscribe, mgm_functions.php/mgm_get_subscription_buttons
        // exit
        exit;
    }
    // default
    return $user_id;
}
/**
 * custom register form, used in sidebar
 *
 * @param boolean $use_custom_fields
 * @param boolean $default_subscription_pack
 * @return string $form
 */
function mgm_sidebar_user_register_form($use_custom_fields, $default_subscription_pack)
{
    // registration disabled
    if (!get_option('users_can_register')) {
        // redirect
        return __('User registration is currently not allowed.', 'mgm');
    }
    // system
    $system_obj = mgm_get_class('system');
    // register button text
    $register_button_text = apply_filters('mgm_register_button_text', $system_obj->get_setting('register_text', __('Register', 'mgm')));
    // cf
    $cf_register_page = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true)));
    // html form
    $html = '<form name="registerform" id="registerform" action="' . mgm_get_custom_url('register') . '" method="post">';
    // email as username
    // if(bool_from_yn($system_obj->get_setting('enable_email_as_username'))){
    // 	$email_username_label = __('Email','mgm');
    // }else{
    // 	$email_username_label = __('Username','mgm');
    // }
    // username
    if (!bool_from_yn($system_obj->get_setting('enable_email_as_username'))) {
        if (!mgm_is_customfield_active(array('username'), $cf_register_page) || !$use_custom_fields) {
            $html .= '<p>
						<label>' . __('Username', 'mgm') . '<br />
						<input type="text" name="user_login" id="user_login" class="input" value="" size="20" tabindex="10" /></label>
					  </p>';
        }
    }
    // email
    if (!mgm_is_customfield_active(array('email'), $cf_register_page) || !$use_custom_fields) {
        $html .= '<p>
					<label>' . __('E-mail', 'mgm') . '<br />
					<input type="email" name="user_email" id="user_email" class="input" value="" size="20" tabindex="20" /></label>
				  </p>';
    }
    // custom
    if ($use_custom_fields) {
        // do_action('register_form');
        // custom
        $html .= apply_filters('mgm_register_form', $html);
        //Issue #777
    } elseif ($default_subscription_pack) {
        $obj_packs = mgm_get_class('subscription_packs');
        $packs = $obj_packs->get_packs('register');
        $subs_pack = mgm_decode_package($default_subscription_pack);
        $modules = array();
        foreach ($packs as $pack) {
            if ($pack['id'] == $subs_pack['pack_id']) {
                $modules = $pack['modules'];
            }
        }
        $cnt = count($modules);
        if ($cnt > 1) {
            for ($i = 0; $i < $cnt; $i++) {
                //issue #1298
                if (in_array($modules[$i], array('mgm_free', 'mgm_trial'))) {
                    continue;
                }
                //issue #1298
                if ($subs_pack['cost'] == 0 && mgm_get_module('mgm_free')->enabled == 'Y') {
                    continue;
                }
                $mod_obj = mgm_get_module($modules[$i], 'payment');
                $img_url = mgm_site_url($mod_obj->logo);
                $checked = $i === 0 ? 'checked="true"' : '';
                //module description
                $html .= sprintf('<div id="%s_container" class="mgm_payment_opt_wrapper" %s>', $mod_obj->code, $hide_div) . sprintf('<input type="radio" %s class="checkbox" name="mgm_payment_gateways" value="%s" alt="%s" />', $checked, $mod_obj->code, $mod_obj->name) . sprintf('<img class="mgm_payment_opt_customfield_image" src="%s" alt="%s" />', $img_url, $mod_obj->name) . sprintf('<div class="mgm_paymod_description">%s</div>', mgm_stripslashes_deep($mod_obj->description)) . '</div>';
            }
        } else {
            $html .= '<input type="hidden" name="mgm_payment_gateways" value="' . (isset($modules[0]) ? $modules[0] : '') . '" alt="Paypal Standard"/>';
            //@todo need actual first module
        }
        $html .= '<input type="hidden" class="checkbox" name="mgm_subscription" value="' . $default_subscription_pack . '"/>';
        $html .= '<input type="hidden" class="checkbox" name="mgm_custom_fields" value="' . $use_custom_fields . '"/>';
        $html .= '<input type="hidden" class="checkbox" name="mgm_widget_active" value="true"/>';
    }
    // nonce
    $nonce = wp_nonce_field('user_register', '_mgmnonce_user_register', true, false);
    // html
    $html .= '<p id="reg_passmail">' . __('A password will be e-mailed to you.') . '</p>
		 	  <p><input class="button mgm-register-button" type="submit" name="wp-submit" id="wp-submit" value="' . $register_button_text . '" tabindex="100" /></p>
		  	  <input type="hidden" name="method" value="create_user">
			 ' . $nonce . '
		  </form>';
    // apply filter and return
    return apply_filters('mgm_sidebar_register_form_html', $html);
}