/**
 * Receives BBCONNECT-specific data and prepares it for WP insertion.
 * On insertion scenarios, WORDPRESS takes the lead.
 * On update scenarios BBCONNECT takes the lead.
 *
 * @since 1.0.2
 *
 * @param arr $ivals Optional. The passed data. Default is a $_POST array.
 * @param bool $update Optional. Whether or not to update.
 * @param str $match Optional. The user field to match on, can use metadata but carefully...
 * @param bool $data_handler Optional. Default is to overwrite existing data .
 * @param bool $no_log Optional. Prevents creation of a post to log the event.
 * @param str $log_type Optional. The type of BBCONNECT action to document the source of the insertion.
 * @param str $log_code Optional. The source code of the BBCONNECT action.
 * @param str $title Optional. The title of the BBCONNECT action.
 * @param str $content Optional. The content of the BBCONNECT action.
 * @param int $agent Optional. The ID of the user performing the action.
 *
 * @return int/arr The ID if insertion was successful, otherwise a WP_Error.
 */
function bbconnect_insert_user($args = '')
{
    global $current_user, $pppass;
    /* SET THE DEFAULTS TO BE OVERRIDDEN AS DESIRED
    		- Need to remove the POST default
    		- reset the type to be a default post type,
    		- add other arg to capture the source and insert as meta
    		-- possibly mode the 'no_log' logic to not add a note if source is false
    		- note the 'private' status now of insertions
    		- need to add hooks to check if we should trigger other actions like subscribe
    		- perhaps a flag to note those subscribed without their buy-in
    	*/
    $defaults = array('ivals' => false, 'update' => false, 'match' => false, 'data_handler' => 'overwrite', 'no_log' => false, 'log_type' => 'admin_registration', 'log_code' => false, 'title' => 'Registration', 'content' => '', 'agent' => $current_user->ID);
    // PARSE THE INCOMING ARGS
    $args = wp_parse_args($args, $defaults);
    // EXTRACT THE VARIABLES
    extract($args, EXTR_SKIP);
    if (false === $ivals) {
        return false;
    }
    // SCRUB!
    $ivals = bbconnect_scrub('bbconnect_sanitize', $ivals);
    // SET THE USERDATA ARRAY
    $userdata = array();
    // IF THIS IS AN UPDATE, SET A USER OBJECT TO TEST AGAINST
    if (false != $update && false != $match) {
        // SET THE DEFAULT MATCHES
        $wp_match_reserve = array('slug', 'email', 'id', 'login');
        // IF WE DON'T HAVE A DEFAULT, TRY AND EXTRACT THE USER ID
        // REGARDLESS, DELIVER A USER OBJECT
        if (!in_array($match, $wp_match_reserve)) {
            //$wpdb->flush();
            global $wpdb;
            $match_value = $wpdb->get_results($wpdb->prepare("SELECT {$wpdb->usermeta}.user_id FROM {$wpdb->usermeta} WHERE {$wpdb->usermeta}.meta_value = %s", $ivals['bbconnect_user_meta'][$match]), ARRAY_N);
            $wpdb->flush();
            if (empty($match_value) || !isset($match_value[0]) || empty($match_value[0])) {
                $user = false;
            } else {
                if (1 < count($match_value[0])) {
                    $user_id = new WP_Error('sorry', 'I found multiple users matching this field -- so I did not do anything');
                    return $user_id;
                } else {
                    $match_single = array_shift($match_value[0]);
                    $user = get_user_by('id', $match_single);
                }
            }
        } else {
            $user = get_user_by($match, $ivals[$match]);
        }
    } else {
        $user = false;
    }
    // SET THE USER LOGIN WITH A RANDOM STRING IF NEED BE
    if (!empty($ivals['user_login'])) {
        $userdata['user_login'] = $ivals['user_login'];
    } else {
        if (!$user) {
            $username_prefix = get_option('_bbconnect_username_prefix');
            $upre = '';
            if (false != $username_prefix) {
                if ('%y%' == $username_prefix) {
                    $upre = date('Y');
                } else {
                    $upre = $username_prefix;
                }
            }
            $userdata['user_login'] = bbconnect_random(array('name' => $upre, 'compact' => true));
        }
    }
    // SET THE USER EMAIL WITH A RANDOM STRING IF NEED BE
    if (!empty($ivals['email'])) {
        $userdata['user_email'] = $ivals['email'];
    } else {
        if (!$user) {
            $userdata['user_email'] = $userdata['user_login'] . '@noreply.invalid';
        }
    }
    /*
    if ( false == is_email( $userdata['user_email'] ) ) {
    	$user_id = new WP_Error('sorry', 'This email is incomplete.');
    	return $user_id;
    }
    */
    // SET THE DISPLAY NAME
    if (!empty($ivals['display_name'])) {
        $userdata['display_name'] = $ivals['display_name'];
    } else {
        if (!$user) {
            $dname = '';
            if (isset($ivals['bbconnect_user_meta']['first_name']) || isset($ivals['bbconnect_user_meta']['last_name'])) {
                if (isset($ivals['bbconnect_user_meta']['first_name'])) {
                    $dname .= $ivals['bbconnect_user_meta']['first_name'] . ' ';
                }
                if (isset($ivals['bbconnect_user_meta']['last_name'])) {
                    $dname .= $ivals['bbconnect_user_meta']['last_name'];
                }
            } else {
                if (isset($ivals['bbconnect_user_meta']['organization'])) {
                    $dname .= $ivals['bbconnect_user_meta']['organization'];
                }
            }
            $userdata['display_name'] = trim($dname);
        }
    }
    // SET THE NICKNAME
    if (!empty($ivals['bbconnect_user_meta']['nickname'])) {
        $userdata['nickname'] = $ivals['bbconnect_user_meta']['nickname'];
    } else {
        if (!$user) {
            if (isset($ivals['bbconnect_user_meta']['first_name'])) {
                $fname = $ivals['bbconnect_user_meta']['first_name'];
            } else {
                $fname = '';
            }
            $userdata['nickname'] = $fname;
        }
    }
    // OPTIONALLY SET THE ROLE IF DESIRED -- WILL OTHERWISE DEFAULT TO WP SETTINGS
    if (!empty($ivals['role'])) {
        $userdata['role'] = $ivals['role'];
    }
    // OPTIONALLY SET THE REGISTRATION DATE IF DESIRED -- WILL OTHERWISE DEFAULT TO WP SETTINGS
    if (!empty($ivals['user_registered'])) {
        $userdata['user_registered'] = $ivals['user_registered'];
    }
    // OPTIONALLY SET THE PASSWORD -- ALL ERROR CHECKING SHOULD BE DONE PRIOR
    // MAKE THE PASSWORD GLOBAL FOR NOTIFICATION PURPOSES
    if (!empty($ivals['pass1'])) {
        $pppass = $ivals['pass1'];
        $userdata['user_pass'] = $pppass;
    } else {
        if (!$user) {
            $pppass = wp_generate_password();
            $userdata['user_pass'] = $pppass;
        }
    }
    // LASTLY, SET THE URL!
    if (!empty($ivals['url'])) {
        $userdata['user_url'] = $ivals['url'];
    }
    // SET THE USER EMAIL WITH A RANDOM STRING IF NEED BE
    if (!empty($ivals['show_admin_bar_front'])) {
        $userdata['show_admin_bar_front'] = $ivals['show_admin_bar_front'];
    } else {
        $sabf = bbconnect_get_option('show_admin_bar_front');
        $userdata['show_admin_bar_front'] = $sabf['options']['choices'];
    }
    // MAKE THE INSERTION. IF WE'RE UPDATING, DO SO AFTER THE META UPDATE
    if (!$user) {
        $user_id = wp_insert_user($userdata);
    } else {
        $userdata['ID'] = $user->ID;
        $user_id = $user->ID;
    }
    // IF WE GOT AN ERROR, RETURN THE ERROR
    if (is_wp_error($user_id)) {
        return $user_id;
    }
    // UPDATE THE USER META AND TAXONOMIES
    bbconnect_update_user_metadata(array('user_id' => $user_id, 'uvals' => $ivals, 'data_handler' => $data_handler));
    // IF WE'RE UPDATING, DO IT NOW
    if ($user && isset($userdata['ID'])) {
        $user_id = wp_update_user($userdata);
    }
    // IF WE GOT AN ERROR, RETURN THE ERROR
    if (is_wp_error($user_id)) {
        return $user_id;
    }
    // DOCUMENT THE SOURCE OF THE USER'S INSERTION
    if (false == $no_log) {
        $postdata['post_title'] = $title;
        $postdata['post_content'] = $content;
        $postdata['post_status'] = 'private';
        $postdata['post_author'] = $user_id;
        $postdata['post_type'] = 'bbc_log';
        $post_id = wp_insert_post($postdata, true);
        // UPDATE THE META
        if (intval($post_id)) {
            update_post_meta($post_id, '_bbc_log_code', $log_code);
            update_post_meta($post_id, '_bbc_log_type', $log_type);
            if (0 !== $agent) {
                update_post_meta($post_id, '_bbc_agent', $agent);
                $ins_log = array(array('id' => $agent, 'date' => time()));
                update_post_meta($post_id, '_bbc_log', $ins_log);
            }
        }
    }
    return $user_id;
}
function bbconnect_profile_fields_update()
{
    if (isset($_POST['data'])) {
        if (!check_ajax_referer('bbconnect-admin-nonce', 'bbconnect_admin_nonce', false)) {
            wp_die(__('that was an illegal action. no data was saved.', 'bbconnect'));
        }
        $post_data = stripslashes_deep(maybe_unserialize(rawurldecode($_POST['data'])));
        $post_vars = explode('&bbconnect_user_', $post_data);
        $post_vars = explode('&bbconnect_user_meta_options', $post_data);
        $post_proc = array();
        $test_proc = array();
        foreach ($post_vars as $var) {
            $pairs = explode('=', $var);
            preg_match_all("/\\[.*?\\]/", $pairs[0], $matches);
            //$post_proc[] = count($matches[0]);
            $match = $matches[0];
            /*
            			$tproc = '';
            			foreach ( $match as $m ) {
            				$pre_proc = str_replace(array('[',']'),'',$m);
            				if ( '' == $pre_proc )
            					$pre_proc = bbconnect_random();
            
            				$tproc .= '['.$pre_proc.']';
            				$tproc = substr($tproc,-1,-1);
            			}
            			$test_proc{$tproc} = urldecode( $pairs[1] );
            */
            if (1 == count($match)) {
                $post_proc[str_replace(array('[', ']'), '', $match[0])] = urldecode($pairs[1]);
            } else {
                if (2 == count($match)) {
                    $post_proc[str_replace(array('[', ']'), '', $match[0])][str_replace(array('[', ']'), '', $match[1])] = urldecode($pairs[1]);
                } else {
                    if (3 == count($match)) {
                        $post_proc[str_replace(array('[', ']'), '', $match[0])][str_replace(array('[', ']'), '', $match[1])][str_replace(array('[', ']'), '', $match[2])] = urldecode($pairs[1]);
                    } else {
                        if (4 == count($match)) {
                            if ('' == str_replace(array('[', ']'), '', $match[3])) {
                                $newtry = bbconnect_random();
                            } else {
                                $newtry = str_replace(array('[', ']'), '', $match[3]);
                            }
                            $post_proc[str_replace(array('[', ']'), '', $match[0])][str_replace(array('[', ']'), '', $match[1])][str_replace(array('[', ']'), '', $match[2])][$newtry] = urldecode($pairs[1]);
                        } else {
                            if (5 == count($match)) {
                                $post_proc[str_replace(array('[', ']'), '', $match[0])][str_replace(array('[', ']'), '', $match[1])][str_replace(array('[', ']'), '', $match[2])][str_replace(array('[', ']'), '', $match[3])][str_replace(array('[', ']'), '', $match[4])] = urldecode($pairs[1]);
                            } else {
                                if (6 == count($match)) {
                                    $post_proc[str_replace(array('[', ']'), '', $match[0])][str_replace(array('[', ']'), '', $match[1])][str_replace(array('[', ']'), '', $match[2])][str_replace(array('[', ']'), '', $match[3])][str_replace(array('[', ']'), '', $match[4])][str_replace(array('[', ']'), '', $match[5])] = urldecode($pairs[1]);
                                } else {
                                    if (7 == count($match)) {
                                        $post_proc[str_replace(array('[', ']'), '', $match[0])][str_replace(array('[', ']'), '', $match[1])][str_replace(array('[', ']'), '', $match[2])][str_replace(array('[', ']'), '', $match[3])][str_replace(array('[', ']'), '', $match[4])][str_replace(array('[', ']'), '', $match[5])][str_replace(array('[', ']'), '', $match[6])] = urldecode($pairs[1]);
                                    } else {
                                        if (8 == count($match)) {
                                            $post_proc[str_replace(array('[', ']'), '', $match[0])][str_replace(array('[', ']'), '', $match[1])][str_replace(array('[', ']'), '', $match[2])][str_replace(array('[', ']'), '', $match[3])][str_replace(array('[', ']'), '', $match[4])][str_replace(array('[', ']'), '', $match[5])][str_replace(array('[', ']'), '', $match[6])][str_replace(array('[', ']'), '', $match[7])] = urldecode($pairs[1]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        //unset( $_POST['data'] );
        //parse_str( $post_data, $_POST );
        //echo count( $_POST ) . ' items and ' . memory_get_peak_usage(true) . ' memory';
        //$post_processed = bbconnect_meta_options_pre_form( $post_proc );
        bbconnect_meta_options_form_save($post_proc);
        //echo 'memory='.memory_get_peak_usage(true);
    } else {
        _e('There seems to be a problem.', 'bbconnect');
    }
    die;
}
function bbconnect_username_prefix($args = null)
{
    // SET THE DEFAULTS TO BE OVERRIDDEN AS DESIRED
    $defaults = array('fdata' => false, 'fvalue' => false, 'faction' => false, 'ftype' => false);
    // PARSE THE INCOMING ARGS
    $args = wp_parse_args($args, $defaults);
    // EXTRACT THE VARIABLES
    extract($args, EXTR_SKIP);
    echo '<input type="text" class="input-short" name="_bbc_option[_bbconnect_username_prefix]" value="' . $fvalue . '" />' . bbconnect_random(array('compact' => true)) . '<br />';
    echo '<span class="example-text">' . sprintf(__('You may use this code %1$s for the Year or any text string as a prefix.', 'bbconnect'), '%y%') . '</span>';
}