Wordpress - Encrypt passwords of imported users - wordpress

I am about to import about 10,000 users to my Wordpress site from another CMS. Problem is, none of their passwords are going to work because they are not encrypted.
How do I encrypt all of these passwords quickly and in a way that Wordpress will recognize and accept so that users can login?

As encryption and hashing are different stuff, I assume all these passwords are in plain text format. In this case, all you have to do is to apply the md5 algorithm on them.
You can do it from a SQL or a PHP importing script. Take a look at the Resetting Your Password Codex page, and that should give you some light.
Anyway, you won't go too far from:
require_once( ABSPATH . WPINC . '/registration.php');
$sql = "SELECT ALL USERS FROM YOUR TABLE";
$db = new wpdb (DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$result = $db->get_results($sql);
foreach ($result as as $r) {
wp_update_user(array(
'user_login' => $r->username,
'user_pass' => $r->password,
'user_firstname' => $r->first_name
));
}
Take a look on the get_userdata function documentation to see what user info you can import at first moment.

As it turns out, I found a couple of other ways to do this. One is done through your mysql phpmyadmin area (on the "sql" tab once you've selected the right database) and was posted by Andrew Vit on another thread within stackoverflow:
UPDATE wp_users SET user_pass = MD5(user_pass) WHERE ...
for the "where" condition, if all your passwords are the same length, you might use the following condition:
WHERE CHAR_LENGTH(wp_users.user_pass) = 12
Of course, if your password length is different, simply change the "12" above to whatever the length of your passwords is. If they are NOT the same character length then you'll have to use some other criteria for determining which passwords to encrypt (unless they ALL need to be encrypted, in which case you can leave the "where" condition off entirely.
I personally ended up using a php script to do the work, so that the passwords could be encrypted by Wordpress itself (or at least using the method that Wordpress uses). Here are the contents of my php file:
<?php
require_once '/home/evaluate/public_html/members-blog/wp-config.php';
$sql="SELECT user_pass,ID FROM wp_users WHERE CHAR_LENGTH(wp_users.user_pass) = 12";
$find = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($find))
{
$current_password = $row['user_pass'];
$current_id = $row['ID'];
$hashed_password = wp_hash_password( $current_password );
$update_sql= "UPDATE wp_users SET user_pass = '" . $hashed_password . "' WHERE ID = " . $current_id . "";
$update = mysql_query($update_sql) or die(mysql_error());
echo $current_id . " " . $hashed_password;
echo "<br />";
}
?>
Done this way, not only are the passwords encrypted using Wordpress' own method, but, you also get a printout on your screen each time you run the script, showing you the ID of all the records that were updated and providing the corresponding hashed password.

Related

Id changing variable

I'm working on a project where I upload a file and use its path in a shortcode. Right now I've hard-coded the post's ID into my code but I want to make it dynamic so that new posts automatically get the correct shortcode.
<?php
global $wpdb;
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = 5574" ) );
echo do_shortcode ('[sgpx gpx="'.'/wp-content/uploads/' . $thepost->meta_value . '"]');
?>
Going off of what #Damocles said, you are really setting yourself up for trouble with your current path. Instead, there are built-in WordPress functions that abstract away the database and utilize caching that you are strongly encouraged to use.
// Get the current WordPress post
$the_post = get_post();
//If we have a value (there are cases where this will be empty)
if($the_post){
// Get the value from the post meta table by the current post's ID
$the_post_meta = get_post_meta($the_post->ID, 'YOUR_META_KEY_HERE', true);
// Double-check that we have a value
if($the_post_meta) {
// Finally, echo the shortcode
echo do_shortcode ('[sgpx gpx="'.'/wp-content/uploads/' . $the_post_meta . '"]');
}
}
There are several ways to get the current post however get_post() is the most common. If you are in a custom loop, however, you might need to adjust accordingly.
To access the meta, use get_post_meta() which includes some optimizations including use a cache instead of the database.
Although there are definitely exceptions, generally speaking, if you are working with WordPress and you find yourself writing SQL statements, there is almost always a better, safer, faster, etc. way to do it using core functions.

What is the user_id parameter of Wordpress function "wp_check_password" used for

I checked the wordpress documents for function:
wp_check_password( string $password, string $hash, string|int $user_id = '' )
and cannot figure out what is the purpose for $user_id. I thought it is the user_id column in my database, but just set it to some random numbers (or string) and it works.
Sorry if it is a duplicate question or has already answered.
wp-includes/pluggable.php contains this function. The user_id argument is used twice:
if ( $check && $user_id ) {
// Rehash using new hash.
wp_set_password($password, $user_id);
$hash = wp_hash_password($password);
}
This piece will set a users password if the passwords entered match. This is useful if you install a plugin that changes the password hashing mechanics, because it will migrate any passwords entered to the new mechanism when a user logs in.
This is, for instance, used by roots wp-password-bcrypt plugin.
The second line occurs twice, but both times with a return statement:
return apply_filters( 'check_password', $check, $password, $hash, $user_id );
This simply lets you catch that a password was just checked and, if needed, modify the result of the check.

how can we get details from another database inside a plugin in wordpress

I created a plugin in wordpress to display earnings by using a shortcode.The details to display while using shortcode are stored in another database.I used direct database connection in plugin to fetch details from the that database.I used the following code
function earnings_shortcode($atts, $content, $tag)
{ //echo $atts[0];echo '<br>';
$str=base64_encode(1);
base64_decode($str);
$length = 4;
$res = trim(preg_replace("/[^0-9]/", "", $atts[0]));
$mydb1 = new wpdb('root','','db_test','localhost');
$rows = $mydb1->get_row("SELECT total,paydate FROM `tbl_shotcode` WHERE userid = $res", ARRAY_A);
echo "Payout on -" .$rows['paydate']; echo '<br/>';
echo "Total for next Pay Period:-" .$rows['total'];
}
Is there any better option to access another database inside a plugin with out hard coding the username and password.please suggest a solution.
No, you have to access the database and be authenticated to do queries. You can't get into a properly configured database without login in.
You can, however, make your $mydb1 variable global and define it at the top of your file (or in your constructor class) to be accessed by all your functions. I recommend putting it in a class to manage it more easily.

Select custom meta (WPAlchemy) from pages with wpdb

I have read some documentation and comparable questions from others about my issue with wpdb, but I've seen very different answers so I'm slightly confused.
What I'm trying to do is get custom meta data from (eventually) about 250 pages in Wordpress. The wpdb request will be in header.php, and the code has to build an array which will serve as input for a Google Map. The custom meta fields are called _ytF_f_name, _ytF_f_lat and _ytF_f_lng (don't ask me why :-)).
So the final output should be: [name1,lat1,lng1], [name2,lat2,lng2], etc.
I'm using a custom table for Wordpress, which has the prefix yt_ (which is defined in wp-config.php). The custom meta is built with WPAlchemy. I have checked the database and the meta data is there (in the postmeta table).
After combining several things, this is what I have now:
<?php
global $wpdb;
$querystr = "SELECT ".$wpdb->prefix."postmeta._ytF_f_name, ".$wpdb->prefix."postmeta._ytF_f_lat, ".$wpdb->prefix."postmeta._ytF_f_lng FROM ".$wpdb->prefix."postmeta WHERE post_type='page'";
$vars = $wpdb->get_results($querystr);
foreach ($vars as $var) {
echo '[' . $var->_ytF_f_name . ',' . $var->_ytF_f_lat . ',' . $var->_ytF_f_lat . '],';
}
?>
The output is blank, so what am I missing here?
Another question related to this is; I've read something about 'prepare' to protect against sql injections.
Is the correct use of the prepare class to change
$vars = $wpdb->get_results($querystr);
into:
$vars = $wpdb->get_results($wpdb->prepare($querystr));
?
About your problem, I don't see the error, so verify if you have SQL errors with $wpdb->show_errors(); before your query (doc here).
The prepare method protects you against SQL injections.
As the doc said, it works like the following :
$wpdb->query(
$wpdb->prepare(
"INSERT INTO ___
( attr1, attr2 )
VALUES ( %s, %d )",
$valueOfAttr1,
$valueOfAttr2
)
);
Of course, you must change the types and values to your needs.

Cannot set user password in wordpress

i have tried everything i could find to set the user password on registration, but no success... I have the fields showing up, the verification(if the passwords match etc) i print them on screen, i print the userid on screen so every argument needed is there, but the function doesn't seem to work at all...
This doesn't work...
$newpassword = "zzzzzz";
update_user_meta($user_id, 'user_pass', $newpassword);
This doesn't work either...
add_action( 'user_register', 'ts_register_extra_fields', 10 );
function ts_register_extra_fields($user_id, $password='11',$meta = array()){
$userdata = array();
if ( $_POST['password'] !== '' ) {
$userdata['user_pass'] = $_POST['password'];
}
$new_user_id = wp_update_user( $userdata );
}
My customer needs this for tomorrow, so I'm totally lost by now, i have no clue on why it's not working...
Forgot to add, all this code is added in the functions.php of my theme. (It gets into it as i already said that i post the variables on screen).
add_action( 'user_register', 'ts_register_extra_fields', 100 );
function ts_register_extra_fields( $user_id, $password = '', $meta = array() ) {
$userdata = array();
$userdata['ID'] = $user_id;
$userdata['contacto'] = $_POST['contacto'];
$userdata['nif'] = $_POST['nif'];
if ( $_POST['password'] !== '' ) {
$userdata['user_pass'] = $_POST['password'];
echo "im in";
}
$new_user_id = wp_insert_user( $userdata );
echo "id-".$userdata['ID'];
echo "contacto-".$userdata['contacto'];
echo "nif-".$userdata['nif'];
echo "pass-".$userdata['user_pass'];
}
All those echos output the correct data... for example id = 195 the next time i try 196 etc...
contacto and nif show the data that i input in the custom registration field and the pass also shows the data that i had inputed in the custom registration field password...
First of all, I think WordPress is using MD5 encryption for passwords.
$hash = wp_hash_password( $newpassword );
// then wp_update_user with $hash as the user_pass value
Secondly, you shouldn't send passwords in clear text over the Internet. If you can encrypt the password with javascript before you send it, it would probably be a lot safer.
At last, give a shot at updating an existing user by specifying ID in wp_update_user.
A HA! Found the error. I have another plugin installed called "New User Aprovement" which required an administrator aprovement in order for the user to login. That plugin when the administrator accepted the user to login, generated another password (to be able to send the password to the user in a readable mode), invalidating the password update that i made when the user registered(because it generated a random password after the admin accept).
I found this by disabling the plugin and testing the functions.php. It did work. In order to make them both work i just erased the code in the plugin that generated a random password. Although the user doesn't receive the account summary via email. It works for my needs.
Best Regards,
Vcoder

Resources