/**
  * API helper method get user data, get user data
  *
  * @param int $user_id
  * @return array $user
  */
 function _get_user($user_id)
 {
     // get user
     $user = mgm_get_userdata((int) $user_id);
     // check null
     if (is_null($user)) {
         // error
         _e('User cannot be found.', 'mgm');
         // return
         return false;
     }
     // send user
     return $user;
 }
 /**
  * API helper method get userdata
  *
  * @param int $user_id
  * @return array $userdata
  */
 function _get_userdata($user_id)
 {
     // get userdata
     $user = mgm_get_userdata($user_id);
     // user data
     $email = stripslashes($user->user_email);
     $first_name = !empty($user->first_name) ? stripslashes($user->first_name) : '';
     $last_name = !empty($user->last_name) ? stripslashes($user->last_name) : '';
     $full_name = !empty($first_name) ? mgm_str_concat($first_name, $last_name) : $user->display_name;
     // return
     $userdata = array('email' => $email, 'full_name' => $full_name, 'first_name' => $first_name, 'last_name' => $last_name);
     // member
     $member = mgm_get_member($user_id);
     // custom fields
     if ($member->custom_fields) {
         // get vars
         $custom_fields = get_object_vars($member->custom_fields);
         // check
         if (count($custom_fields) > 0) {
             // loop
             foreach ($custom_fields as $custom_field => $value) {
                 // check
                 if (!isset($userdata[$custom_field])) {
                     // ensure fields already set are not overwritten
                     $userdata[$custom_field] = $value;
                 }
             }
         }
     }
     //other membership types -issue #1073
     if ($member->other_membership_types) {
         $other_membership_types = array();
         foreach ($member->other_membership_types as $o_membership_type) {
             if (!empty($o_membership_type)) {
                 $other_membership_types[] = $o_membership_type['membership_type'];
             }
         }
         $userdata['other_membership_types'] = $other_membership_types;
     }
     // membership type
     if ($member->membership_type) {
         $userdata['membership_type'] = $member->membership_type;
     }
     // return
     return $userdata;
 }
/**
 * 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;
}