drupal_set_message drupal - drupal

I have created a reset password form in drupal 6. On submit I have to redirect to the same page show a Drupal message.
I have written the following:
global $language;
$account = $form_state['values']['account'];
_user_mail_notify('password_reset', $account, $language);
watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
drupal_set_message(t('Further instructions have been sent to your e-mail address.'));
$form_state['redirect'] = 'user/password';
return;
}
but my mail code is working fine but my message is not shown.

Try this code it will redirect you on same page and show message...
$msg = "Further instructions have been sent to your e-mail address.";
drupal_set_message($msg, $type = 'status');
drupal_goto('user/password');

Have you tried switching back to Garland (to check if the theme is at fault)?
Have you checked your user table has a 0 (zero) entry for anonymous? Sometimes imported tables miss that row due to the auto increment setting on the uid field.
Does the message show for authenticated/admin users?
I assume your snippet is the submit handler? I assume $form_state is being passed in by reference?

You can try this code to redirect to another page with message
drupal_set_message(t('Further instructions have been sent to your e-mail address.'));
drupal_goto('user/password');

Instead of $form_state['redirect'] use the drupal_goto function:
drupal_set_message(
'Further instructions have been sent to your e-mail address.',
'status', $repeat = FALSE);
drupal_goto('user/password');

Related

Wordpress custom login errors based on whether or not an advanced custom field is set true for that user

I have kind of a unique issue. I have migrated a website and rebuilt it on wordpress. Some of the users that were migrated over the passwords were not migrated with them. So for all the old users I added an advanced custom field named "password_reset" and set it to true for all the older users.
What I am trying to do is show a custom message for these users that says something like "we have updated our website please rest your password with a link to reset".
I have added the below code to a function in the functions.php file
//if migrated user needs to reset password
$username = $_POST['username'];
if (username_exists( $username ) && get_field( 'password_reset', 'user_'.$uid ) ) {
$error= 'Please reset your password. To reset your password click here.';
}
return $error;
since the user isn't logged in quite yet when they are to recieve this error, I am trying to use the username_exists(username). Basically I need to identify is the user name exists already and if that username has the acf field "password_reset" checked. So far I have had no luck, any help would be much appreciated.
UPDATE: here is my lates version: the messages for invalid username and incorrect password are working, Just can't get it to work with the usernames that hold the acf value
function my_custom_error_messages() {
global $errors;
$err_codes = $errors->get_error_codes();
// Invalid username.
if ( in_array( 'invalid_username', $err_codes ) ) {
$error = '<strong>ERROR</strong>: Invalid username.';
}
// Incorrect password.
if ( in_array( 'incorrect_password', $err_codes ) ) {
$error = '<strong>ERROR</strong>: The password you entered is incorrect.';
if (username_exists( $username ) && get_field( 'password_reset', 'user_'.$uid ) ) {
$error= 'Please reset your password. To reset your password click here.';
}
}
return $error;
}
add_filter( 'login_errors', 'my_custom_error_messages');
I believe the issue is that the username is not passed to the login_errors filter. The only data available within that filter is the error message that is passed (no definitive data about user accounts at all).
I have found a different reference that may shed some light on a way to provide a customized error message without using that filter. Try using the wp_authenticate_user filter, instead:
WordPress codex reference
https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_authenticate_user
Reference for application of code
https://backups.nl/internet/wordpress-revealing-username-login-trial-error/

Disable auto login upon registration in Wordpress

[update1] I am using the ClassiCraft theme and I have no idea where to customize the login and register forms
[update2] I know that the registration process does not go through wp_authenticate because I redefined it inside a plugin of mine
I am quite new in the Wordpress world (actually just got my hands on it for the first time yesterday) and I am having some difficulties finishing up a little project I am working on.
The project is rather simple (or so I thought) and consists in adding a confirmation link to email received upon registration in order to validate the email address provided to prevent using fake emails that the registrar does not even own.
I am about all done except that once I hit the register button it leads to log in the freshly created user.
I googled stuff like "wp disable auto login on registration" and whatnot but I have not been able to find anything that worked. I even tested a few plugins supposed to be doing exactly what I need but none of them worked.
Also, I am not using any plugins for the registration/login forms and it appears that the code in the wp-login.php file is actually not even used...
Would anyone have an idea? Thanks
Okay, so without an access to the theme, i can't really answer you.
But i can tell you what I would try.
1. Add action on user_register hook, to add a post meta that will be useful to check if user has confirm his email.
add_action( 'user_register', 'add_has_confirm_email_user_meta');
function add_has_confirm_email_user_meta( $user_id ) {
update_user_meta( $user_id, 'has_confirm_email', 0 );
}
2. Prevent the user from log in automatically after registration.
Here i can't tell you the hook that will works for you. For example, the hook for the wordpress registration is user_register, but if you have woocommerce, the hook I will use, would be woocommerce_registration_redirect. So try to find what hook is available after the registration with your theme.
In all case, the code in the function would be something like :
function custom_registration_redirect() {
// Log out the user
wp_logout();
// The login url could be an other, with woocommerce for example it is : get_permalink(get_option('woocommerce_myaccount_page_id')
$login_url = wp_login_url();
// Redirect on it
wp_redirect( $login_url);
exit;
}
It will also be necessary, to add a message on this page to alert the user, that he will receive an email to confirm his account.
3. Prevent user from login when he submit the log in form
Add action on wp_login hook to achieve that.
add_action('wp_login', 'prevent_user_from_login', 10, 2);
function prevent_user_from_login($user_login, $user = null ) {
if ( !$user ) {
$user = get_user_by('login', $user_login);
}
if ( !$user ) {
// not logged in
return;
}
// Get user meta
$has_confirm_email = get_user_meta( $user->ID, 'has_confirm_email', true );
if ( $has_confirm_email == '0' ) {
// Clear cookies, a.k.a log user out
wp_clear_auth_cookie();
$login_url = wp_login_url();
$login_url = add_query_arg( 'has_confirm_email', '0', $login_url);
wp_redirect( $login_url );
exit;
}
}
4. Add message on log in page if we get the has_confirm_email to 0
add_filter('login_message', 'has_not_confirm_email_login_message');
function has_not_confirm_email_login_message($message) {
if ( isset( $_GET['has_confirm_email'] ) && $_GET['has_confirm_email'] == 0 ) {
$message = '<div id="login_error">You have not confirmed your email.</div>';
}
return $message;
}
5. Send the email with a link to confirm his email.
You will need to generate a token to add to the url.
For the hook to change the default email sent by Wordpress, you can use wp_new_user_notification_email that is available since the 4.9 of Wordpress.
In the function itself you could do something like :
function wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname) {
// Generate the token (there is other function available with php 7, but this one works great)
$token = bin2hex(openssl_random_pseudo_bytes(16));
// Add the token to the user
update_user_meta( $user->id, 'confirm_email_token', $token );
// Get your login url
$log_in_url = wp_login_url();
// Add user id and token to the url
$url = add_query_arg(
array(
'token' => $token,
'user_id' => $user->id
),
$log_in_url
);
//
$wp_new_user_notification_email['subject'] = 'Welcome on our website, please confirm your email';
$wp_new_user_notification_email['message'] = 'Blablabla... the url to confirm is: '. $url;
return $wp_new_user_notification_email;
}
6. Hook on the login page to check the $_GET, looking for user_id and token.
Here we check the token and the user. If everything is okay, update the user meta has_confirm_email to 1, so the user can connect, and add a message : "Your email has been confirmed, you can now log in"
add_action( 'login_init', 'custom_login_init');
function custom_login_init(){
if(!empty($_GET['token']) && !empty($_GET['user_id'])) {
if(get_the_author_meta( 'confirm_email_token', $_GET['user_id']) === $_GET['token']) {
// Set the has_confirm_email to 1 so the user can now log in
update_user_meta( $user_id, 'has_confirm_email', 1);
update_user_meta( $user_id, 'confirm_email_token', '');
echo 'Your email has been confirmed, you can now log in';
}
}
}
7. Time for thinking
Okay, after all of his, i'm gonna think a little, and read what i have tell you, to check if there is no mistake ^^. Tell me if you need more explanations.
I think this is a good start for you, and if you find the right hooks, you will achieve this rapidly.
Be careful on some hooks that i have used, because your theme may have use a custom registration or something.
Here is what I did:
added a column in the table wp_users to receive the email confirmation code
built a plugin (details here) called user-emails that allows me to bypass the first email sent upon registration by redefining the function wp_new_user_notification (in which I generate the confirmation code, add it to the user in the DB and send a confirmation email of my own sauce)
redefined the wp_authenticate function inside the same plugin user-emails to allow me to check if the email has been confirmed (column value not null)
created a page for the confirmation with the email and code passed to it that, in case of success, display a message and a link to the home page in order to login
finally got my hands on that one tiny line of code responsible for the auto login after registration located in the page user_auth.php inside the theme folder itself (that file also contains the layout for the login and registration form)
wp_set_auth_cookie( $user_id, true, $secure_cookie );
made sure to display a message after registration informing the user to check his email for the confirmation email

check if user email exists, and if not, stop the submit of the ninja form

I've one form built with ninja forms, and I use ajax to send it.
I need to check if the email introduced already exists in database (user_email), and if it exists properly, I send the form properly, but if it doesn't exist, the form isn't submitted, and I need to give the user the message like "email does not exist".
The form is a survey to be completed by a registered user, who gives us a feedback about our services, but the survey is located in a page where the user can send its opinion without needed to be logged.
I'm investigating, and at the moment I have:
function example_disable_saving_subs( $save, $form_id ) {
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
$email = ninja_forms_get_field_by_id( 18 );
//cuestionario feedback profesor sobre creación de un curso
if($form_id == 3){
if( !email_exists( $email )) {
$save = false;
$ninja_forms_processing->add_error('email_no_existe', 'El email no existe');
}
}
return $save;
}
add_filter( 'ninja_forms_save_submission', 'example_disable_saving_subs', 2, 10 );
But I pick up the field $email without value introduced...In addition, I don't know the way to give the user the message "email does not exists".
As you see, I chose the filter ninja_forms_save_submission. Maybe this is not the correct filter.
I hope your valious help.
Thanks in advance, Daniel
thanks for your help #Renato , I give you +1 :)
It's true that I can do it through the way you tell me, but I don't want to break the api of WordPress, that is, the way this cms uses javascript, php, etc etc...So, I wanted to do this through the API of ninja forms, which is the plugin I use for build this survey.
Finally, I solved it...it was my mistake, because I didn't use the correct filter...Investigating few more, there's another filter much more appropiate: ninja_forms_pre_process
Here is the code:
function add_change_ninja_forms_landing_page(){
add_action( 'ninja_forms_pre_process', 'handle_custom_ninja_forms' );
}
add_action( 'init', 'add_change_ninja_forms_landing_page' );
function handle_custom_ninja_forms(){
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
//if it's my form of survey
if( $form_id == 3 ){
$email = $ninja_forms_processing->get_field_value( 18 ); //pick up the value of the email field
//use the native function of wordpress to check if there's a user with this email
//is anyone has this email, it does not exist
if( !email_exists( $email )) {
$ninja_forms_processing->add_error('email_no_existe', 'El email indicado no está registrado en nuestra base de datos'); //add_error stop the form and gives the error message
}
}
}
With the code above everything works fine! :)
Thanks!
Daniel,
I am not familiar with ninja_forms, but thinking of javascript, you can encapsulate your code to verify if users exists into an url and then, when making the ajax call, use it to verify...
If you can't change the ajax request, you can validate the field on it's blur event and disable the submit button untill it's marked as "successfull"
For you to create PHP files, and yet, use all Wordpress power and functionalities, you can simply include this file on the beggining of the file that will be called
require(wp-blog-header.php)

Drupal login error message displayed without using form_set_error()

I created a module that adds a field to the user login block form to display errors. I want to display the error in the new field instead of using form_set_error(). I am able to see the warning field in the login block. But when I submit with an error it does not display the error.
Code is as follows. I do not understand how to refresh the value of form once it gets an error.
function usermoved_form_user_login_block_alter(&$form, &$form_state) {
$form['warning'] = array(
'#value' => t('oops'),
'#weight' => 11
);
$form['#submit'][] = 'usermoved_form_submit_code';
}
function usermoved_form_submit_code($form, &$form_state) {
global $user;
if (!$user->uid) {
$form['warning']['value']= "changed to someting";
}
}
Your code is wrong: Instead of using $form['warning']['value'], it should use $form['warning']['#value']. Even doing so, the message (which should be passed to t()) is not shown to the users because $form is not passed by reference, and it is not the value returned from the form submission handler, which is not expected to return any value.
Form submission handlers are then never called, when a form validation handler raises an error. If you are checking the user ID to see if the user has not been logged-in, then you cannot do it in a form submission handler, as the user not being logged-in means there have been errors during the validation phase, and the form submission handlers are not invoked.
What you can use is a form validation handler.
function usermoved_form_user_login_block_alter(&$form, &$form_state) {
$message = (empty($_SESSION['usermoved_form_user_login_block_alter']) ? t('Initial message') : $_SESSION['usermoved_form_user_login_block_alter']);
$form['warning'] = array(
'#value' => $message,
'#weight' => 11
);
$form['#validate'][] = 'usermoved_form_validate_code';
}
function usermoved_form_validate_code($form, &$form_state) {
if (empty($form_state['uid'])) {
$_SESSION['usermoved_form_user_login_block_alter'] = t('The error message');
}
else {
unset($_SESSION['usermoved_form_user_login_block_alter']);
}
}
$form_state['uid'] is a value set from user_login_authenticate_validate(), the second validation handler invoked by Drupal. When it is not set, it means there have been some errors before Drupal tried to authenticate the user, or the user didn't authenticate. The first case can happen when the user is blocked (user_login_name_validate() verifies that), or the user tried too much times to authenticate (see user_login_authenticate_validate() which uses flood_is_allowed() to verify the user didn't try too much times to authenticate); the latter case can happen when the user didn't enter the right password. (See user_login_final_validate().)
As side notes:
I used t('Initial message') as default message, but that could be replaced with '', if you don't have any message to show to the users before they log in.
The user login block is not shown to already logged-in users. $user->uid (where $user is the global variable) is always 0, when the login block is shown, and when logging-in failed; checking the value of $user->uid while showing the login block doesn't make sense.

Override user_login_submit in Drupal 6 to redirect an authenticated user

I would like to redirect a user that logged in over the user login block. What I have is a module that contains the following code:
Appendix, 3.9.2011, 15:30h: Changed code according to the advice of kiamlaluno.
Appendix, 3.9.2011, 17:08h: Small Fix: Changed node/admin to admin.
Appendix, 3.9.2011, 17:24h: removed []
-> code is working like this now, but do not forget to change the module priority in DB.
function _MYMODULE_user_login_submit($form, &$form_state) {
global $user;
if ($user->uid == 1) {
$form_state['redirect'] = 'admin';
} elseif ($user->uid) {
$form_state['redirect'] = 'node/add/image';
return;
}
}
/**
* Modifies the outfit and behaviour of the user login block.
*/
function MYMODULE_form_user_login_block_alter(&$form, $form_state) {
unset($form['#action']);
// removes the forgot password and register links
$form['links'] = array();
// Redirects the user to the image upload page after login
// This cannot be done by a rule, the rule based redirect is only
// working for the login page not the user login block.
$form['#submit'] = array('_MYMODULE_user_login_submit');
}
It doesn't redirect users; it seems like _MYMODULE_user_login_submit() is simply ignored.
What I know already:
I cannot use Rules/Triggers, because I do not login over the login page but the user login block
It is always said: "use logintoboggan" on posts, but there I only have redirection options for "on registration" and "on confirmation", but I need "on authentication" or "after login".
Anyway, I do not want to use more modules, I prefer a few lines of PHP.
Your code doesn't work because user_block_login() sets the "#action" property for the form; in that case, redirecting the form after submission doesn't work.
$form = array(
'#action' => url($_GET['q'], array('query' => drupal_get_destination())),
'#id' => 'user-login-form',
'#validate' => user_login_default_validators(),
'#submit' => array('user_login_submit'),
);
To make it work, you should first unset $form[#action], and then executing the code you already execute in your hook_form_alter() implementation.
As side notes, I will add:
If you want to be sure your code effectively redirect the user where you want, be sure your module is executed for last; if any other module that implements hook_form_alter() adds a form submission handler to redirect the user to a different page, and that module is executed after yours, then your module would not have any effect. To make sure your module is executed after the others, you should use code similar to the following during the installation of the module, or in an update hook. (Replace "MYMODULE" with the short name of the module.)
db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULE');
Instead of using MYMODULE_form_alter(), you can use `MYMODULE_form_user_login_block_alter(), which would not require to check the form ID.
You should append new form submission handlers, instead of replacing the existing ones. This means you should use $form['#submit'][] = 'user_login_submit_redirected';.
Functions implemented in a module should be prefixed with the short name of the module, which means "MYMODULE_" or "_MYMODULE_" (the latter is for private functions). Not using such prefix could create a compatibility issue with other module, such as the User module, as the function you are using has a name starting with "user_."
can u try this please
function user_login_submit_redirected($form, &$form_state) {
global $user;
if ($user->uid == 0) {
$form_state['redirect'] = 'node/admin';
drupal_goto('node/admin') ;
} elseif ($user->uid) {
$form_state['redirect'] = 'node/add/image';
drupal_goto('node/add/image') ;
return;
}
}

Resources