Bulk import wordpress users with pre-hashed passwords - php

I'm migrating a whole slew of users between two self-hosted Wordpress sites, and I'm trying to find a way to bring them across without resetting their passwords. The current site has everyone's passwords, naturally, all nicely hashed. Currently the two methods I could see to import these users (wp_insert_user() and wp_create_user()) both require the passwords to be in clear text. Is there something I'm missing, or can this just not be done with current methods?

You have 3 options. Run a custom database query, copy and modify wp_insert_user(), or run wp_insert_user() twice.
Copy and modify wp_insert_user()
Below is a custom wp_insert_user function. All I've done is removed the line that hashes the PW.
function wpse_custom_insert_user( $userdata ) {
global $wpdb;
if ( is_a( $userdata, 'stdClass' ) )
$userdata = get_object_vars( $userdata );
elseif ( is_a( $userdata, 'WP_User' ) )
$userdata = $userdata->to_array();
extract( $userdata, EXTR_SKIP );
// Are we updating or creating?
if ( !empty($ID) ) {
$ID = (int) $ID;
$update = true;
$old_user_data = WP_User::get_data_by( 'id', $ID );
} else {
$update = false;
}
$user_login = sanitize_user($user_login, true);
$user_login = apply_filters('pre_user_login', $user_login);
//Remove any non-printable chars from the login string to see if we have ended up with an empty username
$user_login = trim($user_login);
if ( empty($user_login) )
return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
if ( !$update && username_exists( $user_login ) )
return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
if ( empty($user_nicename) )
$user_nicename = sanitize_title( $user_login );
$user_nicename = apply_filters('pre_user_nicename', $user_nicename);
if ( empty($user_url) )
$user_url = '';
$user_url = apply_filters('pre_user_url', $user_url);
if ( empty($user_email) )
$user_email = '';
$user_email = apply_filters('pre_user_email', $user_email);
if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
if ( empty($nickname) )
$nickname = $user_login;
$nickname = apply_filters('pre_user_nickname', $nickname);
if ( empty($first_name) )
$first_name = '';
$first_name = apply_filters('pre_user_first_name', $first_name);
if ( empty($last_name) )
$last_name = '';
$last_name = apply_filters('pre_user_last_name', $last_name);
if ( empty( $display_name ) ) {
if ( $update )
$display_name = $user_login;
elseif ( $first_name && $last_name )
/* translators: 1: first name, 2: last name */
$display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $first_name, $last_name );
elseif ( $first_name )
$display_name = $first_name;
elseif ( $last_name )
$display_name = $last_name;
else
$display_name = $user_login;
}
$display_name = apply_filters( 'pre_user_display_name', $display_name );
if ( empty($description) )
$description = '';
$description = apply_filters('pre_user_description', $description);
if ( empty($rich_editing) )
$rich_editing = 'true';
if ( empty($comment_shortcuts) )
$comment_shortcuts = 'false';
if ( empty($admin_color) )
$admin_color = 'fresh';
$admin_color = preg_replace('|[^a-z0-9 _.\-#]|i', '', $admin_color);
if ( empty($use_ssl) )
$use_ssl = 0;
if ( empty($user_registered) )
$user_registered = gmdate('Y-m-d H:i:s');
if ( empty($show_admin_bar_front) )
$show_admin_bar_front = 'true';
$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login));
if ( $user_nicename_check ) {
$suffix = 2;
while ($user_nicename_check) {
$alt_user_nicename = $user_nicename . "-$suffix";
$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login));
$suffix++;
}
$user_nicename = $alt_user_nicename;
}
$data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
$data = wp_unslash( $data );
if ( $update ) {
$wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
$user_id = (int) $ID;
} else {
$wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
$user_id = (int) $wpdb->insert_id;
}
$user = new WP_User( $user_id );
foreach ( _get_additional_user_keys( $user ) as $key ) {
if ( isset( $$key ) )
update_user_meta( $user_id, $key, $$key );
}
if ( isset($role) )
$user->set_role($role);
elseif ( !$update )
$user->set_role(get_option('default_role'));
wp_cache_delete($user_id, 'users');
wp_cache_delete($user_login, 'userlogins');
if ( $update )
do_action('profile_update', $user_id, $old_user_data);
else
do_action('user_register', $user_id);
return $user_id;
}
Running wp_insert_user twice
If you run wp_insert_user() user_pass is expected to be a plain string. If you include an ID parameter however you need to use a hashed password instead.
You could run wp_insert_user() with a random password to insert the user. This will return an ID. You could then run the same function again including the ID and the hashed password.
As I pointed out above this is inefficient and not something I'd suggest but it would be possible. Here's an example:
$hashed_pw = get_hashed_pw(); // Replace this with the correct hashed password.
$user_args = array(
'ALL MY' => 'OTHER ARGS', // Enter all your other arguments for wp_insert_user().
'user_pass' => 'random', // Set this to a random string.
);
$user_id = wp_insert_user( $user_args );
$update_user_args = array(
'ID' => $user_id,
'user_pass' => $hashed_pw,
);
wp_insert_user( $update_user_args );
This is not a complete solution. If you were to use it you'd want to include some error checking, etc. You're much better off with one of the two other solutions posed.

Related

Update specific data when someone edit his profile

When user update his email then update a specific row table.
I know how to take the new value of email, but I dont know how to use it in other row in different table.
table name: BIG
row name: secondName
I have this
function wpdocs_check_user_email_updated( $user_id, $old_user_data ) {
$old_user_email = $old_user_data->data->user_email;
$user = get_userdata( $user_id );
$new_user_email = $user->user_email;
if ( $new_user_email !== $old_user_email ) {
// I dont know how to do it
}
}
add_action( 'profile_update', 'wpdocs_check_user_email_updated', 10, 2 );
You can use WP predefine wpdb::update check the below code.
function wpdocs_check_user_email_updated( $user_id, $old_user_data ) {
global $wpdb;
$old_user_email = $old_user_data->data->user_email;
$user = get_userdata( $user_id );
$new_user_email = $user->user_email;
if ( $new_user_email !== $old_user_email ) {
$data = array( 'your-column-name' => $new_user_email );
$where = array( 'your-column-name' => $user_id );
$wpdb->update( $wpdb->prefix . 'your_table', $data, $where );
}
}
add_action( 'profile_update', 'wpdocs_check_user_email_updated', 10, 2 );
USEFUL LINKS
wpdb::update

Wordpress - Send email to users when they get new followers

I'm using a simple plugin "user following system" And all what i need to do is sending an email after the users get a new followers.
I think this is the important part of the plugin code:
function pwuf_follow_user( $user_id, $user_to_follow ) {
$following = pwuf_get_following( $user_id );
if ( $following && is_array( $following ) ) {
$following[] = $user_to_follow;
} else {
$following = array();
$following[] = $user_to_follow;
}
// retrieve the IDs of all users who are following $user_to_follow
$followers = pwuf_get_followers( $user_to_follow );
if ( $followers && is_array( $followers ) ) {
$followers[] = $user_id;
} else {
$followers = array();
$followers[] = $user_id;
}
do_action( 'pwuf_pre_follow_user', $user_id, $user_to_follow );
// update the IDs that this user is following
$followed = update_user_meta( $user_id, '_pwuf_following', $following );
// update the IDs that follow $user_id
$followers = update_user_meta( $user_to_follow, '_pwuf_followers', $followers );
// increase the followers count
$followed_count = pwuf_increase_followed_by_count( $user_to_follow ) ;
if ( $followed ) {
do_action( 'pwuf_post_follow_user', $user_id, $user_to_follow );
return true;
}
return false;
}
and here to check if a user is following another:
function pwuf_is_following( $user_id, $followed_user ) {
$following = pwuf_get_following( $user_id );
$ret = false; // is not following by default
if ( is_array( $following ) && in_array( $followed_user, $following ) ) {
$ret = true; // is following
}
return $ret;
}
I tried to add this code after updating the user meta but nothing happen!
$subscribers = explode(",", $user_to_follow );
$emails = array ();
foreach ( $subscribers as $subscriber ) {
$user_info = get_userdata($subscriber);
$emails[] = $user_info ->user_email;
}
$body = sprintf( $user_to_follow->display_name, 'followed your work! See <%s>' );
wp_mail( $emails, 'New followers!', $body );
I believe you want to send user an email when ever user is been followed by another user. Given this scenario, there is this action hook available in the plugin which is executed when following process is successful:
do_action( 'pwuf_post_follow_user', $user_id, $user_to_follow );
You can hook your own code to this action
add_action('pwuf_post_follow_user', $user_id, $user_to_follow) {
$follower = get_userdata($user_id);
$recipient = get_userdata($user_to_follow);
$recipient_email = $recipient->user_email;
$body = sprintf('%s followed your work!', $follower->display_name );
wp_mail( $recipient_email , 'New follower!', $body );
}
Refernece: https://codex.wordpress.org/Function_Reference/get_userdata

Form not being saved to vendors even though setup in functions.php

I am trying to save a vendor using a gravity form as the front end however i am not getting the record created the form does submit succefully though, i do have user registraction enabled though. I am using wordpress version 4.5.1 and plugin verison 5.3.7 of gravity forms.
I have treid everything I can think of for this but still is not working.
function wc_create_vendor_on_registration( $entry, $form) {
$username = rgar( $entry, '6' );
$email =rgar( $entry, '5' );
$description =rgar( $entry, '2' );
// Ensure vendor name is unique
if ( term_exists( $username, 'shop_vendor' ) ) {
$append = 1;
$o_username = $username;
while ( term_exists( $username, 'shop_vendor' ) ) {
$username = $o_username . $append;
$append ++;
}
}
// Create the new vendor
$return = wp_insert_term(
$username,
'shop_vendor',
array(
'description' => description ,
'slug' => sanitize_title( $username )
)
);
if ( is_wp_error( $return ) ) {
wc_add_notice( __( '<strong>ERROR</strong>: Unable to create the vendor account for this user. Please contact the administrator to register your account.', 'localization-domain' ), 'error' );
} else {
// Update vendor data
$vendor_data['paypal_email'] = $email; // The email used for the account will be used for the payments
$vendor_data['commission'] = '50'; // The commission is 50% for each order
$vendor_data['admins'][] = $customer_id; // The registered account is also the admin of the vendor
update_option( 'shop_vendor_' . $return['term_id'], $vendor_data );
$caps = array(
"edit_product",
"read_product",
"delete_product",
"edit_products",
"edit_others_products",
"delete_products",
"delete_published_products",
"delete_others_products",
"edit_published_products",
"assign_product_terms",
"upload_files",
"manage_bookings",
);
$skip_review = get_option( 'woocommerce_product_vendors_skip_review' ) == 'yes' ? true : false;
if( $skip_review ) {
$caps[] = 'publish_products';
}
$caps = apply_filters( 'product_vendors_admin_caps', $caps );
$user = new WP_User( $customer_id );
foreach( $caps as $cap ) {
$user->add_cap( $cap );
}
}
}
add_action( 'gform_after_submission_1', 'after_submission', 10, 2 );
add_action( 'woocommerce_created_customer', 'wc_create_vendor_on_registration', 10, 2 );
?>

Set session in Invision Power Board

After lots of efforts we found something for IPB remote login, but it's not working correctly. We are able to fetch member information but not able to set this member in session.
Please help us to the set session for IPB.
Here is the code:
remote_login.php
<?php
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
$path = '';
require_once $path . 'init.php';
\IPS\Session\Front::i();
$key = md5( md5( \IPS\Settings::i()->sql_user . \IPS\Settings::i()->sql_pass ) . \IPS\Settings::i()->board_start );
$login_type = 'email';
/* uncomment for more security */
// $ip_address = array('127.0.0.1', 'x.x.x.x'); // EDIT THIS LINE!!
// if(in_array($_SERVER['REMOTE_ADDR'], $ip_address) !== TRUE) {
// echo_json(array('status' => 'FAILD', 'msg' => 'BAD_IP_ADDR'));
// }
/* -~-~-~-~-~-~ Stop Editing -~-~-~-~-~-~ */
if( !\IPS\Request::i()->do || !\IPS\Request::i()->id || !\IPS\Request::i()->key || !\IPS\Login::compareHashes( \IPS\Request::i()->key, md5($key . \IPS\Request::i()->id))) {
echo_json(array('status' => 'FAILD', 'msg' => 'BAD_KEY'));
}
$member = \IPS\Member::load( \IPS\Request::i()->id, $login_type );
if( !$member->member_id ) {
echo_json(array('status' => 'FAILD', 'msg' => 'ACCOUNT_NOT_FOUND'));
}
switch(\IPS\Request::i()->do) {
case 'get_salt':
echo_json(array('status' => 'SUCCESS', 'pass_salt' => $member->members_pass_salt));
break;
case 'login':
if( \IPS\Login::compareHashes($member->members_pass_hash, \IPS\Request::i()->password) === TRUE ) {
/* Remove old failed login attempts */
if ( \IPS\Settings::i()->ipb_bruteforce_period and ( \IPS\Settings::i()->ipb_bruteforce_unlock or !isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) or $member->failed_logins[ \IPS\Request::i()->ipAddress() ] < \IPS\Settings::i()->ipb_bruteforce_attempts ) )
{
$removeLoginsOlderThan = \IPS\DateTime::create()->sub( new \DateInterval( 'PT' . \IPS\Settings::i()->ipb_bruteforce_period . 'M' ) );
$failedLogins = $member->failed_logins;
if ( is_array( $failedLogins ) )
{
foreach ( $failedLogins as $ipAddress => $times )
{
foreach ( $times as $k => $v )
{
if ( $v < $removeLoginsOlderThan->getTimestamp() )
{
unset( $failedLogins[ $ipAddress ][ $k ] );
}
}
}
$member->failed_logins = $failedLogins;
}
else
{
$member->failed_logins = array();
}
$member->save();
}
/* If we're still here, the login was fine, so we can reset the count and process login */
if ( isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) )
{
$failedLogins = $member->failed_logins;
unset( $failedLogins[ \IPS\Request::i()->ipAddress() ] );
$member->failed_logins = $failedLogins;
}
$member->last_visit = time();
$member->save();
/*==========================try to set session code start================*/
/* Create a unique session key and redirect */
\IPS\Session::i()->setMember( $member );
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P7D' ) );
\IPS\Request::i()->setCookie( 'member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'pass_hash', $member->member_login_key, $expire );
if ( $anonymous and !\IPS\Settings::i()->disable_anonymous )
{
\IPS\Request::i()->setCookie( 'anon_login', 1, $expire );
}
\IPS\Session::i()->setMember( $member );
\IPS\Session::i()->init();
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );
/*$member->checkLoginKey();
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P1Y' ) );
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );*/
/*==========================try to set session code end================*/
echo_json(
array(
'status' => 'SUCCESS',
'connect_status' => ( $member->members_bitoptions['validating'] ) ? 'VALIDATING' : 'SUCCESS',
'email' => $member->email,
'name' => $member->name,
'connect_id' => $member->member_id,
'member' =>$member
)
);
}
break;
}
function echo_json(array $arr) {
echo json_encode($arr);
exit;
}
login.php
<?php
$ips_connect_key = '3325a51154becfc88fXXXXXXXXX';
$remote_login = 'IPB/remote_login.php';
$email = $_GET['email'];
$password = $_GET['password'];
$key = md5($ips_connect_key . $email);
// fetch salt first
$res = json_decode(file_get_contents($remote_login . "?do=get_salt&id={$email}&key={$key}"), true);
$hash = crypt( $password, '$2a$13$' . $res['pass_salt'] );
$res = json_decode(file_get_contents($remote_login . "?do=login&id={$email}&key={$key}&password={$hash}"), true);
$_COOKIE["ips4_member_id"]=41;
$_COOKIE['ips4_pass_hash']="e195d3939b62342481dfc32fcf360538";
$_COOKIE['ips4_IPSSessionFront']="sn359rogbto4j7jqhcqh10stl5";
print_r($res);
echo "<br/><br/><br/>";
print_r($_COOKIE);
calling login.php
login.php?email=XXXXX#gmail.com&password=XXXXXX!
Here we are able to get member information but not able to set that member as logged in.

How to add Remember me function at custom login box?

In my theme, there's custom page for the login. Login function at functions.php is like this
function log_in($username, $password) {
$user = parse_user($username);
$username = $username;
$password = $password;
if(isEmptyString($username)) return new WP_Error('username', 'required');
if(isEmptyString($password)) return new WP_Error('password', "required");
if(!wp_check_password( $password, $user->user_pass ) ) return new WP_Error('wrong_password', "wrong");
wp_set_auth_cookie($user->ID, $remember);
wp_login($username, $password);
redirect_profile();
}
function parse_user($info = null, $return = 'object') {
if ( is_null( $info ) ) {
global $current_user;
if ( empty( $current_user->ID ) ) return null;
$info = get_userdata( $current_user->ID );
}
elseif ( empty( $info ) ) {
return null;
}
if( $return == 'ID' ) {
if ( is_object( $info ) ) return $info->ID;
if ( is_numeric( $info ) ) return $info;
}
elseif( $return == 'object' ) {
if ( is_object( $info ) && $info->ID) return $info;
if ( is_object( $info )) return get_userdata( $info->ID );
if ( is_numeric( $info ) ) return get_userdata( $info );
if ( is_string( $info ) ) return get_userdatabylogin( $info );
}
else {
return null;
}
}
I want to add remember me checkbox for user to logged in all the time until they logout. How can i add this ? Please kindly help me out. Thank you.
"remember me" buttons are generally just a simple tweak to the cookie settings internally. Instead of a session cookie that gets deleted when the browser is exitted, a "remember me" login cookie gets some future expiration point (a day, a month, a year, etc...) so it'll persist after the browser's closed.
In pseudo-code, you'd have:
if (form_value('remember_me') == 'yes) {
set_long_term_cookie();
} else {
set_session_cookie();
}
"Add a login form on your WordPress Theme" (including remember me functionality):
http://www.wprecipes.com/add-a-login-form-on-your-wordpress-theme
Also: http://www.problogdesign.com/how-to/how-to-create-a-wordpress-login-form-overlay/
etc...

Categories