/**
 * generate guest purchase post form 
 *
 * @param int post id
 * @return string html
 */
function mgm_guest_purchase_post_form($post_id)
{
    global $wpdb;
    // post
    $post =& get_post($post_id);
    // validate
    if (!$post->ID) {
        return __('Bad data', 'mgm');
    }
    // apply filter html
    $html = apply_filters('mgm_guest_purchase_post_form_pre_button_html', mgm_get_post_purchase_options($post));
    // return button
    return $html .= mgm_get_post_purchase_button($post->ID, false, true);
}
/**
 * custom register form
 *
 * @param array $args
 * @param bool $use_default_links
 * @return string $form
 */
function mgm_user_register_form($args = array(), $use_default_links = false)
{
    // hide from logged in user
    if (is_user_logged_in()) {
        // redirect
        return __('You are already logged in!', 'mgm');
    }
    // registration disabled
    if (!get_option('users_can_register')) {
        // redirect
        return __('User registration is currently not allowed.', 'mgm');
    }
    // get system
    $system_obj = mgm_get_class('system');
    // hide flag
    $hide_custom_fields = $system_obj->get_setting('hide_custom_fields');
    // init
    $cf_show_fields = array();
    // default_register_fields
    $register_fields = mgm_get_config('default_register_fields', array());
    // get active custom fields on register
    $cf_register_page = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true)));
    //issue #1573
    $membership_args_fields = "";
    if (isset($args['membership']) && !empty($args['membership'])) {
        //init
        $show_fields_arr = array();
        // membership
        $membership = $args['membership'];
        // get active custom fields on register
        $cf_register_by_membership_types = mgm_get_class('member_custom_fields')->get_fields_where(array('attributes' => array('register_by_membership_types' => true)));
        //check
        if (!empty($cf_register_by_membership_types)) {
            //loop
            foreach ($cf_register_by_membership_types as $cf_register_by_membership_type) {
                //membership_type
                $membership_types_string = isset($cf_register_by_membership_type['attributes']['register_membership_types_field_alias']) ? $cf_register_by_membership_type['attributes']['register_membership_types_field_alias'] : null;
                //check
                if (preg_match('/\\b' . $membership . '\\b/', $membership_types_string) && $membership_types_string != null) {
                    $show_fields_arr[] = $cf_register_by_membership_type['name'];
                }
            }
        }
        //filter if any empty values found check
        $show_fields_arr = array_filter($show_fields_arr);
        //check
        if (!empty($show_fields_arr)) {
            $membership_args_fields = implode(',', $show_fields_arr);
        }
    }
    // # 740
    // Show fields in short code to filter the registration form #Issue 740
    $args_fields = '';
    if (isset($args['show_fields']) && !empty($args['show_fields']) || isset($membership_args_fields) && !empty($membership_args_fields)) {
        $package = isset($args['package']) ? $args['package'] : null;
        $args_fields = isset($args['show_fields']) ? $args['show_fields'] : $membership_args_fields;
        if (!empty($args_fields)) {
            $cf_register_page = mgm_show_fields_result($args_fields, $cf_register_page, $package);
        }
    }
    // error_html
    $error_html = '';
    // save-------------------------------------------------
    if (isset($_POST['method']) && $_POST['method'] == 'create_user') {
        // check security before processing form
        if (!wp_verify_nonce(mgm_post_var('_mgmnonce_user_register'), 'user_register')) {
            mgm_security_error('user_register');
        }
        // load wp lib for register
        if (mgm_compare_wp_version('3.1', '<')) {
            // only before 3.1
            require_once ABSPATH . WPINC . '/registration.php';
        }
        // process hooked registers i.e. facebook connect
        do_action('mgm_user_register_pre_process');
        // init
        $user_login = $user_email = '';
        // loop to check
        foreach ($register_fields as $cfield => $wfield) {
            // set custom
            if (isset($_POST['mgm_register_field'][$cfield])) {
                // set from custom
                ${$wfield['name']} = $_POST['mgm_register_field'][$cfield];
            } else {
                if (isset($_POST[$wfield['name']])) {
                    // default field
                    ${$wfield['name']} = $_POST[$wfield['name']];
                } else {
                    // else
                    ${$wfield['name']} = '';
                }
            }
        }
        // user login
        if (empty($user_login)) {
            $user_login = mgm_generate_user_login($user_email);
        }
        //issue #1573
        if (!isset($args['show_fields']) && isset($args['membership'])) {
            $args['show_fields'] = $_REQUEST['show_fields'];
        }
        // get error
        $errors = mgm_register_new_user($user_login, $user_email, isset($args['show_fields']) ? $args['show_fields'] : NULL);
        // no error
        if (!is_wp_error($errors)) {
            // get redirect
            $redirect = mgm_get_custom_url('login', $use_default_links, array('checkemail' => 'registered'));
            // check default
            $redirect_to = !empty($_POST['redirect_to']) ? $_POST['redirect_to'] : $redirect;
            // redirect
            wp_safe_redirect($redirect_to);
            // exit
            exit;
        }
        // errors
        $error_html = mgm_set_errors($errors, true);
    }
    // end save-----------------------------------------------
    // issue#: 532
    $form_action = isset($args['package']) || isset($args['membership']) ? get_permalink() : mgm_get_custom_url('register');
    // package code:
    if ($package = mgm_request_var('package', '', true)) {
        $form_action = add_query_arg(array('package' => $package), $form_action);
    }
    // membership code:
    if ($membership = mgm_request_var('membership', '', true)) {
        $form_action = add_query_arg(array('membership' => $membership), $form_action);
    }
    // wordpress register
    $wordpres_form = mgm_check_wordpress_login();
    // 	get row row template
    $form_row_template = $system_obj->get_template('register_form_row_template');
    // get template row filter, mgm_register_form_row_template for custom, mgm_register_form_row_template_wordpress for wordpress
    $form_row_template = apply_filters('mgm_register_form_row_template' . ($wordpres_form ? '_wordpress' : ''), $form_row_template);
    // form_fields_config
    $form_fields_config = array('wordpres_form' => (bool) $wordpres_form, 'form_row_template' => $form_row_template, 'cf_register_page' => $cf_register_page, 'args' => $args);
    // get mgm_form_fields generator
    $form_fields = new mgm_form_fields($form_fields_config);
    // default
    $form_html = '';
    // register & purchase, purchase options
    if (isset($_GET['show_purchase_options']) && isset($_GET['post_id'])) {
        // set
        $form_html .= apply_filters('mgm_guest_purchase_register_form_pre_register_html', mgm_get_post_purchase_options((int) strip_tags($_GET['post_id']), 'pre_register'));
    }
    // register & purchase, add post id
    if (isset($_GET['post_id']) && (int) $_GET['post_id'] > 0) {
        // set
        $form_html .= sprintf('<input type="hidden" name="post_id" value="%d">', (int) strip_tags($_GET['post_id']));
    }
    //register & purchase postpack
    if (isset($_GET['postpack_id']) && (int) $_GET['postpack_id'] > 0 && isset($_GET['postpack_post_id']) && (int) $_GET['postpack_post_id'] > 0) {
        // set
        // $form_html .= mgm_get_postpack_template($_GET['postpack_id'],false,$_GET['postpack_post_id'],'pre_register');
        $form_html .= sprintf('<input type="hidden" name="postpack_id" value="%d">', (int) strip_tags($_GET['postpack_id']));
        $form_html .= sprintf('<input type="hidden" name="postpack_post_id" value="%d">', (int) strip_tags($_GET['postpack_post_id']));
    }
    // mgm_pr($register_fields);
    // loop default register fields, create each if they are not defined in custom fields
    foreach ($register_fields as $cfield => $wfield) {
        // set not found
        $captured = false;
        // first check if in custom fields
        foreach ($cf_register_page as $rfield) {
            // if default register field  == custom register field, skip
            if ($rfield['name'] == $cfield) {
                // skip custom fields by settings call
                if ($hide_custom_fields == 'Y' || $hide_custom_fields == 'W' && $wordpres_form || $hide_custom_fields == 'C' && !$wordpres_form) {
                    // if($hide_custom_fields && $cfield['name'] != 'subscription_options') continue;
                    if (!in_array($field['name'], array('subscription_options', 'payment_gateways'))) {
                        continue;
                    }
                }
                // set found
                $captured = true;
                // do nothing
                break;
            }
            // skip username if setting enabled @todo
            if ($cfield == 'username' && bool_from_yn($system_obj->get_setting('enable_email_as_username'))) {
                // set found
                $captured = true;
                break;
            }
        }
        // not found
        if (!$captured) {
            // create element
            $form_html .= str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wfield['name'], mgm_stripslashes_deep($wfield['label']), $form_fields->get_field_element($wfield, 'mgm_register_field')), $form_row_template);
        }
    }
    // register custom fields, this will be called via register_form hook
    // $form_html .= mgm_wp_register_form_additional($form_fields, $args, true);
    // register button text
    $register_button_text = apply_filters('mgm_register_button_text', $system_obj->get_setting('register_text', __('Register', 'mgm')));
    // buttons
    $buttons = array(sprintf('<input class="button mgm-register-button" type="submit" name="wp-submit" id="wp-submit" value="%s" tabindex="100" />', $register_button_text));
    // apply filters
    $buttons_s = implode(apply_filters('mgm_register_form_buttons_sep', ' &nbsp; '), apply_filters('mgm_register_form_buttons', $buttons));
    // append
    $buttons_html = sprintf('<div class="register-page-buttons">%s</div>', $buttons_s);
    // nonce
    $nonce = wp_nonce_field('user_register', '_mgmnonce_user_register', true, false);
    // this will not work in page shortcde as this does not return form html but directly outputs it
    // do_action('register_form');
    // set to globals to be used by "register_form" action hook
    $GLOBALS['form_fields'] = $form_fields;
    // attach custom fields via default hook
    $form_html .= apply_filters('mgm_register_form', $form_html);
    // output form
    $html = '<div class="mgm_register_form">
				' . $error_html . '
				<form class="mgm_form" name="registerform" id="registerform"  action="' . $form_action . '" method="post">	               
				   ' . $form_html . $buttons_html . $nonce . '					
					<input type="hidden" name="method" value="create_user">	
					<input type="hidden" name="show_fields" value="' . $args_fields . '">					
				</form>
			 </div>';
    // after links
    $links = array();
    // login link
    $links[] = sprintf('<a class="mgm-login-link" href="%s" title="%s">%s</a>', mgm_get_custom_url('login', $use_default_links), __('Log in', 'mgm'), __('Log in', 'mgm'));
    // lostpassword link
    if (get_option('users_can_register')) {
        $links[] = sprintf('<a class="mgm-lostpassword-link" href="%s" title="%s">%s</a>', mgm_get_custom_url('lostpassword', $use_default_links), __('Password Lost and Found', 'mgm'), __('Lost your password', 'mgm'));
    }
    // apply filters
    $links_s = implode(apply_filters('mgm_register_form_after_links_sep', ' | '), apply_filters('mgm_register_form_after_links', $links));
    // append
    $html .= sprintf('<div class="register-page-links">%s</div>', $links_s);
    // attach scripts,
    $html .= mgm_attach_scripts(true);
    // scripts & styles --------------------
    $script = "";
    //issue #1125
    $script .= "jQuery(document).ready(function() {\r\r\n\t\t\t\t\tvar c ='coupon';\r\r\n\t\t\t\t\tif(jQuery('.coupon_box input').attr('name') == 'mgm_register_field') {\t\r\r\n\t \t\t\t\t\tjQuery('.coupon_box input').attr('name', 'mgm_register_field['+c+']');\r\r\n\t\t\t\t\t}\r\r\n\t\t\t\t});";
    // script
    $script = sprintf('<script type="text/javascript">%s</script>', apply_filters('mgm_register_form_inline_script', $script));
    // scripts
    $html .= apply_filters('mgm_register_form_scripts', $script);
    // style
    $style = '.register-page-links, .register-page-buttons{margin-top:10px; clear:both}';
    // style
    $style = sprintf('<style type="text/css">%s</style>', apply_filters('mgm_register_form_inline_style', $style));
    // style
    $html .= apply_filters('mgm_register_form_styles', $style);
    // apply filter and return
    return apply_filters('mgm_register_form_html', $html);
}