/**
 * get payment processing page title
 *
 * @param void
 * @return string
 * @since 1.5
 */
function mgm_get_payment_processing_page_title()
{
    // title
    $title = __('Processing Payment', 'mgm');
    // get module
    if ($module = mgm_get_var('module', '', true)) {
        // module
        if ($module_obj = mgm_get_module($module, 'payment')) {
            // onsite with credit cards, @todo add payflow iframe onsite
            if (!$module_obj->is_hosted_payment()) {
                $title = __('Enter Credit Card Details', 'mgm');
            }
        }
    }
    // return
    return apply_filters('mgm_payment_processing_page_title', mgm_stripslashes_deep($title));
}
/**
 * parse shortcodes
 *
 * @param array @args
 * @param string @content
 * @param string @tag
 * @return string $content
 */
function mgm_shortcode_parse($args, $content, $tag)
{
    // current_user
    $current_user = wp_get_current_user();
    // system
    $system_obj = mgm_get_class('system');
    // issue#: 859
    // add <p> to the beggining and </p> to the end of content
    // as WP pass $content with incomplete p tags
    $content = '<p>' . $content . '</p>';
    // remove any '<p></p> found
    $content = str_replace(array('<p></p>'), '', $content);
    // @todo test with force_balance_tags();
    // tag block
    switch ($tag) {
        case 'private':
            // [private] protected content [/private]
            if (mgm_protect_content() || mgm_post_is_purchasable()) {
                //issue #1687
                if (mgm_content_post_access_delay($args)) {
                    $content = mgm_replace_postdealy_content($content);
                } else {
                    $content = mgm_replace_content_tags($tag, $content, $args);
                }
            }
            break;
        case 'private_or':
            // [private_or#member] protected content [/private_or]
            // [private_or membership_type="member"] protected content [/private_or]
            $membership_type = isset($args['membership_type']) ? $args['membership_type'] : str_replace('#', '', mgm_array_shift($args));
            // match
            if ($membership_type) {
                $content = mgm_replace_content_tags($tag, $content, $membership_type);
            }
            break;
        case 'private_and':
            // [private_and#member] protected content [/private_and]
            // [private_and membership_type="member"] protected content [/private_and]
            $membership_type = isset($args['membership_type']) ? $args['membership_type'] : str_replace('#', '', mgm_array_shift($args));
            // match
            if ($membership_type) {
                $content = mgm_replace_content_tags($tag, $content, $membership_type);
            }
            break;
        case 'payperpost_pack':
            // [payperpost_pack#1] : 1 = pack_id, packs to be created in MGM -> PayPerPost -> Post Packs, use the id here
            // [payperpost_pack id=1] : 1 = pack_id
            $pack_id = isset($args['id']) ? $args['id'] : str_replace('#', '', mgm_array_shift($args));
            // match
            if ($pack_id) {
                $content = mgm_replace_content_tags($tag, $content, $pack_id);
            }
            break;
        case 'payperpost':
            // [payperpost#1] : 1 = post_id
            // [payperpost id=1] : 1 = post_id
            $pack_id = isset($args['id']) ? $args['id'] : str_replace('#', '', mgm_array_shift($args));
            // match
            if ($pack_id) {
                $content = mgm_replace_content_tags($tag, $content, $pack_id);
            }
            break;
        case 'subscription_packs':
            // subscription packs / payment gateways
            $content = mgm_sidebar_register_links($current_user->user_login, true, 'page');
            // @todo test
            break;
        case 'user_unsubscribe':
            // user unsubscribe
            $content = mgm_user_unsubscribe_info(null, $args);
            // view current user
            break;
        case 'user_other_subscriptions':
            // other subscriptions
            $content = mgm_user_other_subscriptions_info();
            break;
        case 'membership_details':
            // user subscription
            $content = mgm_membership_details();
            // view current user
            break;
        case 'user_upgrade':
            // user upgrade membership
            $content = mgm_get_upgrade_buttons($args);
            break;
        case 'user_purchase_another_membership':
            // purchase another subscription
            $content = mgm_get_purchase_another_subscription_button($args);
            break;
        case 'user_subscribe':
        case 'user_register':
            // named
            if ($method = mgm_get_var('method', '', true)) {
                // method
                switch ($method) {
                    case 'login':
                        $content = mgm_user_login_form(false);
                        break;
                    case 'lostpassword':
                        $content = mgm_user_lostpassword_form(false);
                        break;
                    default:
                        if (preg_match('/^payment/', $method)) {
                            $content = mgm_transactions_page($args);
                        }
                        break;
                }
            } else {
                $content = mgm_user_register_form($args);
            }
            break;
        case 'user_profile':
            // user profile
            $content = mgm_user_profile_form(NULL, false, $args);
            // view
            break;
        case 'user_public_profile':
            // user profile
            $content = mgm_user_public_profile($args);
            // view
            break;
        case 'transactions':
            // user payments/transactions
            $content = mgm_transactions_page($args);
            break;
        case 'user_contents_by_membership':
            // user contents by membership level
            $content = mgm_membership_content_page();
            break;
        case 'user_lostpassword':
            // user lost password form
            $content = mgm_user_lostpassword_form(false);
            break;
        case 'user_login':
            // user login form
            $content = mgm_user_login_form(false);
            break;
        case 'user_field':
            // user field
            $content = __('Experimental', 'mgm');
            break;
        case 'membership_contents':
            // membership contents
            $content = mgm_membership_contents();
            // view current user
            break;
        case 'logout_link':
            // custom logout link
            // [logout_link#Logout]
            // [logout_link label="Logout"]
            $label = isset($args['label']) ? $args['label'] : str_replace('#', '', mgm_array_shift($args));
            // match
            $content = mgm_logout_link($label);
            break;
        case 'membership_extend_link':
            //INCOMPLETE
            // membership extend link
            // [membership_extend_link#Extend]
            // [membership_extend_link label="Extend"]
            $label = isset($args['label']) ? $args['label'] : str_replace('#', '', mgm_array_shift($args));
            // match
            $content = mgm_membership_extend_link($label);
            break;
        case 'download_error':
            // content
            $content = isset($_GET['error_code']) ? mgm_download_error($_GET['error_code']) : '';
            break;
        case 'user_payment_history':
            // content
            $content = mgm_user_payment_history();
            // view current user
            break;
        case 'user_list':
            // content
            $content = mgm_generate_member_list($args);
            break;
        case 'user_facebook_login':
            // content
            $content = mgm_generate_facebook_login();
            break;
        case 'user_facebook_registration':
            // content
            $content = mgm_generate_facebook_registration();
            break;
        case 'user_purchased_contents':
            // content
            $content = mgm_generate_purchased_contents();
            break;
        case 'user_purchasable_contents':
            // content
            $content = mgm_generate_purchasable_contents();
            break;
            /*case 'addon':
            			// content
             			$content = mgm_purchase_addons($args);
            		break;*/
        /*case 'addon':
        			// content
         			$content = mgm_purchase_addons($args);
        		break;*/
        default:
            // default, which are not shortcode but content tags
            $args = str_replace('#', '', mgm_array_shift($args));
            // match
            $content = mgm_replace_content_tags($tag, $content, $args);
            break;
    }
    // return
    return $content;
}
 function process_return()
 {
     // log
     // mgm_log('process_return free REQUEST : '.print_r($_REQUEST,true));
     //mgm_pr($_REQUEST); die;
     // only save once success, there may be multiple try
     if (isset($_REQUEST['custom']) && !empty($_REQUEST['custom'])) {
         // id
         $transid = mgm_decode_id(mgm_get_var('transid', '', true));
         // process
         $this->process_notify($transid);
         // query arg
         $query_arg = array('status' => 'success');
         // is a post redirect?
         $post_redirect = $this->_get_post_redirect($_REQUEST['custom']);
         // set post redirect
         if ($post_redirect !== false) {
             $query_arg['post_redirect'] = $post_redirect;
         }
         // log
         mgm_log($query_arg, __FUNCTION__);
         // login autoredirection
         if (is_numeric($transid)) {
             // update transaction
             mgm_update_transaction_status($transid, MGM_STATUS_ACTIVE, '');
             // is a register redirect?
             $register_redirect = $this->_auto_login($transid);
             // set register redirect
             if ($register_redirect !== false) {
                 $query_arg['register_redirect'] = $register_redirect;
             }
         }
         // log
         mgm_log($query_arg, __FUNCTION__);
         // redirect
         mgm_redirect(add_query_arg($query_arg, $this->_get_thankyou_url()));
     } else {
         // teat as error
         $errors = 'error in processing your request';
         // redirect
         mgm_redirect(add_query_arg(array('status' => 'error', 'errors' => $errors), $this->_get_thankyou_url()));
     }
 }
/**
 * 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;
}
/**
 * check if there is any redirect condition on post
 *
 * @param object system
 * @return boolean redirect status
 * @since 1.0
 */
function mgm_check_redirect_condition($system_obj = NULL)
{
    // system
    if (!$system_obj) {
        $system_obj = mgm_get_class('system');
    }
    // init
    $return = false;
    $current_url = mgm_current_url();
    $admin_membership_page = mgm_get_var('page', '', true) == 'mgm/membership/content' ? true : false;
    // check page
    if (!$admin_membership_page) {
        // there is redirect setting
        $no_access_redirect_loggedin_users = trim($system_obj->get_setting('no_access_redirect_loggedin_users'));
        $no_access_redirect_loggedout_users = trim($system_obj->get_setting('no_access_redirect_loggedout_users'));
        $redirect_on_homepage = bool_from_yn($system_obj->get_setting('redirect_on_homepage'));
        // check
        if (!empty($no_access_redirect_loggedin_users) || !empty($no_access_redirect_loggedout_users)) {
            // start as redirect
            $return = true;
            // enable
            // user logged in
            if (is_user_logged_in()) {
                // disable redirect for logged in user if there is no url set
                if (empty($no_access_redirect_loggedin_users)) {
                    $return = false;
                    // disable
                }
            } else {
                // user not logged in,
                // disable redirect for logged out user if there is no url set
                if (empty($no_access_redirect_loggedout_users)) {
                    $return = false;
                    // disable
                }
            }
            // redirect on home
            if (is_home() && $redirect_on_homepage == TRUE) {
                $return = true;
                // enable
            }
            // check token request or feed, feed will not use redirect feature
            if (is_feed() || mgm_get_var('token', '', true) != '' && mgm_use_rss_token()) {
                $return = false;
                // disable
            } elseif (!$return && !(is_single() || is_page())) {
                $return = true;
                // enable
            }
        }
    }
    // return
    return $return;
}
/**
 * custom user login form, output by [user_register] shortcode
 *
 * @param bool $use_default_links
 * @param string $html
 */
function mgm_user_login_form($use_default_links = true)
{
    //fb logins i.e. facebook connect errors
    global $fb_errors;
    // hide from logged in user
    if (is_user_logged_in()) {
        // not logout call to self
        if (mgm_get_var('action', '', true) != 'logout') {
            return __('You are already logged in!', 'mgm');
        }
    }
    // check auto login
    if ($html = mgm_try_auto_login()) {
        return $html;
    }
    // init errors
    $fb_errors = $errors = null;
    // system
    $system_obj = mgm_get_class('system');
    // process hooked logins i.e. facebook connect
    do_action('mgm_user_login_pre_process');
    // check security before processing form
    if (isset($_POST['log'])) {
        if (!wp_verify_nonce(mgm_post_var('_mgmnonce_user_login'), 'user_login')) {
            mgm_security_error('user_login');
        }
    }
    // issue #1203
    if (empty($fb_errors)) {
        $errors = mgm_process_user_login();
    } else {
        $errors = $fb_errors;
    }
    // action
    $form_action = mgm_get_custom_url('login');
    // init
    $user_login = $user_pwd = $html = '';
    //check logged in cookie:
    $rememberme = !empty($_POST['rememberme']);
    $interim_login = isset($_REQUEST['interim-login']);
    // login
    if (isset($_POST['log'])) {
        $user_login = esc_attr(stripslashes($_POST['log']));
        // issue# 525
    } elseif ($cookie_userid = wp_validate_auth_cookie('', 'logged_in')) {
        //check a valid logged cookie exists
        // cookie
        $arr_loggedin_cookie = wp_parse_auth_cookie('', 'logged_in');
        // get mgm_member
        $member = mgm_get_member($cookie_userid);
        // mark checked
        $rememberme = true;
        // get login from cookie
        $user_login = esc_attr(stripslashes($arr_loggedin_cookie['username']));
        // password from member object
        // issue#: 672
        $user_pwd = mgm_decrypt_password($member->user_password, $cookie_userid);
    }
    // redirect
    $redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : '';
    // start html
    $html = '';
    // set error !
    if (isset($errors) && is_object($errors)) {
        // get error
        if ($error_html = mgm_set_errors($errors, true)) {
            $html .= $error_html;
        }
    }
    // check
    if (bool_from_yn($system_obj->get_setting('enable_email_as_username'))) {
        $email_username_label = __('Email', 'mgm');
    } else {
        $email_username_label = __('Username', 'mgm');
    }
    // start form
    $html .= '<form class="mgm_form" name="loginform" id="loginform" action="' . $form_action . '" method="post">
				<div>
					<label>' . $email_username_label . '<br />
					<input type="text" name="log" id="user_login" class="input" value="' . esc_attr($user_login) . '" size="40" tabindex="10" /></label>
				</div>
				<div>
					<label>' . __('Password', 'mgm') . '<br />
					<input type="password" name="pwd" id="user_pass" class="input" value="' . esc_attr($user_pwd) . '" size="40" tabindex="20" /></label>
				</div>';
    //Issue #782
    $html .= mgm_get_captcha_field('mgm_login_field');
    // login form, fetch as return
    // do_action('login_form');
    // custom
    $html .= apply_filters('mgm_login_form', $html);
    // forget
    $html .= '<div class="forgetmenot">
				 <label>
					<input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" ' . checked($rememberme, true, false) . '  /> ' . __('Remember Me', 'mgm') . '
				 </label>
			  </div>';
    // buttons
    $buttons = array(sprintf('<input class="button mgm-login-button" type="submit" name="wp-submit" id="wp-submit" value="%s" tabindex="100" />', __('Log In', 'mgm')));
    // apply filters
    $buttons_s = implode(apply_filters('mgm_login_form_buttons_sep', ' &nbsp; '), apply_filters('mgm_login_form_buttons', $buttons));
    // append
    $html .= sprintf('<div class="login-page-buttons">%s</div>', $buttons_s);
    if ($system_obj->get_setting('disable_testcookie') == 'N') {
        // hiddens
        $html .= '<input type="hidden" name="testcookie" value="1" /> ';
    }
    // intrim
    if ($interim_login) {
        $html .= '<input type="hidden" name="interim-login" value="1" />';
    } else {
        $html .= '<input type="hidden" name="redirect_to" value="' . esc_attr($redirect_to) . '" />';
    }
    // nonce
    $html .= wp_nonce_field('user_login', '_mgmnonce_user_login', true, false);
    // end form
    $html .= '</form>';
    // after links
    $links = array();
    // interim_login
    if (!$interim_login) {
        // check mail will not have any
        if (!isset($_GET['checkemail']) || isset($_GET['checkemail']) && !in_array($_GET['checkemail'], array('confirm', 'newpass'))) {
            // register
            if (get_option('users_can_register')) {
                $links[] = sprintf('<a class="mgm-register-link" href="%s">%s</a>', mgm_get_custom_url('register'), __('Register', 'mgm'));
            }
            // lostpassword
            $links[] = sprintf('<a class="mgm-lostpassword-link" href="%s" title="%s">%s</a>', mgm_get_custom_url('lostpassword'), __('Password Lost and Found', 'mgm'), __('Lost your password?', 'mgm'));
        }
    }
    // apply filters
    $links_s = implode(apply_filters('mgm_login_form_after_links_sep', ' | '), apply_filters('mgm_login_form_after_links', $links));
    // appaend
    $html .= sprintf('<div class="login-page-links">%s</div>', $links_s);
    // scripts & styles --------------------
    // focus
    $focus = $user_login || $interim_login ? 'user_pass' : 'user_login';
    // script
    $script = 'function wp_attempt_focus(){setTimeout( function(){ try{ d = document.getElementById("' . $focus . '"); d.focus();} catch(e){}}, 200);}';
    // focus
    if (@(!$error)) {
        $script .= 'wp_attempt_focus();';
    }
    // script
    $script = sprintf('<script type="text/javascript">%s</script>', apply_filters('mgm_login_form_inline_script', $script));
    // scripts
    $html .= apply_filters('mgm_login_form_scripts', $script);
    // style
    $style = '.login-page-links, .login-page-buttons{margin-top:10px; clear:both}';
    // style
    $style = sprintf('<style type="text/css">%s</style>', apply_filters('mgm_login_form_inline_style', $style));
    // style
    $html .= apply_filters('mgm_login_form_styles', $style);
    // apply filters and return
    return apply_filters('mgm_login_form_html', $html);
}