/** * profile_fields_screen() * * Adds extra field to profile screen */ function register_profile_fields() { //HACK: to allow options global $bp; (array) ($bp->profile->field_types[] = 'option'); if (BPSP_Roles::field_group_id_from_name(__('Courseware', 'bpsp'))) { return false; } $bpsp_group_id = xprofile_insert_field_group(array(name => __('Courseware', 'bpsp'), description => __('Students and Teachers fields. Do not delete as long as you use BuddyPress ScholarPress Courseware!', 'bpsp'), can_delete => false)); if (!$bpsp_group_id) { wp_die(__('BuddyPress Courseware error when saving xProfile group.', 'bpsp')); } /* Create the radio buttons */ xprofile_insert_field(array(field_group_id => $bpsp_group_id, name => __('Role', 'bpsp'), can_delete => false, description => __('Your role when using Courseware. Every request requires moderation. Please be patient until an administrator reviews it.', 'bpsp'), is_required => false, type => 'radio')); $bpsp_field_id = xprofile_get_field_id_from_name(__('Role', 'bpsp')); if (!$bpsp_field_id) { wp_die(__('BuddyPress Courseware error when saving xProfile field.', 'bpsp')); } /* Create the radio options */ xprofile_insert_field(array(field_group_id => $bpsp_group_id, parent_id => $bpsp_field_id, name => __('Teacher', 'bpsp'), can_delete => false, is_required => false, type => 'option')); xprofile_insert_field(array(field_group_id => $bpsp_group_id, parent_id => $bpsp_field_id, name => __('Student', 'bpsp'), can_delete => false, is_required => false, type => 'option', is_default_option => true)); xprofile_insert_field(array(field_group_id => $bpsp_group_id, parent_id => $bpsp_field_id, name => __('Apply for Teacher', 'bpsp'), can_delete => false, is_required => false, type => 'option')); if (!xprofile_get_field_id_from_name(__('Teacher', 'bpsp')) || !xprofile_get_field_id_from_name(__('Student', 'bpsp')) || !xprofile_get_field_id_from_name(__('Apply for Teacher', 'bpsp'))) { wp_die(__('BuddyPress Courseware error when saving xProfile field options.', 'bpsp')); } return true; }
public function saved_field_action($field) { // Happens that new field has no accesible 'id' property if (empty($field->id)) { if ($field_id = xprofile_get_field_id_from_name($field->name)) { $field->id = $field_id; } else { return; } } // Register name if (!empty($field->name)) { icl_register_string($this->_context, "{$this->_field_string_prefix}{$field->id} name", $field->name); } // Register description if (!empty($field->description)) { icl_register_string($this->_context, "{$this->_field_string_prefix}{$field->id} description", $field->description); } // Register options if (in_array($field->type, array('radio', 'checkbox', 'selectbox', 'multiselectbox'))) { $bp_field = xprofile_get_field($field->id); $options = $bp_field->get_children(); foreach ($options as $option) { if (!empty($option->name)) { icl_register_string($this->_context, $this->sanitize_option_basename($option, $field->id) . ' name', $option->name); } if (!empty($option->description)) { icl_register_string($this->_context, $this->sanitize_option_basename($option, $field->id) . ' description', $option->description); } } } }
/** * @group xprofile_get_field_id_from_name */ public function test_get_id_from_name_field_name_option_value_conflict() { $group = $this->factory->xprofile_group->create(); // force some checkbox options for our profile field $_POST['checkbox_option'] = array(1 => 'BuddyPress', 2 => 'WordPress'); // checkbox field $f1 = $this->factory->xprofile_field->create(array('field_group_id' => $group, 'type' => 'checkbox', 'name' => 'Interests')); // textbox field with the same name as our checkbox value $f2 = $this->factory->xprofile_field->create(array('field_group_id' => $group, 'type' => 'textbox', 'name' => 'BuddyPress')); $this->assertEquals($f2, xprofile_get_field_id_from_name('BuddyPress')); // cleanup! unset($_POST['checkbox_option']); }
/** * Constructs Buddypress query for users whose last name begins with a cetain letter of the alphabet */ function aps_bp_last_name_filter($query_string) { $pattern = '/^[A-Z]$/'; $filter_letter = NULL; if (preg_match($pattern, $query_string)) { $filter_letter = $query_string; } $custom_ids = NULL; if (isset($filter_letter)) { global $wpdb; $the_field = xprofile_get_field_id_from_name('Last Name'); $user_query_string = "SELECT user_id FROM {$wpdb->prefix}bp_xprofile_data WHERE field_id = {$the_field} AND LEFT(value, 1) = \"{$filter_letter}\""; $custom_ids = $wpdb->get_col($user_query_string); } return $custom_ids; }
function xprofile_delete_field_data($field, $user_id) { if (is_numeric($field)) { $field_id = $field; } else { $field_id = xprofile_get_field_id_from_name($field); } if (empty($field_id) || empty($user_id)) { return false; } $field = new BP_XProfile_ProfileData($field_id, $user_id); return $field->delete(); }
/** * Generate SQL JOIN and WHERE clauses for a first-order query clause. * * "First-order" means that it's an array with a 'field' or 'value'. * * @since 2.2.0 * * @param array $clause Query clause. * @param array $parent_query Parent query array. * @return array { * Array containing JOIN and WHERE SQL clauses to append to a first-order query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ public function get_sql_for_clause(&$clause, $parent_query) { global $wpdb; $sql_chunks = array('where' => array(), 'join' => array()); if (isset($clause['compare'])) { $clause['compare'] = strtoupper($clause['compare']); } else { $clause['compare'] = isset($clause['value']) && is_array($clause['value']) ? 'IN' : '='; } if (!in_array($clause['compare'], array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP', 'NOT REGEXP', 'RLIKE'))) { $clause['compare'] = '='; } $field_compare = $clause['compare']; // First build the JOIN clause, if one is required. $join = ''; $data_table = buddypress()->profile->table_name_data; // We prefer to avoid joins if possible. Look for an existing join compatible with this clause. $alias = $this->find_compatible_table_alias($clause, $parent_query); if (false === $alias) { $i = count($this->table_aliases); $alias = $i ? 'xpq' . $i : $data_table; // JOIN clauses for NOT EXISTS have their own syntax. if ('NOT EXISTS' === $field_compare) { $join .= " LEFT JOIN {$data_table}"; $join .= $i ? " AS {$alias}" : ''; $join .= $wpdb->prepare(" ON ({$this->primary_table}.{$this->primary_id_column} = {$alias}.user_id AND {$alias}.field_id = %d )", $clause['field']); // All other JOIN clauses. } else { $join .= " INNER JOIN {$data_table}"; $join .= $i ? " AS {$alias}" : ''; $join .= " ON ( {$this->primary_table}.{$this->primary_id_column} = {$alias}.user_id )"; } $this->table_aliases[] = $alias; $sql_chunks['join'][] = $join; } // Save the alias to this clause, for future siblings to find. $clause['alias'] = $alias; // Next, build the WHERE clause. $where = ''; // Field_id. if (array_key_exists('field', $clause)) { // Convert field name to ID if necessary. if (!is_numeric($clause['field'])) { $clause['field'] = xprofile_get_field_id_from_name($clause['field']); } // NOT EXISTS has its own syntax. if ('NOT EXISTS' === $field_compare) { $sql_chunks['where'][] = $alias . '.user_id IS NULL'; } else { $sql_chunks['where'][] = $wpdb->prepare("{$alias}.field_id = %d", $clause['field']); } } // Value. if (array_key_exists('value', $clause)) { $field_value = $clause['value']; $field_type = $this->get_cast_for_type(isset($clause['type']) ? $clause['type'] : ''); if (in_array($field_compare, array('IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))) { if (!is_array($field_value)) { $field_value = preg_split('/[,\\s]+/', $field_value); } } else { $field_value = trim($field_value); } switch ($field_compare) { case 'IN': case 'NOT IN': $field_compare_string = '(' . substr(str_repeat(',%s', count($field_value)), 1) . ')'; $where = $wpdb->prepare($field_compare_string, $field_value); break; case 'BETWEEN': case 'NOT BETWEEN': $field_value = array_slice($field_value, 0, 2); $where = $wpdb->prepare('%s AND %s', $field_value); break; case 'LIKE': case 'NOT LIKE': $field_value = '%' . bp_esc_like($field_value) . '%'; $where = $wpdb->prepare('%s', $field_value); break; default: $where = $wpdb->prepare('%s', $field_value); break; } if ($where) { $sql_chunks['where'][] = "CAST({$alias}.value AS {$field_type}) {$field_compare} {$where}"; } } /* * Multiple WHERE clauses (`field` and `value` pairs) should be joined in parentheses. */ if (1 < count($sql_chunks['where'])) { $sql_chunks['where'] = array('( ' . implode(' AND ', $sql_chunks['where']) . ' )'); } return $sql_chunks; }
/** * xprofile_set_field_data() * * A simple function to set profile data for a specific field for a specific user. * * @package BuddyPress Core * @param $field_name The name of the field to set data for. * @param $user_id The ID of the user * @param $value The value for the field you want to set for the user. * @global $bp The global BuddyPress settings variable created in bp_core_setup_globals() * @uses xprofile_get_field_id_from_name() Gets the ID for the field based on the name. * @return true on success, false on failure. */ function xprofile_set_field_data($field_name, $user_id, $value) { global $bp; if (!($field_id = xprofile_get_field_id_from_name($field_name))) { return false; } $field = new BP_XProfile_ProfileData(); $field->field_id = $field_id; $field->user_id = $user_id; $field->value = $value; return $field->save(); }
/** * Saves Buddypress profile data. * * @uses WP_CRM_Core::wp_crm_save_user_data() * @param array $data. Request (POST,GET) * @author peshkov@UD */ static function bp_save_profile_data($data) { global $bp; if (empty($data['bp']) || empty($data['user_id'])) { return; } //* Set necessary variables */ $user_id = $data['user_id']; $user_data = $data['wp_crm']['user_data']; $data = $data['bp']; $errors = false; $posted_field_ids = array(); $is_required = array(); //* Set xprofile full name from display_name */ $display_name = WP_CRM_F::get_first_value($user_data['display_name']); if (!empty($display_name)) { $fullname_field_name = bp_xprofile_fullname_field_name(); $fullname_field_id = xprofile_get_field_id_from_name($fullname_field_name); $data["field_{$fullname_field_id}"] = $display_name; } //* Get all posted field ids */ foreach ($data as $name => $value) { $field_id = str_replace(array('field_', '_day', '_month', '_year'), '', $name); array_push($posted_field_ids, $field_id); } $posted_field_ids = array_unique($posted_field_ids); //* Validate the field */ foreach ($posted_field_ids as $field_id) { if (!isset($data['field_' . $field_id])) { if (!empty($data['field_' . $field_id . '_day']) && !empty($data['field_' . $field_id . '_month']) && !empty($data['field_' . $field_id . '_year'])) { /* Concatenate the values */ $date_value = $data['field_' . $field_id . '_day'] . ' ' . $data['field_' . $field_id . '_month'] . ' ' . $data['field_' . $field_id . '_year']; /* Turn the concatenated value into a timestamp */ $data['field_' . $field_id] = date('Y-m-d H:i:s', strtotime($date_value)); } } $is_required[$field_id] = xprofile_check_is_required_field($field_id); if ($is_required[$field_id] && empty($data['field_' . $field_id])) { $errors = true; } } //** There are errors */ if ($errors) { WP_CRM_F::add_message(__('Please make sure you fill in all required Buddypress fields in this profile field group before saving.', ud_get_wp_crm()->domain), 'bad'); //** No errors */ } else { //** Now we've checked for required fields, lets save the values. */ foreach ($posted_field_ids as $field_id) { //** Certain types of fields (checkboxes, multiselects) may come through empty. */ //** Save them as an empty array so that they don't get overwritten by the default on the next edit. */ if (empty($data['field_' . $field_id])) { $value = array(); } else { $value = $data['field_' . $field_id]; } if (!xprofile_set_field_data($field_id, $user_id, $value, $is_required[$field_id])) { $errors = true; } else { do_action('xprofile_profile_field_data_updated', $field_id, $value); } } //** Set the feedback message if we have error */ if ($errors) { WP_CRM_F::add_message(__('There was a problem updating some of Buddypress profile information, please try again.', ud_get_wp_crm()->domain), 'bad'); } } }
/** * register a user through api request * requires signup_* => display_name, username, password, confirm password, location, */ function rtmedia_api_process_wp_register_request() { //Registration errors and messages $ec_register_fields_missing = 300001; $msg_register_fields_missing = __('fields empty', 'rtmedia'); $ec_invalid_email = 300002; $msg_invalid_email = __('invalid email', 'rtmedia'); $ec_pass_do_not_match = 300003; $msg_pass_do_not_match = __('password do not match', 'rtmedia'); $ec_username_exists = 300004; $msg_username_exists = __('username already registered', 'rtmedia'); $ec_email_exists = 300005; $msg_email_existsh = __('email already exists', 'rtmedia'); $ec_user_insert_success = 300007; $msg_user_insert_success = __('new user created', 'rtmedia'); $registration_fields = array('username', 'email', 'password', 'password_confirm'); //fields empty field_1, field_4 if (empty($_POST['field_1'])) { echo $this->rtmedia_api_response_object('FALSE', $ec_register_fields_missing, $msg_register_fields_missing); exit; } foreach ($registration_fields as $field_name) { if (empty($_POST['signup_' . $field_name])) { echo $this->rtmedia_api_response_object('FALSE', $ec_register_fields_missing, $msg_register_fields_missing); exit; } } //incorrect email if (!is_email($_POST['signup_email'])) { echo $this->rtmedia_api_response_object('FALSE', $ec_invalid_email, $msg_invalid_email); exit; } elseif ($_POST['signup_password'] !== $_POST['signup_password_confirm']) { echo $this->rtmedia_api_response_object('FALSE', $ec_pass_do_not_match, $msg_pass_do_not_match); exit; } elseif (username_exists($_POST['signup_username'])) { echo $this->rtmedia_api_response_object('FALSE', $ec_username_exists, $msg_username_exists); exit; } elseif (email_exists($_POST['signup_email'])) { echo $this->rtmedia_api_response_object('FALSE', $ec_email_exists, $msg_email_existsh); exit; } else { $userdata = array('user_login' => $_POST['signup_username'], 'user_pass' => $_POST['signup_password'], 'display_name' => $_POST['field_1']); $user_id = wp_insert_user($userdata); if (!is_wp_error($user_id)) { echo xprofile_get_field_id_from_name('field_1'); xprofile_set_field_data(1, $user_id, $_POST['field_1']); update_user_meta($user_id, 'register_source', 'site_api'); echo $this->rtmedia_api_response_object('TRUE', $ec_user_insert_success, $msg_user_insert_success); exit; } else { echo $this->rtmedia_api_response_object('FALSE', $this->ec_server_error, $this->msg_server_error); exit; } } }
/** * Process content of CSV file * * @since 0.1 **/ public function generate_data() { // This function runs before we display the admin page, so we need to skip // the rest of this function if the user didn't click on the // Save, Load, or Delete Settings buttons if (!isset($_POST['_wpnonce-q-eud-export-user-page_export']) || isset($_POST['load_export']) || isset($_POST['save_export']) || isset($_POST['delete_export'])) { return false; } // check admin referer ## check_admin_referer('q-eud-export-user-page_export', '_wpnonce-q-eud-export-user-page_export'); // build argument array ## $args = array('fields' => 'all', 'role' => sanitize_text_field($_POST['role'])); // did they request a specific program ? ## if (isset($_POST['program']) && $_POST['program'] != '') { $args['meta_key'] = 'member_of_club'; $args['meta_value'] = (int) $_POST['program']; $args['meta_compare'] = '='; } // is there a range limit in place for the export ? ## if (isset($_POST['limit_offset']) && $_POST['limit_offset'] != '' && isset($_POST['limit_total']) && $_POST['limit_total'] != '') { // let's just make sure they are integer values ## $limit_offset = (int) $_POST['limit_offset']; $limit_total = (int) $_POST['limit_total']; if (is_int($limit_offset) && is_int($limit_total)) { $args['offset'] = $limit_offset; /* cwjordan codex says: * number - Limit the total number of users returned * so don't subtract the offset, like as not * that will give us a negative number for $args['number'] * e.g. offset of 1000 total of 100 */ $args['number'] = $limit_total; // $args['number'] = $limit_total - $limit_offset; #wp_die(pr($args)); } } /* pre_user query */ add_action('pre_user_query', array($this, 'pre_user_query')); $users = get_users($args); remove_action('pre_user_query', array($this, 'pre_user_query')); /* no users found, so chuck an error into the args array and exit the export */ if (!$users) { $referer = add_query_arg('error', 'empty', wp_get_referer()); wp_redirect($referer); exit; } /* get sitename and clean it up */ $sitename = sanitize_key(get_bloginfo('name')); if (!empty($sitename)) { $sitename .= '.'; } // export method ? ## $export_method = 'excel'; // default to Excel export ## if (isset($_POST['format']) && $_POST['format'] != '') { $export_method = sanitize_text_field($_POST['format']); } // set export filename structure ## $filename = $sitename . 'users.' . date('Y-m-d-H-i-s'); switch ($export_method) { case "csv": // to csv ## header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename=' . $filename . '.csv'); header('Content-Type: text/csv; charset=' . get_option('blog_charset'), true); // set a csv check flag $is_csv = true; // nothing here $doc_begin = ''; //preformat $pre = ''; // how to seperate data ## $seperator = ','; // comma for csv ## // line break ## $breaker = "\n"; // nothing here $doc_end = ''; break; case 'excel': // to xls ## header('Content-Description: File Transfer'); header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename={$filename}.xls"); header("Pragma: no-cache"); header("Expires: 0"); // set a csv check flag $is_csv = false; //grab the template file (for tidy formatting) include 'xml-template.php'; // open xml $doc_begin = $xml_doc_begin; //preformat $pre = $xml_pre; // how to seperate data ## $seperator = $xml_seperator; // line break ## $breaker = $xml_breaker; // close xml $doc_end = $xml_doc_end; break; } // function to exclude data ## $exclude_data = apply_filters('q_eud_exclude_data', array()); // check for selected usermeta fields ## $usermeta = isset($_POST['usermeta']) ? $_POST['usermeta'] : ''; $usermeta_fields = array(); if ($usermeta && is_array($usermeta)) { foreach ($usermeta as $field) { $usermeta_fields[] = sanitize_text_field($field); } } #pr($usermeta_fields); #exit; // check for selected x profile fields ## $bp_fields = isset($_POST['bp_fields']) ? $_POST['bp_fields'] : ''; $bp_fields_passed = array(); if ($bp_fields && is_array($bp_fields)) { foreach ($bp_fields as $field) { // reverse tidy ## $field = str_replace('__', ' ', sanitize_text_field($field)); // add to array ## $bp_fields_passed[] = $field; } } // cwjordan: check for x profile fields we want update time for ## $bp_fields_update = isset($_POST['bp_fields_update_time']) ? $_POST['bp_fields_update_time'] : ''; $bp_fields_update_passed = array(); if ($bp_fields_update && is_array($bp_fields_update)) { foreach ($bp_fields_update as $field) { // reverse tidy ## $field = str_replace('__', ' ', sanitize_text_field($field)); // add to array ## $bp_fields_update_passed[] = $field . " Update Date"; } } // global wpdb object ## global $wpdb; // exportable user data ## $data_keys = array('ID', 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'display_name'); // compile final fields list ## $fields = array_merge($data_keys, $usermeta_fields, $bp_fields_passed, $bp_fields_update_passed); // build the document headers ## $headers = array(); foreach ($fields as $key => $field) { // rename programs field ## if ($field == 'member_of_club') { $field = 'Program'; } if (in_array($field, $exclude_data)) { unset($fields[$key]); } else { if ($is_csv) { $headers[] = '"' . $field . '"'; } else { $headers[] = $field; #echo '<script>console.log("Echoing header cell: '.$field.'")</script>'; } } } // no more buffering while spitting back the export data ## ob_end_flush(); // get the value in bytes allocated for Memory via php.ini ## // @link http://wordpress.org/support/topic/how-to-exporting-a-lot-of-data-out-of-memory-issue?replies=2 $memory_limit = $this->return_bytes(ini_get('memory_limit')) * 0.75; // we need to disable caching while exporting because we export so much data that it could blow the memory cache // if we can't override the cache here, we'll have to clear it later... if (function_exists('override_function')) { override_function('wp_cache_add', '$key, $data, $group="", $expire=0', ''); override_function('wp_cache_set', '$key, $data, $group="", $expire=0', ''); override_function('wp_cache_replace', '$key, $data, $group="", $expire=0', ''); override_function('wp_cache_add_non_persistent_groups', '$key, $data, $group="", $expire=0', ''); } elseif (function_exists('runkit_function_redefine')) { runkit_function_redefine('wp_cache_add', '$key, $data, $group="", $expire=0', ''); runkit_function_redefine('wp_cache_set', '$key, $data, $group="", $expire=0', ''); runkit_function_redefine('wp_cache_replace', '$key, $data, $group="", $expire=0', ''); runkit_function_redefine('wp_cache_add_non_persistent_groups', '$key, $data, $group="", $expire=0', ''); } // open doc wrapper.. ## echo $doc_begin; // echo headers ## echo $pre . implode($seperator, $headers) . $breaker; // build row values for each user ## foreach ($users as $user) { // check if we're hitting any Memory limits, if so flush them out ## // per http://wordpress.org/support/topic/how-to-exporting-a-lot-of-data-out-of-memory-issue?replies=2 if (memory_get_usage(true) > $memory_limit) { wp_cache_flush(); } // open up a new empty array ## $data = array(); // BP loaded ? ## if (function_exists('bp_is_active')) { $bp_data = BP_XProfile_ProfileData::get_all_for_user($user->ID); } // loop over each field ## foreach ($fields as $field) { // check if this is a BP field ## if (isset($bp_data) && isset($bp_data[$field]) && in_array($field, $bp_fields_passed)) { $value = $bp_data[$field]; if (is_array($value)) { $value = maybe_unserialize($value['field_data']); // suggested by @grexican ## #$value = $value['field_data']; /** * cwjordan * after unserializing it we then * need to implode it so * that we have something readable? * Going to use :: as a separator * because that's what Buddypress Members Import * expects, but we might want to make that * configurable. */ if (is_array($value)) { $value = implode("::", $value); } } $value = $this->sanitize($value); // check if this is a BP field we want the updated date for ## } elseif (in_array($field, $bp_fields_update_passed)) { global $bp; $real_field = str_replace(" Update Date", "", $field); $field_id = xprofile_get_field_id_from_name($real_field); $value = $wpdb->get_var($wpdb->prepare("\n SELECT last_updated \n FROM {$bp->profile->table_name_data} \n WHERE user_id = %d AND field_id = %d\n ", $user->ID, $field_id)); // include the user's role in the export ## } elseif (isset($_POST['q_eud_role']) && $_POST['q_eud_role'] != '' && $field == 'role') { // add "Role" as $value ## $value = $user->roles[0] ? $user->roles[0] : ''; // empty value if no role found - note: we only take the first role assigned to the user ## // user data or usermeta ## } else { $value = isset($user->{$field}) ? $user->{$field} : ''; #$value = is_array( $value ) ? serialize( $value ) : $value; // maybe serialize the value ## $value = is_array($value) ? implode(", ", $value) : $value; // maybe serialize the value - suggested by @nicmare ## } // correct program value to Program Name ## if ($field == 'member_of_club') { $value = get_the_title($value); } if ($is_csv) { $data[] = '"' . str_replace('"', '""', $value) . '"'; } else { $data[] = $value; } } // echo row data ## echo $pre . implode($seperator, $data) . $breaker; } // close doc wrapper.. echo $doc_end; // stop PHP, so file can export correctly ## exit; }
/** * @group get_all_for_user */ public function test_get_all_for_user_uncached() { $u = $this->factory->user->create(); $g1 = $this->factory->xprofile_group->create(); $g2 = $this->factory->xprofile_group->create(); $f1 = $this->factory->xprofile_field->create(array('type' => 'textbox', 'field_group_id' => $g1)); $f2 = $this->factory->xprofile_field->create(array('type' => 'radio', 'field_group_id' => $g2)); $time = bp_core_current_time(); // Get the fullname field - hackish $f0_id = xprofile_get_field_id_from_name(bp_xprofile_fullname_field_name()); $f0 = new BP_XProfile_Field($f0_id); $g0 = new BP_XProfile_Group($f0->group_id); $d0 = new BP_XProfile_ProfileData($f0->id, $u); $d1 = new BP_XProfile_ProfileData(); $d1->user_id = $u; $d1->field_id = $f1; $d1->value = 'foo'; $d1->last_updated = $time; $d1->save(); $d2 = new BP_XProfile_ProfileData(); $d2->user_id = $u; $d2->field_id = $f2; $d2->value = 'bar'; $d2->last_updated = $time; $d2->save(); // Ensure it's deleted from cache wp_cache_delete("{$u}:{$f1}", 'bp_xprofile_data'); wp_cache_delete("{$u}:{$f2}", 'bp_xprofile_data'); $u_obj = new WP_User($u); $g1_obj = new BP_XProfile_Group($g1); $g2_obj = new BP_XProfile_Group($g2); $f1_obj = new BP_XProfile_Field($f1); $f2_obj = new BP_XProfile_Field($f2); $expected = array('user_login' => $u_obj->user_login, 'user_nicename' => $u_obj->user_nicename, 'user_email' => $u_obj->user_email, $f0->name => array('field_group_id' => $g0->id, 'field_group_name' => $g0->name, 'field_id' => $f0->id, 'field_type' => $f0->type, 'field_data' => $d0->value), $f1_obj->name => array('field_group_id' => $g1, 'field_group_name' => $g1_obj->name, 'field_id' => $f1, 'field_type' => $f1_obj->type, 'field_data' => $d1->value), $f2_obj->name => array('field_group_id' => $g2, 'field_group_name' => $g2_obj->name, 'field_id' => $f2, 'field_type' => $f2_obj->type, 'field_data' => $d2->value)); $this->assertEquals($expected, BP_XProfile_ProfileData::get_all_for_user($u)); }
/** * register a user through api request * requires signup_* => display_name, username, password, confirm password, location, */ function rtmedia_api_process_wp_register_request() { //Registration errors and messages $ec_register_fields_missing = 300001; $msg_register_fields_missing = esc_html__('fields empty', 'buddypress-media'); $ec_invalid_email = 300002; $msg_invalid_email = esc_html__('invalid email', 'buddypress-media'); $ec_pass_do_not_match = 300003; $msg_pass_do_not_match = esc_html__('password do not match', 'buddypress-media'); $ec_username_exists = 300004; $msg_username_exists = esc_html__('username already registered', 'buddypress-media'); $ec_email_exists = 300005; $msg_email_existsh = esc_html__('email already exists', 'buddypress-media'); $ec_user_insert_success = 300007; $msg_user_insert_success = esc_html__('new user created', 'buddypress-media'); $registration_fields = array('username', 'email', 'password', 'password_confirm'); //fields empty field_1, field_4 $field_1 = filter_input(INPUT_POST, 'field_1', FILTER_SANITIZE_STRING); if (empty($field_1)) { wp_send_json($this->rtmedia_api_response_object('FALSE', $ec_register_fields_missing, $msg_register_fields_missing)); } foreach ($registration_fields as $field_name) { $field_signup = filter_input(INPUT_POST, 'signup_' . $field_name, FILTER_SANITIZE_STRING); if (empty($field_signup)) { wp_send_json($this->rtmedia_api_response_object('FALSE', $ec_register_fields_missing, $msg_register_fields_missing)); } } $signup_email = filter_input(INPUT_POST, 'signup_email', FILTER_VALIDATE_EMAIL); $signup_username = filter_input(INPUT_POST, 'signup_username', FILTER_SANITIZE_STRING); $signup_password = filter_input(INPUT_POST, 'signup_password', FILTER_SANITIZE_STRING); $signup_password_confirm = filter_input(INPUT_POST, 'signup_password_confirm', FILTER_SANITIZE_STRING); //incorrect email if (!is_email($signup_email)) { wp_send_json($this->rtmedia_api_response_object('FALSE', $ec_invalid_email, $msg_invalid_email)); } elseif ($signup_password !== $signup_password_confirm) { wp_send_json($this->rtmedia_api_response_object('FALSE', $ec_pass_do_not_match, $msg_pass_do_not_match)); } elseif (username_exists($signup_username)) { wp_send_json($this->rtmedia_api_response_object('FALSE', $ec_username_exists, $msg_username_exists)); } elseif (email_exists($signup_email)) { wp_send_json($this->rtmedia_api_response_object('FALSE', $ec_email_exists, $msg_email_existsh)); } else { $userdata = array('user_login' => sanitize_user($signup_username), 'user_pass' => $signup_password, 'display_name' => sanitize_text_field($field_1)); $user_id = wp_insert_user($userdata); if (!is_wp_error($user_id)) { echo esc_html(xprofile_get_field_id_from_name('field_1')); xprofile_set_field_data(1, $user_id, sanitize_text_field($field_1)); //todo user attr update_user_meta($user_id, 'register_source', 'site_api'); echo wp_json_encode($this->rtmedia_api_response_object('TRUE', $ec_user_insert_success, $msg_user_insert_success)); wp_die(); } else { wp_send_json($this->rtmedia_api_response_object('FALSE', $this->ec_server_error, $this->msg_server_error)); } } }
function buatp_get_field_id_by_name($name) { return xprofile_get_field_id_from_name($name); }
function bp_ning_import_profiles_markup() { $profile_fields = bp_ning_import_get_profile_fields(); ?> <form method="post" action=""> <?php if (!empty($profile_fields)) { ?> <h3><?php _e('Profile fields', 'bp-ning-import'); ?> </h3> <p><?php _e('The following profile fields were identified in your Ning data. Select the ones you\'d like to keep as BuddyPress profile fields. Your members\' data will be imported automatically.', 'bp-ning-import'); ?> </p> <p><?php _e('You can also edit or add profile fields later on at Dashboard > BuddyPress > Profile Field Setup.', 'bp-ning-import'); ?> </p> <table id="ning-import-profile-fields"> <tr> <th> </th> <th><?php _e('Original field name'); ?> </th> <th><?php _e('New field name (optional)'); ?> </th> </tr> <?php $update = false; ?> <?php foreach ((array) $profile_fields as $pf) { ?> <?php if (xprofile_get_field_id_from_name($pf)) { continue; } ?> <?php $update = true; ?> <tr> <td> <input type="checkbox" name="pf[]" value="<?php echo $pf; ?> " checked> </td> <td><?php echo $pf; ?> </td> <td><input type="text" name="pfn[]" /></td> </tr> <?php } ?> </table> <?php if (!$update) { ?> <p>It looks like all of the profile fields found have already been imported. Click Continue to move on to the next step.</p> <?php } ?> <?php } else { ?> <h3><?php _e('Profile fields', 'bp-ning-import'); ?> </h3> <p><?php _e('No additional profile fields were found.', 'bp-ning-import'); ?> </p> <?php } ?> <div class="submit"> <input class="button primary-button" type="submit" id='submit' name='submit' value="<?php _e('Continue'); ?> "> <input type="hidden" id="current_step" name="current_step" value="profiles_done" /> </div> </form> <?php }
function amt_bp_get_profile_field_data($internal_profile_property, $user_id, $xprofile_field_map, $xprofile_public_fields) { foreach ($xprofile_field_map[$internal_profile_property] as $field_name) { $field_value = bp_get_profile_field_data(array('field' => $field_name, 'user_id' => $user_id)); // profile_group_id if (!empty($field_value) && in_array(xprofile_get_field_id_from_name($field_name), $xprofile_public_fields)) { return $field_value; } } return ''; }
function xprofile_delete_field_data($field = '', $user_id = 0) { // Get the field ID if (is_numeric($field)) { $field_id = (int) $field; } else { $field_id = xprofile_get_field_id_from_name($field); } // Bail if field or user ID are empty if (empty($field_id) || empty($user_id)) { return false; } // Get the profile field data to delete $field = new BP_XProfile_ProfileData($field_id, $user_id); // Delete the field data return $field->delete(); }
/** * Process content of CSV file * * @since 0.1 **/ public function generate_data() { // Check if the user clicked on the Save, Load, or Delete Settings buttons ## if (!isset($_POST['_wpnonce-q-eud-export-user-page_export']) || isset($_POST['load_export']) || isset($_POST['save_export']) || isset($_POST['delete_export'])) { return false; } // check admin referer ## check_admin_referer('q-eud-export-user-page_export', '_wpnonce-q-eud-export-user-page_export'); // build argument array ## $args = array('fields' => isset($_POST['user_fields']) && '1' == $_POST['user_fields'] ? 'all' : array('ID'), 'role' => sanitize_text_field($_POST['role'])); // did they request a specific program ? ## if (isset($_POST['program']) && $_POST['program'] != '') { $args['meta_key'] = 'member_of_club'; $args['meta_value'] = (int) $_POST['program']; $args['meta_compare'] = '='; } // is there a range limit in place for the export ? ## if (isset($_POST['limit_total']) && $_POST['limit_total'] != '') { // let's just make sure they are integer values ## $limit_offset = isset($_POST['limit_offset']) ? (int) $_POST['limit_offset'] : 0; $limit_total = (int) $_POST['limit_total']; if (is_int($limit_offset) && is_int($limit_total)) { $args['offset'] = $limit_offset; $args['number'] = $limit_total; // number - Limit the total number of users returned ## // test it ## #wp_die( $this->pr( $args ) ); } } // pre_user query ## add_action('pre_user_query', array($this, 'pre_user_query')); $users = get_users($args); remove_action('pre_user_query', array($this, 'pre_user_query')); // test args ## #wp_die( $this->pr ( $users ) ); // no users found, so chuck an error into the args array and exit the export ## if (!$users) { wp_redirect(add_query_arg('error', 'empty', wp_get_referer())); exit; } // get sitename and clean it up ## $sitename = sanitize_key(get_bloginfo('name')); if (!empty($sitename)) { $sitename .= '.'; } // export method ? ## $export_method = 'excel'; // default to Excel export ## if (isset($_POST['format']) && $_POST['format'] != '') { $export_method = sanitize_text_field($_POST['format']); } // set export filename structure ## $filename = $sitename . 'users.' . date('Y-m-d-H-i-s'); switch ($export_method) { case 'csv': // to csv ## header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename=' . $filename . '.csv'); header('Content-Type: text/csv; charset=' . get_option('blog_charset'), true); // set a csv check flag $is_csv = true; // nothing here $doc_begin = ''; //preformat $pre = ''; // how to seperate data ## $seperator = ','; // comma for csv ## // line break ## $breaker = "\n"; // nothing here $doc_end = ''; break; case 'excel': // to xls ## header('Content-Description: File Transfer'); header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename={$filename}.xls"); header("Pragma: no-cache"); header("Expires: 0"); // set a csv check flag $is_csv = false; //grab the template file (for tidy formatting) include 'xml-template.php'; // open xml $doc_begin = $xml_doc_begin; //preformat $pre = $xml_pre; // how to seperate data ## $seperator = $xml_seperator; // line break ## $breaker = $xml_breaker; // close xml $doc_end = $xml_doc_end; break; } // check for selected usermeta fields ## $usermeta = isset($_POST['usermeta']) ? $_POST['usermeta'] : ''; #$this->pr( $usermeta ); $usermeta_fields = array(); if ($usermeta && is_array($usermeta)) { foreach ($usermeta as $field) { $usermeta_fields[] = sanitize_text_field($field); } } #$this->pr( $usermeta_fields ); #exit; // check for selected x profile fields ## $bp_fields = isset($_POST['bp_fields']) ? $_POST['bp_fields'] : ''; $bp_fields_passed = array(); if ($bp_fields && is_array($bp_fields)) { foreach ($bp_fields as $field) { // reverse tidy ## $field = str_replace('__', ' ', sanitize_text_field($field)); // add to array ## $bp_fields_passed[] = $field; } } // cwjordan: check for x profile fields we want update time for ## $bp_fields_update = isset($_POST['bp_fields_update_time']) ? $_POST['bp_fields_update_time'] : ''; $bp_fields_update_passed = array(); if ($bp_fields_update && is_array($bp_fields_update)) { foreach ($bp_fields_update as $field) { // reverse tidy ## $field = str_replace('__', ' ', sanitize_text_field($field)); // add to array ## $bp_fields_update_passed[] = $field . " Update Date"; } } // global wpdb object ## global $wpdb; // debug ## if (self::debug) { self::log('generate_data(): merging array'); } // compile final fields list ## $fields = array_merge(self::get_user_fields(), self::get_special_fields(), $usermeta_fields, $bp_fields_passed, $bp_fields_update_passed); // test field array ## #self::pr( $fields ); // build the document headers ## $headers = array(); foreach ($fields as $key => $field) { // rename programs field ## if ($field == 'member_of_club') { $field = 'Program'; } // grab fields to exclude from exports ## if (in_array($field, $this->get_exclude_fields())) { // ditch 'em ## unset($fields[$key]); } else { if ($is_csv) { $headers[] = '"' . $field . '"'; } else { $headers[] = $field; #echo '<script>console.log("Echoing header cell: '.$field.'")</script>'; } } } // quick check ## #if ( self::debug ) self::log( 'All Fields: '. var_dump( $fields ) ); #if ( self::debug ) self::log( '$bp_fields_passed: '. var_dump( $bp_fields_passed ) ); // no more buffering while spitting back the export data ## ob_end_flush(); // get the value in bytes allocated for Memory via php.ini ## // @link http://wordpress.org/support/topic/how-to-exporting-a-lot-of-data-out-of-memory-issue $memory_limit = $this->return_bytes(ini_get('memory_limit')) * 0.75; // we need to disable caching while exporting because we export so much data that it could blow the memory cache // if we can't override the cache here, we'll have to clear it later... if (function_exists('override_function')) { override_function('wp_cache_add', '$key, $data, $group="", $expire=0', ''); override_function('wp_cache_set', '$key, $data, $group="", $expire=0', ''); override_function('wp_cache_replace', '$key, $data, $group="", $expire=0', ''); override_function('wp_cache_add_non_persistent_groups', '$key, $data, $group="", $expire=0', ''); } elseif (function_exists('runkit_function_redefine')) { runkit_function_redefine('wp_cache_add', '$key, $data, $group="", $expire=0', ''); runkit_function_redefine('wp_cache_set', '$key, $data, $group="", $expire=0', ''); runkit_function_redefine('wp_cache_replace', '$key, $data, $group="", $expire=0', ''); runkit_function_redefine('wp_cache_add_non_persistent_groups', '$key, $data, $group="", $expire=0', ''); } // open doc wrapper.. ## echo $doc_begin; // echo headers ## echo $pre . implode($seperator, $headers) . $breaker; #wp_die( self::pr( $users ) ); // build row values for each user ## foreach ($users as $user) { #wp_die( self::pr( $user ) ); // check if we're hitting any Memory limits, if so flush them out ## // per http://wordpress.org/support/topic/how-to-exporting-a-lot-of-data-out-of-memory-issue?replies=2 if (memory_get_usage(true) > $memory_limit) { wp_cache_flush(); } // open up a new empty array ## $data = array(); #wp_die( self::pr( $GLOBALS['bp'] ) ); // BP loaded ? ## if (function_exists('bp_is_active') && bp_is_active('xprofile')) { // grab all user data ## $bp_data = BP_XProfile_ProfileData::get_all_for_user($user->ID); } // single query method - get all user_meta data ## $get_user_meta = (array) get_user_meta($user->ID); #wp_die( self::pr( $get_user_meta ) ); // Filter out empty meta data ## #$get_user_meta = array_filter( array_map( function( $a ) { # return $a[0]; #}, $get_user_meta ) ); // loop over each field ## foreach ($fields as $field) { // check if this is a BP field ## if (isset($bp_data) && isset($bp_data[$field]) && in_array($field, $bp_fields_passed)) { // old way from single BP query ## $value = $bp_data[$field]; if (is_array($value)) { $value = maybe_unserialize($value['field_data']); // suggested by @grexican ## #$value = $value['field_data']; /** * cwjordan * after unserializing it we then * need to implode it so * that we have something readable? * Going to use :: as a separator * because that's what Buddypress Members Import * expects, but we might want to make that * configurable. */ if (is_array($value)) { $value = implode("::", $value); } } $value = self::sanitize($value); // check if this is a BP field we want the updated date for ## } elseif (in_array($field, $bp_fields_update_passed)) { global $bp; $real_field = str_replace(" Update Date", "", $field); $field_id = xprofile_get_field_id_from_name($real_field); $value = $wpdb->get_var($wpdb->prepare("\n SELECT last_updated \n FROM {$bp->profile->table_name_data} \n WHERE user_id = %d AND field_id = %d\n ", $user->ID, $field_id)); // include the user's role in the export ## } elseif (isset($_POST['roles']) && '1' == $_POST['roles'] && $field == 'roles') { // add "Role" as $value ## $value = isset($user->roles[0]) ? implode($user->roles, '|') : ''; // empty value if no role found - or flat array of user roles ## // include the user's BP group in the export ## } elseif (isset($_POST['groups']) && '1' == $_POST['groups'] && $field == 'groups') { if (function_exists('groups_get_user_groups')) { // check if user is a member of any groups ## $group_ids = groups_get_user_groups($user->ID); #self::pr( $group_ids ); #wp_die( pr( 'loaded group data.' )); if (!$group_ids || $group_ids == '') { $value = ''; } else { // new empty array ## $groups = array(); // loop over all groups ## foreach ($group_ids["groups"] as $group_id) { $groups[] = groups_get_group(array('group_id' => $group_id))->name . (end($group_ids["groups"]) == $group_id ? '' : ''); } // implode it ## $value = implode($groups, '|'); } } else { $value = ''; } } elseif ($field == 'bp_latest_update') { // https://bpdevel.wordpress.com/2014/02/21/user-last_activity-data-and-buddypress-2-0/ ## $value = bp_get_user_last_activity($user->ID); // user or usermeta field ## } else { // the user_meta key isset ## if (isset($get_user_meta[$field])) { // take from the bulk get_user_meta call - this returns an array in all cases, so we take the first key ## $value = $get_user_meta[$field][0]; // standard WP_User value ## } else { // use the magically assigned value from WP_Users $value = $user->{$field}; } // the $value might be serialized ## $value = self::unserialize($value); // the value is an array ## if (is_array($value)) { // recursive implode it ## $value = self::recursive_implode($value); } } // correct program value to Program Name ## if ($field == 'member_of_club') { $value = get_the_title($value); } // wrap values in quotes and add to array ## if ($is_csv) { $data[] = '"' . str_replace('"', '""', self::special_characters($value)) . '"'; // just add to array ## } else { $data[] = self::special_characters($value); } } // echo row data ## echo $pre . implode($seperator, $data) . $breaker; } // close doc wrapper.. echo $doc_end; // stop PHP, so file can export correctly ## exit; }