diff --git a/captcha.module b/captcha.module index 676f362..53676b5 100644 --- a/captcha.module +++ b/captcha.module @@ -220,12 +220,21 @@ function captcha_element_process($element, &$form_state, $complete_form) { '#value' => $captcha_sid, ); - // Additional one time CAPTCHA token: store in database and send with form. - $captcha_token = md5(mt_rand()); - db_update('captcha_sessions') - ->fields(array('token' => $captcha_token)) - ->condition('csid', $captcha_sid) - ->execute(); + $captcha_token = db_select('captcha_sessions', 'c') + ->fields('c', array('token')) + ->condition('csid', $captcha_sid) + ->execute() + ->fetchAssoc(); + $captcha_token = $captcha_token['token']; + if (!isset($captcha_token) && !$form_state['submitted']) { + // Additional one time CAPTCHA token: store in database and send with form. + $captcha_token = md5(mt_rand()); + db_update('captcha_sessions') + ->fields(array('token' => $captcha_token)) + ->condition('csid', $captcha_sid) + ->execute(); + } + $element['captcha_token'] = array( '#type' => 'hidden', '#value' => $captcha_token, @@ -350,7 +359,8 @@ function captcha_form_alter(&$form, &$form_state, $form_id) { // Get placement in form and insert in form. $captcha_placement = _captcha_get_captcha_placement($form_id, $form); _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element); - + // Add #submit functions to invalidate captcha + $form['#submit'][] = 'captcha_submit_invalidate_session'; } } elseif (user_access('administer CAPTCHA settings') && variable_get('captcha_administration_mode', FALSE)) { @@ -415,6 +425,20 @@ function captcha_form_alter(&$form, &$form_state, $form_id) { } /** + * Invalidate CAPTCHA token to avoid reuse. + * @param unknown_type $form + * @param unknown_type $form_state + */ +function captcha_submit_invalidate_session($form, $form_state) { + if (isset($form_state['captcha_info']['captcha_sid'])) { + db_update('captcha_sessions') + ->fields(array('token' => NULL)) + ->condition('csid', $form_state['captcha_info']['captcha_sid']) + ->execute(); + } +} + +/** * CAPTCHA validation function to tests strict equality. * @param $solution the solution of the test. * @param $response the response to the test. @@ -528,10 +552,6 @@ function _captcha_get_posted_captcha_info($element, $form_state, $this_form_id) // Invalidate the CAPTCHA session. $posted_captcha_sid = NULL; } - // Invalidate CAPTCHA token to avoid reuse. - db_update('captcha_sessions') - ->fields(array('token' => NULL)) - ->condition('csid', $posted_captcha_sid); } } else {