<?php
// $Id: password_strength.module,v 1.3.2.5.2.1 2009/08/13 21:51:49 jrbeeman Exp $

/**
 * @file
 * Server side checks for newly submittted passwords
 */

/**
 * Implementation of hook_perm().
 */
function password_strength_perm() {
  return array('configure password strength');
}


/**
 * Implementation of hook_menu().
 */
function password_strength_menu() {
  $items = array();

    $items['admin/settings/password_strength'] = array(
      'title' => 'Password strength',
      'description' => 'Configure password strength enforcement rules.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('password_strength_admin_settings'),
      'access callback' => 'user_access',
      'access arguments' => array('configure password strength')
    );
  
  return $items;
}


/**
 * Implementation of hook_help().
 */
function password_strength_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/password_strength':
      return t('<p>The rules below are tested to determine password strength. A <em>high</em> strength password contains:</p>
        <ul>
          <li>letters,</li>
          <li>numbers,</li>
          <li>punctuation,</li>
          <li>both upper- and lower-case letters.</li>
        </ul>
      <p>Minimum length and username match tests do not count toward the "score" of a password. If either of these conditions fails to match the configured settings, the password is immediately rejected.</p>');
    default :
      return;
  }
}


/**
 * Menu callback
 */
function password_strength_admin_settings() {
  $form['rules'] = array(
    '#type' => 'fieldset',
    '#title' => t('Enforcement rules'),
  );
  $form['rules']['password_strength_verify_on_server'] = array(
    '#type' => 'checkbox',
    '#title' => t('Verify password strength on server'),
    '#default_value' => variable_get('password_strength_verify_on_server', 0),
    '#description' => t('Drupal should verify and enforce password strength on the server (i.e. not only in JavaScript).'),
  );
  $form['rules']['password_strength_not_username'] = array(
    '#type' => 'checkbox',
    '#title' => t('Test password not same as username'),
    '#default_value' => variable_get('password_strength_not_username', 1),
  );
  $options = drupal_map_assoc(array(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));
  $form['rules']['password_strength_min_length'] = array(
    '#type' => 'select',
    '#title' => t('Minimum length'),
    '#options' => $options,
    '#default_value' => variable_get('password_strength_min_length', 6),
  );
  $form['rules']['password_strength_min_level'] = array(
    '#type' => 'select',
    '#title' => t('Enforcement level'),
    '#options' => array(
      1 => t('None'),
      2 => t('Low'),
      3 => t('Medium'),
      4 => t('High'),
    ),
    '#default_value' => variable_get('password_strength_min_level', 4),
    '#description' => t('
      <ul>
        <li><em>None:</em> 1 or fewer rules passed.</li>
        <li><em>Low:</em> 2 rules passed.</li>
        <li><em>Medium:</em> 3 rules passed.</li>
        <li><em>High:</em> 4 rules passed.</li>
      </ul>
    '),
  );
  return system_settings_form($form);
}


/**
 * Add the necessary classes, and validation to password_confirm elements
 */
function password_strength_expand_password_confirm($element) {
     
  drupal_add_js(password_strength_js_settings(), 'setting');
  drupal_add_js(drupal_get_path('module', 'password_strength') .'/password_strength.js');
  drupal_add_css(drupal_get_path('module', 'password_strength') .'/password_strength.css');
  
  $strength = variable_get('password_strength_min_level', 4);
  $levels = array(
    1 => t('none'),
    2 => t('low'),
    3 => t('medium'),
    4 => t('high'),
  );

  $element = expand_password_confirm($element);
  $element['pass1']['#attributes'] = array('class' => 'password-field');
  $element['pass2']['#attributes'] = array('class' => 'password-confirm');
  if ($strength > 1) {
    $element['#description'] .= ' '. t('Password must be at least %strength strength.', array('%strength' => $levels[$strength]));
  }

  // Only validate on server if admins want it
  if (variable_get('password_strength_verify_on_server', 0)) {
    $element['#element_validate']= array( 'password_strength_confirm_validate');
  }
  return $element;
}


/**
 * Provide translatable strings and variables to javascript settings
 */
function password_strength_js_settings() {
  global $user;

  return array(
    'passwordStrength' => array(
      'strengthTitle' => t('Password strength:'),
      'lowStrength' => t('Low'),
      'mediumStrength' => t('Medium'),
      'highStrength' => t('High'),
      'requiredStrength' => variable_get('password_strength_min_level', 4),
      'tooShort' => t('It is recommended to choose a password that contains at least %characters. It should include numbers, punctuation, and both upper and lowercase letters.',
       array( '%characters' => format_plural(variable_get('password_strength_min_length', 6), "1 character", "@count characters"),)),
       'needsMoreVariation' => t('The password does not include enough variation to be secure. Try:'),
      'recommendVariation' => t('Your password is strong enough to meet the site requirements, but could be stronger.  If you like, try:'),
      'addLetters' => t('Adding both upper and lowercase letters.'),
      'addNumbers' => t('Adding numbers.'),
      'addPunctuation' => t('Adding punctuation.'),
      'sameAsUsername' => t('It is recommended to choose a password different from the username.'),
      'confirmSuccess' => t('Yes'),
      'confirmFailure' => t('No'),
      'confirmTitle' => t('Passwords match:'),
      'minLength' => variable_get('password_strength_min_length', 6),
      'username' => (isset($user->name) ? $user->name : ''), 
    ),
  );
}


/**
 * Implementation of hook_elements
 */
function password_strength_elements() {
 
  // Override the default password_confirm processor
  $type['password_confirm'] = array('#input' => TRUE, '#process' => array('password_strength_expand_password_confirm'));
  return $type;
}


/**
 * Validate password strength according to configured rules.
 * Confirmation that both passwords provided match is already handled
 * by password_confirm_validate.
 */
function password_strength_confirm_validate($form, &$form_state) {
   
  $pass1 = trim($form_state['values']['pass']['pass1']);
  if (!empty($pass1)) {
    global $user;
    $min_length = variable_get('password_strength_min_length', '6');
    $min_level = variable_get('password_strength_min_level', 4);
    $pass = $form_state['values']['pass']['pass1'];

    $has_letters = preg_match("/[a-zA-Z]/", $pass);
    $has_numbers = preg_match("/[0-9]/", $pass);
    $has_punctuation = preg_match("/[^a-zA-Z0-9]/", $pass);
    $has_casing = preg_match("/[a-z]+.*[A-Z]+|[A-Z]+.*[a-z]/", $pass);

    // Check if length is less than 6 characters.
    if (strlen($pass) < $min_length) {
      form_error($form, t('Password is not long enough. Password must be at least @l characters.', array('@l' => $min_length)));
    }
    
    // Check if password is the same as the username (convert both to lowercase).
    else if (strtolower($pass) == strtolower($user->name) && variable_get('password_strength_not_username', 1)) {
      form_error($form, t('Password cannot be the same as the username.'));
    }
    
    // Password is not secure enough so construct the medium-strength message.
    else {
      // Extremely bad passwords still count as low.
      $count = ($has_letters ? 1 : 0) + ($has_numbers ? 1 : 0) + ($has_punctuation ? 1 : 0) + ($has_casing ? 1 : 0);
      if ($count < $min_level) {
        $msgs = array();
        if (!$has_letters || !$has_casing) {
          $msgs[] = t('Adding both upper and lowercase letters.');
        }
        if (!$has_numbers) {
          $msgs[] = t('Adding numbers.');
        }
        if (!$has_punctuation) {
          $msgs[] = t('Adding punctuation.');
        }
        if (count($msgs)) {
          $msg = t('The password does not include enough variation to be secure. Try:') .'<ul><li>'. implode('</li><li>', $msgs) .'</li></ul>';
          form_error($form, $msg);
        }
      }
    }
  }

  // Password field must be converted from a two-element array into a single
  // string regardless of validation results.
  form_set_value($form['pass1'], NULL, $form_state);
  form_set_value($form['pass2'], NULL, $form_state);
  form_set_value($form, $pass1, $form_state);

  return $form;
}