function mgm_modify_retrieve_password_emailbody($message)
{
    global $wpdb, $current_site, $wp_hasher;
    $system_obj = mgm_get_class('system');
    $blogname = is_multisite() ? $current_site->site_name : wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
    if (strpos($_POST['user_login'], '@')) {
        $user_data = get_user_by('email', trim($_POST['user_login']));
    } else {
        $login = trim($_POST['user_login']);
        $user_data = get_user_by('login', $login);
    }
    $user_login = $user_data->user_login;
    //just fetch the key from db as it is already updated
    $key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM {$wpdb->users} WHERE user_login = %s", $user_login));
    //issue #1464
    if ($system_obj->get_setting('enable_default_wp_lost_password') == "Y") {
        //issue #1665
        if (mgm_compare_wp_version('3.7', '>=')) {
            // Generate something random for a password reset key.
            $key = wp_generate_password(20, false);
            do_action('retrieve_password_key', $user_login, $key);
            // Now insert the key, hashed, into the DB.
            if (empty($wp_hasher)) {
                require_once ABSPATH . 'wp-includes/class-phpass.php';
                $wp_hasher = new PasswordHash(8, true);
            }
            $hashed = $wp_hasher->HashPassword($key);
            $wpdb->update($wpdb->users, array('user_activation_key' => $hashed), array('user_login' => $user_login));
        }
        //password link
        $passwordlink = network_site_url("wp-login.php?action=rp&key={$key}&login=" . rawurlencode($user_login), 'login');
    } else {
        $passwordlink = mgm_get_custom_url('login', false, array('action' => 'rp', 'key' => $key, 'login' => rawurlencode($user_login)));
    }
    // subject
    $body = $system_obj->get_template('retrieve_password_email_template_body', array('blogname' => $blogname, 'siteurl' => network_site_url(), 'username' => $user_login, 'passwordlink' => $passwordlink), true);
    //issue #862
    $body = mgm_replace_email_tags($body, $user_data->ID);
    //apply mgm content type
    add_filter('wp_mail_content_type', 'mgm_get_mail_content_type', 10);
    // return
    return $body;
}
示例#2
0
?>
	
					});		
					// wp3.6+
					jQuery( "#subs_pkgs_panel" ).accordion( "refresh" );					
				});	
			}
			
			load_roles_capabilities_others=function(){
				jQuery('#roles_capabilities_list_others').load('admin-ajax.php?action=mgm_admin_ajax_action&page=mgm/admin/members&method=roles_capabilities_list_others', function(){
					// set up accordian
					jQuery("#roles_list_div_others").accordion({
						collapsible: true,
						active: false,
						<?php 
if (mgm_compare_wp_version('3.6', '>=')) {
    ?>
						heightStyle: 'content'
						<?php 
} else {
    ?>
						autoHeight: true,
						fillSpace: false,
						clearStyle: true
						<?php 
}
?>
	
					});			
					// wp3.6+
					jQuery( "#subs_pkgs_panel" ).accordion( "refresh" );				
/**
 * show buttons of modules available for upgrade/downgrade/complete payment
 *
 * @param array args
 * @return string html
 */
function mgm_get_upgrade_buttons($args = array())
{
    global $wpdb;
    // current user
    $user = wp_get_current_user();
    // get user
    if (!$user->ID) {
        // get user from 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');
    // upgrdae multiple
    $multiple_upgrade = false;
    //issue #1511
    $prev_pack_id = mgm_get_var('prev_pack_id', '', true);
    $prev_membership_type = mgm_get_var('membership_type', '', true);
    // get member
    // issue#: 843 (3)
    if (isset($prev_pack_id) && (int) $prev_pack_id > 0 && isset($prev_membership_type) && !empty($prev_membership_type)) {
        // only for multiple membership upgrade
        $multiple_upgrade = true;
        // get member
        $member = mgm_get_member_another_purchase($user->ID, $prev_membership_type, $prev_pack_id);
        // mark status as inactive
        $member->status = MGM_STATUS_NULL;
    } else {
        $member = mgm_get_member($user->ID);
        //this is a fix for issue#: 589, see the notes for details:
        //This is to read saved coupons as array in order to fix the fatal error on some servers.
        //This will change the object on each users profile view.
        //Also this will avoid using patch for batch update,
        $old_coupons_found = 0;
        // loop
        foreach (array('upgrade', 'extend') as $coupon_type) {
            // check
            if (isset($member->{$coupon_type}['coupon']) && is_object($member->{$coupon_type}['coupon'])) {
                // convert
                $member->{$coupon_type}['coupon'] = (array) $member->{$coupon_type}['coupon'];
                // mark
                $old_coupons_found++;
            }
        }
        // save if old coupons found
        if ($old_coupons_found) {
            $member->save();
        }
    }
    // other objects
    $system_obj = mgm_get_class('system');
    $packs_obj = mgm_get_class('subscription_packs');
    // membership_type
    $membership_type = isset($prev_membership_type) && !empty($prev_membership_type) ? $prev_membership_type : mgm_get_user_membership_type($user->ID, 'code');
    // captured above
    // duration
    $duration_str = $packs_obj->duration_str;
    $trial_taken = $member->trial_taken;
    // pack_id if main mgm_member / multiple membership
    $pack_id = isset($prev_pack_id) && (int) $prev_pack_id > 0 ? $prev_pack_id : (int) $member->pack_id;
    // got pack
    if ($pack_id) {
        $pack_details = $packs_obj->get_pack($pack_id);
        $pack_membership_type = $pack_details['membership_type'];
        $preference = $pack_details['preference'];
    } else {
        $preference = 0;
    }
    // action - issue #1275
    $action = mgm_get_var('action', '', true);
    if ($action == 'complete_payment') {
        // get active packs on complete payment page
        $active_packs = $packs_obj->get_packs('register');
    } else {
        // get active packs on upgrade page
        $active_packs = $packs_obj->get_packs('upgrade');
        //issue #1368
        // loop and preference
        foreach ($active_packs as $_pack) {
            // set preference order for later sort
            $pack_preferences[] = $_pack['preference'];
        }
        // preference sort packs
        if (count($pack_preferences) > 0) {
            // preference sort
            sort($pack_preferences);
            //preference sorted
            $preferences_sorted = array();
            // loop by preference
            foreach ($pack_preferences as $pack_preference) {
                //issue #1710
                if ($pack_preference >= $preference) {
                    // loop packs
                    foreach ($active_packs as $_pack) {
                        // preference order match
                        if ($_pack['preference'] == $pack_preference) {
                            // duplicate check
                            if (!in_array($_pack['id'], $preferences_sorted)) {
                                // set pack
                                $preference_packs[] = mgm_stripslashes_deep($_pack);
                                // mark as preference sorted
                                $preferences_sorted[] = $_pack['id'];
                            }
                        }
                    }
                }
            }
        }
        $active_packs = $preference_packs;
    }
    // issue#: 664
    // action : upgrade/complete_payment. Allow complete payment only if there is an associated $pack_id and the current subscription is not free/trial
    $action = !empty($action) && (int) $pack_id > 0 ? $action : 'upgrade';
    // upgrade or complete_payment
    // show current
    $show_current_pack = false;
    // switch
    if ($action == 'complete_payment' && isset($pack_membership_type) && in_array($pack_membership_type, array('free', 'trial'))) {
        // upgrade
        $action = 'upgrade';
        // show current
        $show_current_pack = true;
    }
    // form action
    // carry forward get params
    $url_parms = array('action' => $action, 'user_id' => $user->ID);
    // 'username'=> $username,
    // prev_membership_type
    if (isset($prev_membership_type)) {
        $url_parms['membership_type'] = $prev_membership_type;
    }
    // prev_pack_id
    if (isset($prev_pack_id)) {
        $url_parms['prev_pack_id'] = $prev_pack_id;
    }
    // form action
    $form_action = mgm_get_custom_url('transactions', false, $url_parms);
    // issue 1009
    if (!($membership_details_url = $system_obj->get_setting('membership_details_url'))) {
        $membership_details_url = get_admin_url() . 'profile.php?page=mgm/profile';
    }
    // cancel
    $cancel_url = $action == 'upgrade' && $user->ID > 0 ? $membership_details_url : mgm_get_custom_url('login');
    // active modules
    $a_payment_modules = $system_obj->get_active_modules('payment');
    // bug from liquid-dynamiks.com theme #779
    if (isset($_POST['wpsb_email'])) {
        unset($_POST['wpsb_email']);
    }
    // posted form-----------------------------------------------------------------------
    if (!empty($_POST) || isset($_GET['edit_userinfo'])) {
        // update user data
        if (isset($_POST['method']) && $_POST['method'] == 'update_user') {
            // user lib
            if (mgm_compare_wp_version('3.1', '<')) {
                // only before 3.1
                require_once ABSPATH . WPINC . '/registration.php';
            }
            // callback
            // do_action('personal_options_update', $user->ID);
            // not multisite, duplicate email allowed ?
            if (!is_multisite()) {
                // save
                $errors = mgm_user_profile_update($user->ID);
            } else {
                // multi site
                // get user
                $user = get_userdata($user->ID);
                // update here:
                // Update the email address, if present. duplicate check
                if ($user->user_login && isset($_POST['user_email']) && is_email($_POST['user_email']) && $wpdb->get_var($wpdb->prepare("SELECT user_login FROM {$wpdb->signups} WHERE user_login = %s", $user->user_login))) {
                    $wpdb->query($wpdb->prepare("UPDATE {$wpdb->signups} SET user_email = %s WHERE user_login = %s", $_POST['user_email'], $user->user_login));
                }
                // edit
                if (!isset($errors) || isset($errors) && is_object($errors) && false == $errors->get_error_codes()) {
                    $errors = mgm_user_profile_update($user->ID);
                }
            }
            // errors
            if (isset($errors) && !is_numeric($errors)) {
                // get error
                $error_html = mgm_set_errors($errors, true);
                // edit flag
                $_GET['edit_userinfo'] = 1;
            }
        }
        // second step for complete payment, userdata edit
        if (isset($_GET['edit_userinfo'])) {
            // error
            if (isset($error_html)) {
                $html .= $error_html;
            }
            // form
            $html .= sprintf('<form action="%s" method="post" class="mgm_form">', $form_action);
            $html .= sprintf('<p>%s</p>', __('Edit Your Personal Information', 'mgm'));
            // get custom fields
            $html .= mgm_user_profile_form($user->ID, true);
            // html
            $html .= '<input type="hidden" name="ref" value="' . md5($member->amount . '_' . $member->duration . '_' . $member->duration_type . '_' . $member->membership_type) . '" />';
            $html .= '<input type="hidden" name="form_action" value="' . $form_action . '" />';
            $html .= '<input type="hidden" name="subs_opt" value="' . $_POST['subs_opt'] . '" rel="mgm_subscription_options"/>';
            // carry forward mgm_payment_gateways field value: issue#: 919
            if (isset($_POST['mgm_payment_gateways'])) {
                $html .= '<input type="hidden" name="mgm_payment_gateways" value="' . $_POST['mgm_payment_gateways'] . '" />';
            }
            //issue #1236
            if (isset($_POST['mgm_upgrade_field']['coupon']) && !empty($_POST['mgm_upgrade_field']['coupon'])) {
                //issue #1250 - Coupon validation
                if (!empty($_POST['form_action'])) {
                    //issue #1591
                    $coupon_err_redirect_url = $_POST['form_action'];
                    if (preg_match('/complete_payment/', $coupon_err_redirect_url)) {
                        $coupon_err_redirect_url = str_replace('&edit_userinfo=1', '', $coupon_err_redirect_url);
                    }
                    // 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, $coupon_err_redirect_url);
                        mgm_redirect($redirect);
                        exit;
                    } else {
                        // 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, $coupon_err_redirect_url);
                                mgm_redirect($redirect);
                                exit;
                            }
                        }
                    }
                }
                $html .= '<input type="hidden" name="mgm_upgrade_field[coupon]" value="' . $_POST['mgm_upgrade_field']['coupon'] . '" class="mgm_upgrade_field">';
            }
            // set
            $html .= sprintf('<p>
								 <input class="button button-primary" type="button" name="back" onclick="window.location=\'%s\'" value="%s" />						
							 	 <input class="button button-primary" type="submit" name="submit" value="%s" />&nbsp;&nbsp;
						      	 <input class="button button-primary" type="button" name="cancel" onclick="window.location=\'%s\'" value="%s" />&nbsp;					
					          </p>', $form_action, __('Back', 'mgm'), __('Save & Next', 'mgm'), $cancel_url, __('Cancel', 'mgm'));
            // html
            $html .= '</form>';
            // final step, show payment buttons
        } elseif (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;
            }
            // check and validate passed data
            if ($_POST['ref'] != md5($member->amount . '_' . $member->duration . '_' . $member->duration_type . '_' . $member->membership_type)) {
                // die
                return __('Package data tampered. Cheatin!', 'mgm');
                exit;
            }
            // get selected pack
            $selected_pack = mgm_decode_package($_POST['subs_opt']);
            // check selected pack is a valid pack
            $valid = false;
            // loop packs
            foreach ($active_packs as $pack) {
                // check
                if ($pack['cost'] == $selected_pack['cost'] && $pack['duration'] == $selected_pack['duration'] && $pack['duration_type'] == $selected_pack['duration_type'] && $pack['membership_type'] == $selected_pack['membership_type'] && $pack['id'] == $selected_pack['pack_id']) {
                    // valid
                    $valid = true;
                    break;
                }
            }
            // error
            if (!$valid) {
                return __('Invalid package data. Cheatin!', 'mgm');
                exit;
            }
            //update description if not set
            if (!isset($selected_pack['description'])) {
                $selected_pack['description'] = $pack['description'];
            }
            //update pack currency - issue #1602
            if (isset($pack['currency']) && !empty($pack['currency'])) {
                $selected_pack['currency'] = $pack['currency'];
            }
            // num cycle
            if (!isset($selected_pack['num_cycles'])) {
                //Note the above break in for loop:
                $selected_pack['num_cycles'] = $pack['num_cycles'];
            }
            //issue#: 658
            if (isset($pack['role'])) {
                $selected_pack['role'] = $pack['role'];
            }
            //applicable modules:
            $selected_pack['modules'] = $pack['modules'];
            $selected_pack['product'] = $pack['product'];
            // trial
            if ($pack['trial_on']) {
                $selected_pack['trial_on'] = $pack['trial_on'];
                $selected_pack['trial_duration'] = $pack['trial_duration'];
                $selected_pack['trial_duration_type'] = $pack['trial_duration_type'];
                $selected_pack['trial_cost'] = $pack['trial_cost'];
                $selected_pack['trial_num_cycles'] = $pack['trial_num_cycles'];
            }
            // save member data including coupon etc, MUST save after all validation passed, we dont want any
            // unwanted value in member object unless its a valid upgrade
            // save
            if ($multiple_upgrade) {
                $member = mgm_save_partial_fields(array('on_upgrade' => true), 'mgm_upgrade_field', $selected_pack['cost'], true, strip_tags($_GET['action']), $member);
            } else {
                $member = mgm_save_partial_fields(array('on_upgrade' => true), 'mgm_upgrade_field', $selected_pack['cost'], true, strip_tags($_GET['action']));
            }
            //save custom fields issue #1285
            if (isset($_POST['mgm_upgrade_field']) && !empty($_POST['mgm_upgrade_field'])) {
                //upgrade custom fileds
                $cfu_fileds = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_upgrade' => 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($member->custom_fields->{$cf_filed}['name'])) {
                            $member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                        } else {
                            $member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                        }
                    }
                }
                $member->save();
            }
            //issue #860
            if (isset($_POST['mgm_upgrade_field']['autoresponder']) && bool_from_yn($_POST['mgm_upgrade_field']['autoresponder'])) {
                $member->subscribed = 'Y';
                $member->autoresponder = $system_obj->active_modules['autoresponder'];
                //issue #1511
                if ($multiple_upgrade) {
                    mgm_save_another_membership_fields($member, $user->ID);
                } else {
                    $member->save();
                }
                //issue #1276
            } else {
                $member->subscribed = '';
                $member->autoresponder = '';
                //issue #1511
                if ($multiple_upgrade) {
                    mgm_save_another_membership_fields($member, $user->ID);
                } else {
                    $member->save();
                }
            }
            //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']);
                        mgm_redirect($redirect);
                        exit;
                    } else {
                        // 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']);
                                mgm_redirect($redirect);
                                exit;
                            }
                        }
                    }
                }
            }
            // payment_gateways if set: Eg: $_POST['mgm_payment_gateways'] = mgm_paypal
            $cf_payment_gateways = isset($_POST['mgm_payment_gateways']) && !empty($_POST['mgm_payment_gateways']) ? $_POST['mgm_payment_gateways'] : null;
            // bypass step2 if payment gateway is submitted: issue #: 469
            // removed complete_payment checking here in order to enable coupon for complete_payment. issue#: 802
            if (!is_null($cf_payment_gateways)) {
                // get pack
                mgm_get_upgrade_coupon_pack($member, $selected_pack, strip_tags($_GET['action']));
                // cost
                if ((double) $selected_pack['cost'] > 0) {
                    //get an object of the payment gateway:
                    $mod_obj = mgm_get_module($cf_payment_gateways, 'payment');
                    // tran options
                    $tran_options = array('user_id' => $user->ID);
                    // is register & purchase
                    if (isset($_POST['post_id'])) {
                        $tran_options['post_id'] = (int) $_POST['post_id'];
                    }
                    // if multiple membership
                    if ($multiple_upgrade) {
                        $tran_options['is_another_membership_purchase'] = true;
                        // This is to replace current mgm_member object with new mgm_member object of the upgrade pack
                        $tran_options['multiple_upgrade_prev_packid'] = mgm_get_var('prev_pack_id', '', true);
                    }
                    // upgrade flag
                    if ($action == 'upgrade') {
                        $tran_options['subscription_option'] = 'upgrade';
                    }
                    // create transaction
                    // $tran_id = $mod_obj->_create_transaction($selected_pack, $tran_options);
                    $tran_id = mgm_add_transaction($selected_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;
                    }
                    // set redirect
                    $redirect = add_query_arg(array('tran_id' => mgm_encode_id($tran_id)), $mod_obj->_get_endpoint('html_redirect', true));
                    // redirect
                    mgm_redirect($redirect);
                    // this goes to subscribe, mgm_functions.php/mgm_get_subscription_buttons
                    // exit
                    exit;
                }
            }
            // end gateway
            // get coupon pack
            mgm_get_upgrade_coupon_pack($member, $selected_pack, strip_tags($_GET['action']));
            // start html
            $html = '<div>';
            // free package
            if (($selected_pack['cost'] == 0 || $selected_pack['membership_type'] == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->enabled == 'Y') {
                // html
                $html .= sprintf('<div>%s - %s</div>', __('Create a free account ', 'mgm'), ucwords($selected_pack['membership_type']));
                // module
                $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 ($selected_pack['membership_type'] == 'trial') {
                    // check
                    if (in_array('mgm_trial', $a_payment_modules)) {
                        // module
                        $module = 'mgm_trial';
                    }
                }
                // query_args -issue #1005
                $query_args = array('method' => 'payment_return', 'module' => $module, 'custom' => implode('_', array($user->ID, $selected_pack['duration'], $selected_pack['duration_type'], $selected_pack['pack_id'], 'N', $selected_pack['membership_type'])));
                // redirector
                if (isset($_REQUEST['redirector'])) {
                    // set
                    $query_args['redirector'] = $_REQUEST['redirector'];
                }
                // redirect to module to mark the payment as complete
                $redirect = add_query_arg($query_args, $payments_url);
                // redirect
                if (!headers_sent()) {
                    @header('location: ' . $redirect);
                } else {
                    // js redirect
                    $html .= sprintf('<script type="text/javascript">window.location = "%s";</script><div>%s</div>', $redirect, $packs_obj->get_pack_desc($pack));
                }
            } else {
                // paid package, generate buy buttons
                // set html
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $packs_obj->get_pack_desc($selected_pack));
                // coupon
                if (isset($member->upgrade) && is_array($member->upgrade) && isset($member->upgrade['coupon']['id'])) {
                    // set html
                    $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', sprintf(__('Using Coupon "%s" - %s', 'mgm'), $member->upgrade['coupon']['name'], $member->upgrade['coupon']['description']));
                }
                // set html
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', __('Please Select from Available Payment Gateways', 'mgm'));
            }
            // init
            $payment_modules = array();
            // active
            if (count($a_payment_modules) > 0) {
                // 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($selected_pack['modules']) && !in_array($payment_module, (array) $selected_pack['modules'])) {
                        continue;
                    }
                    // store
                    $payment_modules[] = $payment_module;
                }
            }
            // loop payment module if not free
            if (count($payment_modules) && $selected_pack['cost']) {
                // transaction
                $tran_id = false;
                $tran_options = array('user_id' => $user->ID);
                // if multiple membership
                if ($multiple_upgrade) {
                    // another
                    $tran_options['is_another_membership_purchase'] = true;
                    // This is to replace current mgm_member object with new mgm_member object of the upgrade pack
                    $tran_options['multiple_upgrade_prev_packid'] = mgm_get_var('prev_pack_id', '', true);
                }
                // upgrade
                if ($action == 'upgrade') {
                    $tran_options['subscription_option'] = 'upgrade';
                }
                // 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($selected_pack, $extra_options);
                    if (!$tran_id) {
                        $tran_id = mgm_add_transaction($selected_pack, $tran_options);
                    }
                    // set html
                    $html .= sprintf('<div>%s</div>', $mod_obj->get_button_subscribe(array('pack' => $selected_pack, 'tran_id' => $tran_id)));
                }
                // mgm_pr($_REQUEST);
                // profile edit #698
                if ($_GET['action'] == 'complete_payment') {
                    // update $form_action for user data edit
                    if (isset($_COOKIE['wp_tempuser_login']) && $_COOKIE['wp_tempuser_login'] == $user->ID && !isset($_GET['edit_userinfo'])) {
                        // form action
                        $form_action = add_query_arg(array('edit_userinfo' => 1), $form_action);
                        // action
                        $html .= sprintf('<form action="%s" method="post" class="mgm_form">', $form_action);
                        $html .= '<input type="hidden" name="ref" value="' . md5($member->amount . '_' . $member->duration . '_' . $member->duration_type . '_' . $member->membership_type) . '" />';
                        $html .= '<input type="hidden" name="form_action" value="' . $form_action . '" />';
                        $html .= '<input type="hidden" name="subs_opt" value="' . $_POST['subs_opt'] . '" rel="mgm_subscription_options"/>';
                        // set
                        $html .= sprintf('<p><input type="button" name="back" onclick="window.location=\'%s\'" value="%s" class="button-primary" />	
											 <input type="button" name="cancel" onclick="window.location=\'%s\'" value="%s" class="button-primary" />&nbsp;					
										  </p>', $form_action, __('Edit Personal Information', 'mgm'), $cancel_url, __('Cancel', 'mgm'));
                        // html
                        $html .= '</form>';
                    }
                }
            } else {
                // no module error
                if ($selected_pack['cost']) {
                    // set html
                    $html .= sprintf('<div>%s</div>', __('Error, no payment gateways active on upgrade page, notify administrator.', 'mgm'));
                }
            }
            // html
            $html .= '</div>';
        }
        // end final step post
    } else {
        // generate upgrade/complete payment form ----------------------------------------------------------
        // selected subscription, from args (shortcode) or get url
        $selected_pack = mgm_get_selected_subscription($args);
        $css_group = mgm_get_css_group();
        // upgrade_packages
        $upgrade_packages = '';
        // pack count
        $pack_count = 0;
        // pack to modules
        $pack_modules = array();
        //mgm_pr($active_packs);
        //issue #1553
        if (!empty($active_packs)) {
            // loop	packs
            foreach ($active_packs as $pack) {
                // mgm_pr($pack);
                // default
                $checked = '';
                // for complete payment only show purchased pack
                if ($action == 'complete_payment') {
                    // pack selected
                    if (isset($pack_id)) {
                        // leave other pack, if not show other packs
                        if ($pack['id'] != $pack_id && !isset($_GET['show_other_packs'])) {
                            continue;
                        }
                        // select
                        if ($pack['id'] == $pack_id) {
                            $checked = 'checked="checked"';
                        }
                    }
                } else {
                    //  'upgrade':
                    // upgrade
                    // echo '<br>pack#' . $pack['id'] . ' step1';
                    // leave current pack, it will goto extend
                    if (isset($pack_id)) {
                        if (!$show_current_pack && $pack['id'] == $pack_id) {
                            continue;
                        }
                    }
                    // echo '<br>pack#' . $pack['id'] . ' step2';
                    // skip trial or free packs
                    if (in_array($pack['membership_type'], array('trial', 'free'))) {
                        continue;
                    }
                    // echo '<br>pack#' . $pack['id'] . ' step3';
                    // skip if not allowed
                    if (!mgm_pack_upgrade_allowed($pack)) {
                        continue;
                    }
                    // echo '<br>pack#' . $pack['id'] . ' step4';
                    // selected pack
                    if ($selected_pack !== false) {
                        // checked
                        $checked = mgm_select_subscription($pack, $selected_pack);
                        // skip other when a package sent as selected
                        if (empty($checked)) {
                            continue;
                        }
                    }
                    // echo '<br>pack#' . $pack['id'] . ' step5';
                }
                // 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']];
                }
                // encode pack
                $subs_opt_enc = mgm_encode_package($pack);
                // set
                $pack_modules[$subs_opt_enc] = $pack['modules'];
                // free
                if (($pack['cost'] == 0 || strtolower($pack['membership_type']) == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->is_enabled()) {
                    // 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>';
                }
                // count
                $pack_count++;
            }
        }
        // start
        $html = '';
        // html
        if ($pack_count > 1) {
            $html .= sprintf('<p class="message register">%s</p>', __('Please Select from Available Membership Packages', 'mgm'));
        }
        // 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));
        }
        //issue #867
        if ($css_group != 'none') {
            // set css
            $html .= sprintf('<link rel="stylesheet" href="%s/css/%s/mgm.form.fields.css" type="text/css" media="all" />', untrailingslashit(MGM_ASSETS_URL), $css_group);
        }
        // show error when no upgrde
        if (!$upgrade_packages) {
            // html
            $html .= '<div class="mgm_subs_wrapper">
						<div  class="mgm_subs_pack_desc">
							' . __('Sorry, no upgrades available.', 'mgm') . '
						</div>
					  </div>
					  <p>						
					  	  <input type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '" class="button-primary" />&nbsp;					
					  </p>';
        } else {
            // edit/other pack link
            $edit_button = $other_packs_button = '';
            // issue #: 675, issue #1279
            if ($action == 'complete_payment' || isset($_REQUEST['action']) && $_REQUEST['action'] == 'complete_payment') {
                // issue#: 416
                // mgm_pr($_GET);
                if (isset($_GET['show_other_packs'])) {
                    // other packs url - issue #1279, #1215 update, other packs url missed username
                    $other_packs_url = add_query_arg(array('action' => 'complete_payment', 'username' => $username), mgm_get_custom_url('transactions'));
                    // mgm_get_current_url()
                    //$other_packs_url   = str_replace('&show_other_packs=1', '', $other_packs_url);
                    $other_packs_label = __('Show subscribed package', 'mgm') . '';
                } else {
                    // other packs url - issue #1279, #1215 update, other packs url missed username
                    $other_packs_url = add_query_arg(array('action' => 'complete_payment', 'show_other_packs' => 1, 'username' => $username), mgm_get_custom_url('transactions'));
                    // mgm_get_current_url()
                    $other_packs_label = __('Show other packages', 'mgm');
                }
                // issue#: 710
                if (count($active_packs) > 1) {
                    // button
                    $other_packs_button = sprintf('<input type="button" value="%s" class="button-primary" onclick="window.location=\'%s\'">', $other_packs_label, $other_packs_url);
                }
                // update $form_action for user data edit
                if (isset($_COOKIE['wp_tempuser_login']) && $_COOKIE['wp_tempuser_login'] == $user->ID && !isset($_GET['edit_userinfo'])) {
                    $form_action = add_query_arg(array('edit_userinfo' => 1), $form_action);
                } else {
                    //issue #1279
                    $form_action = add_query_arg(array('action' => 'complete_payment', 'username' => $username, 'edit_userinfo' => 1), mgm_get_current_url());
                }
            }
            // echo $form_action;
            // check errors if any:
            $html .= mgm_subscription_purchase_errors();
            // form
            $html .= sprintf('<form action="%s" method="post" class="mgm_form">', $form_action);
            $html .= sprintf('<div class="mgm_get_pack_form_container">%s', $upgrade_packages);
            //issue #1285
            $html .= mgm_get_custom_fields($user->ID, array('on_upgrade' => true), 'mgm_upgrade_field');
            $html .= '<input type="hidden" name="ref" value="' . md5($member->amount . '_' . $member->duration . '_' . $member->duration_type . '_' . $member->membership_type) . '" />';
            $html .= '<input type="hidden" name="form_action" value="' . $form_action . '" />';
            // set
            $html .= sprintf('<p>%s						
							 	 <input class="button button-primary" type="submit" name="submit" value="%s" />&nbsp;&nbsp;
						      	 <input class="button button-primary" type="button" name="cancel" onclick="window.location=\'%s\'" value="%s" />&nbsp;					
					          </p>', $other_packs_button, __('Next', 'mgm'), $cancel_url, __('Cancel', 'mgm'));
            // html
            $html .= '</div></form>';
        }
        // end generate form
    }
    // end
    // return
    return $html;
}
/**
 * enque screen wise admin assets 
 *
 * @param string hook_suffix (file name)
 * @todo add all case
 */
function mgm_admin_enqueue_scripts($hook_suffix)
{
    global $wp_version, $wp_styles, $wp_scripts;
    // check and disable jquery ui
    if (isset($_GET['page']) && preg_match('#^mgm/admin#', $_GET['page'])) {
        // remove style by handler
        $style_handles = array('jquery-ui-css', 'jquery-ui', 'aiow-plugin-css', 'smoothness');
        // reset
        foreach ($style_handles as $style_handle) {
            if (isset($wp_styles->registered[$style_handle])) {
                unset($wp_styles->registered[$style_handle]);
            }
        }
        // remove script by handler
        $script_handles = array('jquery-ui');
        // reset
        foreach ($script_handles as $script_handle) {
            if (isset($wp_scripts->registered[$script_handle])) {
                unset($wp_scripts->registered[$script_handle]);
            }
        }
    }
    // screen
    $screen_id = get_current_screen()->id;
    // edit taxonomy
    if (preg_match('/^edit-/', $screen_id)) {
        if ('edit-tags.php' == $hook_suffix) {
            $screen_id = 'edit-taxonomy';
        }
    }
    // echo $screen_id;
    // post screen
    switch ($screen_id) {
        case 'post':
            // post edit,add
        // post edit,add
        case 'page':
            // page @todo custompage
            // case 'edit-post':// post listing
            // load respective jQueryUI
            $jqueryui_version = sprintf('js/jquery/jquery.ui/jquery-ui-%s.min.js', mgm_get_jqueryui_version());
            // load ui
            wp_enqueue_script('mgm-jquery-ui', MGM_ASSETS_URL . $jqueryui_version, array('jquery'));
            // custom scripts
            wp_enqueue_script('mgm-helpers', MGM_ASSETS_URL . 'js/helpers.js');
            // ui css
            wp_enqueue_style('mgm-jqueryui-css', MGM_ASSETS_URL . 'css/default/mgm/jquery.ui.css');
            wp_enqueue_style('mgm-widgets-css', MGM_ASSETS_URL . 'css/admin/mgm.widgets.css');
            break;
        case 'edit-category':
        case 'edit-post_tag':
        case 'edit-taxonomy':
            // styles
            wp_enqueue_style('mgm-adminui-css', MGM_ASSETS_URL . 'css/admin/mgm.adminui.css');
            // wp 3.3+ fix
            if (mgm_compare_wp_version('3.3', '>')) {
                wp_enqueue_style('mgm-adminui-wp3fix-css', MGM_ASSETS_URL . 'css/admin/mgm.adminui.wp3fix.css');
            }
            break;
        case 'users':
            // list
            // case 'user':// add
        // list
        // case 'user':// add
        case 'user-edit':
            // edit
            wp_enqueue_style('mgm-users-css', MGM_ASSETS_URL . 'css/admin/mgm.users.css');
            break;
        case 'dashboard':
            wp_enqueue_style('mgm-dashboard-css', MGM_ASSETS_URL . 'css/admin/mgm.dashboard.css');
            break;
        case 'profile_page_mgm/membership_details':
        case 'profile_page_mgm/membership_contents':
            // profile pages
            // ui css
            wp_enqueue_style('mgm-ui-css', MGM_ASSETS_URL . 'css/default/mgm/jquery.ui.css');
            // styles
            wp_enqueue_style('mgm-adminui-css', MGM_ASSETS_URL . 'css/admin/mgm.adminui.css');
            // styles
            wp_enqueue_style('mgm-wp-profile-css', MGM_ASSETS_URL . 'css/admin/mgm.wp-profile.css');
            break;
        case 'toplevel_page_mgm/admin':
            // mgm admin ui
            // load respective jQueryUI
            $jqueryui_version = sprintf('js/jquery/jquery.ui/jquery-ui-%s.min.js', mgm_get_jqueryui_version());
            // load ui
            wp_enqueue_script('mgm-jquery-ui', MGM_ASSETS_URL . $jqueryui_version, array('jquery'));
            // helpers scripts
            wp_enqueue_script('mgm-jquery-validate', MGM_ASSETS_URL . 'js/jquery/jquery.validate.pack.js');
            wp_enqueue_script('mgm-jquery-metadata', MGM_ASSETS_URL . 'js/jquery/jquery.metadata.js');
            wp_enqueue_script('mgm-jquery-form', MGM_ASSETS_URL . 'js/jquery/jquery.form.js');
            // custom scripts
            wp_enqueue_script('mgm-helpers', MGM_ASSETS_URL . 'js/helpers.js');
            wp_enqueue_script('mgm-string', MGM_ASSETS_URL . 'js/string.js');
            wp_enqueue_script('mgm-jquery-helpers', MGM_ASSETS_URL . 'js/jquery/jquery.helpers.js');
            // helpers scripts
            wp_enqueue_script('mgm-jquery-ajaxupload', MGM_ASSETS_URL . 'js/jquery/jquery.ajaxfileupload.js');
            // ?? is used
            wp_enqueue_script('mgm-jquery-scrollto', MGM_ASSETS_URL . 'js/jquery/jquery.scrollTo-min.js');
            wp_enqueue_script('mgm-jquery-corner', MGM_ASSETS_URL . 'js/jquery/jquery.corner.js');
            // wp_enqueue_script('mgm-jquery-tools', MGM_ASSETS_URL . 'js/jquery/jquery.tools.min.js');
            // wp_enqueue_script('mgm-jquery-tools', MGM_ASSETS_URL . 'js/jquery/messi/messi.min.js');
            wp_enqueue_script('mgm-nicedit', MGM_ASSETS_URL . 'js/nicedit/nicedit.js');
            wp_enqueue_script('mgm-checkboxtree', MGM_ASSETS_URL . 'js/jquery/jquery.tree.js');
            wp_enqueue_script('mgm-excanvas-min', MGM_ASSETS_URL . 'js/flot/excanvas.min.js');
            wp_enqueue_script('mgm-jquery-flot', MGM_ASSETS_URL . 'js/flot/jquery.flot.js');
            // ui css
            wp_enqueue_style('mgm-ui-css', MGM_ASSETS_URL . 'css/default/mgm/jquery.ui.css');
            // styles
            wp_enqueue_style('mgm-adminui-css', MGM_ASSETS_URL . 'css/admin/mgm.adminui.css');
            // wp 3.3+ fix
            if (mgm_compare_wp_version('3.3', '>')) {
                wp_enqueue_style('mgm-adminui-wp3fix-css', MGM_ASSETS_URL . 'css/admin/mgm.adminui.wp3fix.css');
            }
            // other
            // wp_enqueue_style('mgm-admin-overlay-css', MGM_ASSETS_URL . 'css/admin/jquery.overlay.css' );
            // wp_enqueue_style('mgm-admin-overlay-css', MGM_ASSETS_URL . 'css/admin/messi/messi.min.css' );
            wp_enqueue_style('mgm-admin-checkboxtree-css', MGM_ASSETS_URL . 'css/admin/jquery.tree.css');
            break;
        case 'widgets':
            // styles
            wp_enqueue_style('mgm-widgets-css', MGM_ASSETS_URL . 'css/admin/mgm.widgets.css');
            break;
        case 'profile_page_mgm/profile':
        case 'profile_page_mgm/membership/content':
            // styles
            wp_enqueue_style('mgm-adminui-css', MGM_ASSETS_URL . 'css/admin/mgm.adminui.css');
            wp_enqueue_style('mgm-pages-css', MGM_ASSETS_URL . 'css/default/mgm.pages.css');
            break;
    }
}
/**
 * check wordpress version support
 */
function mgm_check_wp_version_support($key = NULL)
{
    // return
    return mgm_compare_wp_version('3.1.0', '>=') ? true : false;
    # ((version_compare($GLOBALS['wp_version'], '3.1.0')) >= 0) ? true : false;
}
/**
 * $wpdb escape compatibility
 */
function mgm_escape($value = NULL)
{
    global $wpdb;
    //check
    if (mgm_compare_wp_version('3.6', '>=')) {
        return $wpdb->_escape($value);
    } else {
        // older
        return $wpdb->escape($value);
    }
}
/**
 * Custom user profile form
 */
function mgm_user_profile_form($user_id = NULL, $temp_edit = false, $args = array())
{
    global $wpdb;
    // get mgm_system
    $system_obj = mgm_get_class('system');
    // current user
    $current_user = $user_id ? get_userdata($user_id) : wp_get_current_user();
    // current or voew
    if ($current_user->ID) {
        // current
        $user = mgm_get_userdata($current_user->ID);
    } else {
        // query string
        $user = mgm_get_user_from_querystring();
    }
    // if no user
    if (!isset($user) || !$user->ID || is_super_admin($user->ID)) {
        return mgm_user_login_form();
        exit;
    }
    // mgm member
    $member = mgm_get_member($user->ID);
    // edit mode, on for current user
    $edit_mode = $current_user->ID == $user->ID ? true : false;
    $temp = 0;
    // form action
    $form_action = get_permalink();
    // reset
    if ($form_action == null) {
        $form_action = mgm_get_current_url();
        $form_action = str_replace(array('&updated=true', '?updated=true'), '', $form_action);
    }
    //init - issue #1573
    $show_membership_fields_arr = array();
    if (isset($args['membership']) && !empty($args['membership'])) {
        // membership
        $membership = $args['membership'];
        // get active custom fields on register
        $cf_profile_by_membership_types = mgm_get_class('member_custom_fields')->get_fields_where(array('attributes' => array('profile_by_membership_types' => true)));
        //check
        if (!empty($cf_profile_by_membership_types)) {
            //loop
            foreach ($cf_profile_by_membership_types as $cf_profile_by_membership_type) {
                //membership_type
                $membership_types_string = isset($cf_profile_by_membership_type['attributes']['profile_membership_types_field_alias']) ? $cf_profile_by_membership_type['attributes']['profile_membership_types_field_alias'] : null;
                //check
                if (preg_match('/\\b' . $membership . '\\b/', $membership_types_string) && $membership_types_string != null) {
                    $show_fields_arr[] = $cf_profile_by_membership_type['name'];
                    $show_membership_fields_arr[] = $cf_profile_by_membership_type;
                    if ($cf_profile_by_membership_type['name'] == 'password') {
                        foreach ($cf_profile_by_membership_types as $cf_profile_by_membership) {
                            if ($cf_profile_by_membership['name'] == 'password_conf') {
                                $show_membership_fields_arr[] = $cf_profile_by_membership;
                            }
                        }
                    }
                }
            }
        }
    }
    // get default fields
    $profile_fields = mgm_get_config('default_profile_fields', array());
    // get active custom fields on profile page
    $cf_profile_page = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_profile' => true)));
    $cf_noton_profile = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_profile' => false)));
    //merge - issue #1573
    if (isset($show_membership_fields_arr) && is_array($show_membership_fields_arr) && !empty($show_membership_fields_arr)) {
        $cf_profile_page = array_merge($cf_profile_page, $show_membership_fields_arr);
        $cf_noton_profile = array_merge($cf_noton_profile, $show_membership_fields_arr);
    }
    $error_html = '';
    //issue #867
    $css_group = mgm_get_css_group();
    if ($css_group != 'none') {
        // error_html
        $error_html .= '<link rel="stylesheet" href="' . MGM_ASSETS_URL . 'css/' . $css_group . '/mgm.messages.css' . '" type="text/css" media="all" />';
    }
    // update
    if ($edit_mode) {
        // updated
        if (isset($_POST['method']) && $_POST['method'] == 'update_user') {
            // check security before processing form
            if (!wp_verify_nonce(mgm_post_var('_mgmnonce_user_profile'), 'user_profile')) {
                mgm_security_error('user_profile');
            }
            // user lib
            if (mgm_compare_wp_version('3.1', '<')) {
                // only before 3.1
                require_once ABSPATH . WPINC . '/registration.php';
            }
            // callback
            do_action('personal_options_update', $current_user->ID);
            // not multisite, duplicate email allowed ?
            if (!is_multisite()) {
                // save
                $errors = mgm_user_profile_update($current_user->ID);
            } else {
                // multi site
                // get user
                $user = get_userdata($current_user->ID);
                // update here:
                // Update the email address, if present. duplicate check
                if ($user->user_login && isset($_POST['user_email']) && is_email($_POST['user_email']) && $wpdb->get_var($wpdb->prepare("SELECT user_login FROM {$wpdb->signups} WHERE user_login = %s", $user->user_login))) {
                    $wpdb->query($wpdb->prepare("UPDATE {$wpdb->signups} SET user_email = %s WHERE user_login = %s", $_POST['user_email'], $user->user_login));
                }
                // edit
                if (!isset($errors) || isset($errors) && is_object($errors) && false == $errors->get_error_codes()) {
                    $errors = mgm_user_profile_update($current_user->ID);
                }
            }
            // trap erros
            if (!is_wp_error($errors)) {
                // redirect
                mgm_redirect(add_query_arg(array('updated' => 'true'), $form_action));
            }
            // errors
            if (isset($errors) && !is_numeric($errors)) {
                // get error
                $error_html .= mgm_set_errors($errors, true);
            }
        }
    }
    // updated
    if ($edit_mode && isset($_GET['updated'])) {
        $error_html .= '<div class="mgm_message_success">';
        $message = apply_filters('mgm_profile_edit_message', __('User updated.', 'mgm'));
        $error_html .= '<div><strong>' . $message . '</strong></div></div>';
    }
    // 	get row row template
    $form_row_template = $system_obj->get_template('profile_form_row_template');
    // get template row filter, mgm_profile_form_row_template for edit, mgm_profile_form_row_template_view for public view
    $form_row_template = apply_filters('mgm_profile_form_row_template' . (!$edit_mode ? '_view' : ''), $form_row_template);
    $cf_order = array();
    foreach ($cf_profile_page as $fld) {
        $cf_order[] = array('field' => $fld['name']);
    }
    // auto generate form template
    // form_template
    $form_template = '';
    // captured
    $fields_captured = array();
    // get field_groups
    $field_groups = mgm_get_config('profile_field_groups', array());
    // loop groups
    foreach ($field_groups as $group => $group_fields) {
        if ($group == 'Photo') {
            $photo_exists = false;
            foreach ($cf_profile_page as $photo) {
                if ($photo['name'] == 'photo') {
                    $photo_exists = true;
                    break;
                }
            }
            if (!$photo_exists) {
                continue;
            }
        }
        $fields_with_order = array();
        //issue #1197
        $css_title = function_exists('mb_strtolower') ? @mb_strtolower($group) : strtolower($group);
        $css_title = str_replace(' ', '_', $css_title);
        // group
        // PREV CODE
        $form_template .= sprintf('<span class="profile_group_%s">%s</span>', $css_title, $group);
        // loop to create form template
        foreach ($group_fields as $group_field) {
            // skip password
            //if(!$edit_mode && $group_field == 'password') continue;
            if (!$edit_mode && in_array($group_field, array('password', 'password_conf'))) {
                continue;
            }
            // set not found
            $captured = false;
            // first check if in custom fields
            foreach ($cf_profile_page as $field) {
                // skip password in non edit mode
                if ($field['name'] == $group_field) {
                    // set found
                    $captured = true;
                    // skip password
                    //if(!$edit_mode && $field['name'] == 'password') continue;
                    if (!$edit_mode && in_array($field['name'], array('password', 'password_conf'))) {
                        continue;
                    }
                    // store for no repeat
                    $fields_captured[] = $field['name'];
                    // field wrapper
                    $wrapper_ph = sprintf('[user_field_wrapper_%s]', $field['name']);
                    // field label
                    $label_ph = sprintf('[user_field_label_%s]', $field['name']);
                    // field/html element
                    $element_ph = sprintf('[user_field_element_%s]', $field['name']);
                    // set element name
                    // PREV CODE
                    //$form_template .= str_replace(array('[user_field_wrapper]','[user_field_label]','[user_field_element]'),array($wrapper_ph,$label_ph,$element_ph),$form_row_template);
                    // Issue #1149
                    foreach ($cf_order as $index => $cfo) {
                        if ($cfo['field'] == $field['name']) {
                            $fields_with_order[$index] = str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wrapper_ph, $label_ph, $element_ph), $form_row_template);
                            break;
                        }
                    }
                    // break;
                    break;
                }
            }
            // if not captured
            if (!$captured) {
                $continue = false;
                foreach ($cf_noton_profile as $cffield) {
                    if ($cffield['name'] == $group_field) {
                        $continue = true;
                        break;
                    }
                }
                // break;
                if ($continue) {
                    continue;
                }
                // check set
                if (!isset($profile_fields[$group_field]['name'])) {
                    continue;
                }
                // field wrapper
                $wrapper_ph = sprintf('[user_field_wrapper_%s]', $profile_fields[$group_field]['name']);
                // field label
                $label_ph = sprintf('[user_field_label_%s]', $profile_fields[$group_field]['name']);
                // field/html element
                $element_ph = sprintf('[user_field_element_%s]', $profile_fields[$group_field]['name']);
                // set element name
                // PREV CODE
                // $form_template .= str_replace(array('[user_field_wrapper]','[user_field_label]','[user_field_element]'),array($wrapper_ph,$label_ph,$element_ph),$form_row_template);
                // Issue #1149
                $field_added = false;
                foreach ($cf_order as $index => $cfo) {
                    if ($cfo['field'] == $group_field) {
                        $fields_with_order[$index] = str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wrapper_ph, $label_ph, $element_ph), $form_row_template);
                        $field_added = true;
                        break;
                    }
                }
                if (!$field_added) {
                    /*$fields_with_order[$index+1] = str_replace(array('[user_field_wrapper]','[user_field_label]','[user_field_element]'),array($wrapper_ph,$label_ph,$element_ph),$form_row_template);*/
                    // default profile instalation fields - issue #1207
                    if (in_array($group_field, array('username', 'email', 'password', 'password', 'password_conf'))) {
                        $fields_with_order[$temp++] = str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wrapper_ph, $label_ph, $element_ph), $form_row_template);
                    }
                }
            }
        }
        // Issue #1149
        // Process custom field form_template with order
        if (!empty($fields_with_order)) {
            // Sort by key
            ksort($fields_with_order);
            // Loop through fields and attach html
            foreach ($fields_with_order as $fworder) {
                $form_template .= $fworder;
            }
        }
    }
    // other
    $other_header = false;
    // loop to create form template
    foreach ($cf_profile_page as $field) {
        // skip password in non edit mode
        //if(!$edit_mode && $field['name'] == 'password') continue;
        if (!$edit_mode && in_array($field['name'], array('password', 'password_conf'))) {
            continue;
        }
        // skip captured
        if (in_array($field['name'], $fields_captured)) {
            continue;
        }
        // header
        if (!$other_header) {
            // rest
            $form_template .= sprintf('<span class="profile_group_others">%s</span>', __('Others', 'mgm'));
            $other_header = true;
        }
        // field wrapper
        $wrapper_ph = sprintf('[user_field_wrapper_%s]', $field['name']);
        // field label
        $label_ph = sprintf('[user_field_label_%s]', $field['name']);
        // field/html element
        $element_ph = sprintf('[user_field_element_%s]', $field['name']);
        // template for show_public_profile
        if ($field['name'] == 'show_public_profile') {
            // template
            $form_row_template_pf = $system_obj->get_template('register_form_row_autoresponder_template');
            // set element place holders
            $form_template .= str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wrapper_ph, $label_ph, $element_ph), $form_row_template_pf);
        } else {
            // set element name
            $form_template .= str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wrapper_ph, $label_ph, $element_ph), $form_row_template);
        }
    }
    // get template filter, mgm_profile_form_template for edit, mgm_profile_form_template_view for public view
    $form_template = apply_filters('mgm_profile_form_template' . (!$edit_mode ? '_view' : ''), $form_template);
    // now replace and create the fields
    $form_html = $form_template;
    // get mgm_form_fields generator
    $form_fields = new mgm_form_fields(array('wordpres_form' => false));
    $arr_images = array();
    // loop custom fields to replace form labels/elements
    foreach ($cf_profile_page as $field) {
        // skip password in non edit mode
        //if(!$edit_mode && $field['name'] == 'password') continue;
        if (!$edit_mode && in_array($field['name'], array('password', 'password_conf'))) {
            continue;
        }
        if ($edit_mode && $field['type'] == 'image') {
            if (!in_array($field['name'], $arr_images)) {
                $arr_images[] = $field['name'];
            }
        }
        // field wrapper
        $wrapper_ph = sprintf('[user_field_wrapper_%s]', $field['name']);
        // field label
        $label_ph = sprintf('[user_field_label_%s]', $field['name']);
        // field/html element
        $element_ph = sprintf('[user_field_element_%s]', $field['name']);
        // edit mode
        if ($edit_mode) {
            // for username
            if ($field['name'] == 'username') {
                //localazing the label  issue# 617
                $label_lcz = mgm_stripslashes_deep($field['label']);
                $label_lcz = __($label_lcz, 'mgm');
                $field['label'] = sprintf('%s (<em>%s</em>)', $label_lcz, __('Username not changeable', 'mgm'));
            } elseif ($field['name'] == 'password') {
                //localazing the label  issue# 617
                $label_lcz = mgm_stripslashes_deep($field['label']);
                $label_lcz = __($label_lcz, 'mgm');
                $field['label'] = sprintf('%s (<em>%s</em>)', $label_lcz, __('Leave blank if don\'t wish to update', 'mgm'));
            }
        } else {
            // for display_name
            if ($field['name'] == 'display_name') {
                $field['label'] = __('Display Name', 'mgm');
            }
        }
        // replace wrapper
        $form_html = str_replace($wrapper_ph, $field['name'] . '_box', $form_html);
        //localazing the label  issue# 617
        $label_lcz = mgm_stripslashes_deep($field['label']);
        $label_lcz = __($label_lcz, 'mgm');
        // replace label(hidden) - issue #1050
        $form_html = str_replace($label_ph, $field['attributes']['hide_label'] ? '' : mgm_stripslashes_deep($field['label']), $form_html);
        // replace label
        $form_html = str_replace($label_ph, $label_lcz, $form_html);
        // selected value
        if (isset($profile_fields[$field['name']]) && isset($user->{$profile_fields}[$field['name']]['name'])) {
            // wp alias'
            // value
            $value = $user->{$profile_fields}[$field['name']]['name'];
            // birthdate
            if ($field['name'] == 'birthdate') {
                // convert saved date to input field format
                $value = mgm_get_datepicker_format('date', $value);
            } elseif ($field['type'] == 'checkbox') {
                //$options = preg_split('/[;,]/', $field['options']);
                //$value  = preg_split('/[;,\s]/', $value);
                //issue #1070
                $value = @unserialize($value);
                // pass " " as value to prevent the default value getting selected, if no option is selected
                $value = empty($value) ? " " : $value;
            }
        } else {
            if (isset($member->custom_fields->{$field}['name'])) {
                // custom field
                // value
                $value = $member->custom_fields->{$field}['name'];
                // birthdate
                if ($field['name'] == 'birthdate') {
                    // convert saved date to input field format
                    $value = mgm_get_datepicker_format('date', $value);
                } elseif ($field['type'] == 'checkbox') {
                    //$options = preg_split('/[;,]/', $field['options']);
                    //$value  = preg_split('/[;,\s]/', $value);
                    //issue #1070
                    $value = @unserialize($value);
                    // pass " " as value to prevent the default value getting selected, if no option is selected
                    $value = empty($value) ? " " : $value;
                }
                //issue #1484
                if ($field['name'] == 'show_public_profile' && $field['type'] == 'checkbox') {
                    $value = $member->custom_fields->{$field}['name'];
                }
            } else {
                if (isset($user->{$field}['name'])) {
                    // object var
                    // value
                    $value = $user->{$field}['name'];
                } else {
                    // none
                    // default
                    $value = '';
                }
            }
        }
        // dont set value for password
        if (in_array($field['name'], array('password', 'password_conf'))) {
            $value = '';
        }
        // disable username
        if ($field['name'] == 'username') {
            $field['attributes']['readonly'] = true;
        }
        // nickname
        if ($field['name'] == 'nickname') {
            $field['attributes']['required'] = true;
        }
        // edit mode
        if ($edit_mode) {
            if ($field['name'] == 'show_public_profile') {
                //echo "xxx".$form_fields->get_field_element($field,'mgm_profile_field',$value);
            }
            // replace element
            $form_html = str_replace($element_ph, $form_fields->get_field_element($field, 'mgm_profile_field', $value), $form_html);
        } else {
            // view
            // country
            if ($field['name'] == 'country') {
                $value = mgm_country_from_code($value);
            } elseif ($field['name'] == 'photo' && !empty($value)) {
                $value = sprintf('<img src="%s" alt="%s" >', $value, basename($value));
            }
            // replace element
            $form_html = str_replace($element_ph, $value, $form_html);
        }
    }
    // loop default fields to replace form elements
    foreach ($profile_fields as $field_key => $field) {
        // skip password in non edit mode
        //if(!$edit_mode && $field['name'] == 'user_password') continue;
        if (!$edit_mode && in_array($field['name'], array('user_password', 'user_password_conf'))) {
            continue;
        }
        $continue = false;
        foreach ($cf_noton_profile as $cffield) {
            if ($cffield['name'] == $field['name']) {
                $continue = true;
                break;
            }
        }
        if ($continue) {
            continue;
        }
        // field wrapper
        $wrapper_ph = sprintf('[user_field_wrapper_%s]', $field['name']);
        // field label
        $label_ph = sprintf('[user_field_label_%s]', $field['name']);
        // field/html element
        $element_ph = sprintf('[user_field_element_%s]', $field['name']);
        // edit mode
        if ($edit_mode) {
            // for username
            if ($field['name'] == 'user_login') {
                //localazing the label  issue# 617
                $label_lcz = mgm_stripslashes_deep($field['label']);
                $label_lcz = __($label_lcz, 'mgm');
                $field['label'] = sprintf('%s (<em>%s</em>)', $label_lcz, __('Username not changeable', 'mgm'));
            } elseif ($field['name'] == 'user_password') {
                //localazing the label  issue# 617
                $label_lcz = mgm_stripslashes_deep($field['label']);
                $label_lcz = __($label_lcz, 'mgm');
                $field['label'] = sprintf('%s (<em>%s</em>)', $label_lcz, __('Leave blank if don\'t wish to update', 'mgm'));
            }
        } else {
            // for display_name
            if ($field['name'] == 'display_name') {
                $field['label'] = __('Display Name', 'mgm');
            }
        }
        // replace wrapper
        $form_html = str_replace($wrapper_ph, $field['name'] . '_box', $form_html);
        //localazing the label  issue# 617
        $label_lcz = mgm_stripslashes_deep($field['label']);
        $label_lcz = __($label_lcz, 'mgm');
        // replace label
        $form_html = str_replace($label_ph, $label_lcz, $form_html);
        // selected value
        if (isset($user->{$field}['name'])) {
            // wp alias
            $value = $user->{$field}['name'];
        } else {
            if (isset($member->custom_fields->{$field_key})) {
                // custom field
                $value = $member->custom_fields->{$field_key};
            } else {
                // none
                $value = '';
            }
        }
        // dont set value for password
        //if($field['name'] == 'user_password') $value = '';
        if (in_array($field['name'], array('user_password', 'user_password_conf'))) {
            $value = '';
        }
        // edit mode
        if ($edit_mode) {
            // replace element
            $form_html = str_replace($element_ph, $form_fields->get_field_element($field, 'mgm_profile_field', $value), $form_html);
        } else {
            // country
            if ($field_key == 'country') {
                $value = mgm_country_from_code($value);
            }
            // set
            $form_html = str_replace($element_ph, $value, $form_html);
        }
    }
    // attach scripts
    $form_html .= mgm_attach_scripts(true, array());
    // range
    $yearRange = mgm_get_calendar_year_range();
    // append script
    $form_html .= '<script language="javascript">jQuery(document).ready(function(){try{mgm_date_picker(".mgm_date",false,{yearRange:"' . $yearRange . '", dateFormat: "' . mgm_get_datepicker_format() . '"});}catch(x){}});</script>';
    //include scripts for image upload:
    if (!empty($arr_images)) {
        $form_html .= mgm_upload_script_js('profileform', $arr_images);
    }
    // buttun
    $button_html = '';
    // button on edit
    if ($edit_mode && !$temp_edit) {
        // default
        $button_html = '<div><input class="button mgm-profile-button" type="submit" name="wp-submit" id="wp-submit" value="' . __('Update', 'mgm') . '" /></div>';
        // apply button filter
        $button_html = apply_filters('mgm_profile_form_button', $button_html);
    }
    //profile by membership - issue #1573
    if (isset($args['membership']) && !empty($args['membership'])) {
        // hidden
        $button_html .= sprintf('<input type="hidden" name="membership" value="%s">', $args['membership']);
    }
    // hidden
    $button_html .= '<input type="hidden" name="method" value="update_user">';
    // nonce
    $button_html .= wp_nonce_field('user_profile', '_mgmnonce_user_profile', true, false);
    // temp
    if (!$temp_edit) {
        // open
        $form_open = sprintf('<form class="mgm_form" name="profileform" id="profileform" action="%s" method="post">', $form_action);
        $form_close = '</form>';
    } else {
        $form_open = $form_close = '';
    }
    // output form
    $html = sprintf('<div class="mgm_prifile_form">%s %s %s %s %s</div>', $error_html, $form_open, $form_html, $button_html, $form_close);
    //issue #1113
    $html = mgm_stripslashes_deep($html);
    // filter
    $html = apply_filters('mgm_user_profile_form_html', $html, $current_user);
    //issue #1635
    $user_profile_html = '<div class="mgm_user_profile_container">' . $html . '</div>';
    // return
    return $user_profile_html;
}