source: sipes/modules_contrib/genpass/genpass.module @ ef72343

stableversion-3.0
Last change on this file since ef72343 was 664c856, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se actualizo el modulo

  • Propiedad mode establecida a 100755
File size: 10.7 KB
Línea 
1<?php
2
3define('GENPASS_DEFAULT', 0);
4define('GENPASS_OPTIONAL', 1);
5define('GENPASS_RESTRICTED', 2);
6
7define('GENPASS_DISPLAY_NONE', 0);
8define('GENPASS_DISPLAY_ADMIN', 1);
9define('GENPASS_DISPLAY_USER', 2);
10define('GENPASS_DISPLAY_BOTH', 3);
11
12/**
13 * Implementation of hook_init().
14 */
15function genpass_init() {
16  drupal_add_css(drupal_get_path('module', 'genpass') . '/genpass.css');
17}
18
19/**
20 * Defines default characters allowed for passwords.
21 */
22function _genpass_default_entropy() {
23  return 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!#$%&()*+,-./:;<=>?@[]^_{|}~';
24}
25
26/**
27 * Generate a new password using the preferred password generation algorithm.
28 *
29 * @return a fresh password.
30 */
31function genpass_generate() {
32  return module_invoke(genpass_algorithm_module(), 'password');
33}
34
35/**
36 * Generate a new password using genpass's internal password generation
37 * algorithm.
38 * Based on the original D6 user_password function (with more characters)
39 *
40 * @return a fresh password according to the settings made in /admin/user/settings
41 *
42 * @see genpass_form_alter()
43 */
44function genpass_password() {
45  $pass = '';
46  $length = variable_get('genpass_length', 8);
47  $allowable_characters = variable_get('genpass_entropy', _genpass_default_entropy());
48
49  // Zero-based count of characters in the allowable list:
50  $len = strlen($allowable_characters) - 1;
51 
52  // Loop the number of times specified by $length.
53  for ($i = 0; $i < $length; $i++) {
54    // Each iteration, pick a random character from the
55    // allowable string and append it to the password:
56    $pass .= $allowable_characters[mt_rand(0, $len)];
57  }
58
59  return $pass;
60}
61
62
63/**
64 * Helper function to find a item in the user form, since its position
65 * within the form-array depends on the profile module (account-category).
66 */
67function &_genpass_get_form_item(&$form, $field) {
68  if (isset($form['account'][$field])) {
69    return $form['account'][$field];
70  }
71  else {
72    return $form[$field];
73  }
74}
75
76/**
77 * Implementation of hook_form_alter()
78 */
79function genpass_form_alter(&$form, $form_state, $form_id) {
80 
81  switch ($form_id) {
82   
83    // User admin settings form
84    case 'user_admin_settings':
85   
86      $form['registration']['genpass_mode'] = array(
87        '#type' => 'radios',
88        '#title' => t('Password handling'),
89        '#default_value' => variable_get('genpass_mode', GENPASS_DEFAULT),
90        '#options' => array(
91          GENPASS_DEFAULT => t('Users must enter a password on registration (default Drupal behaviour).'),
92          GENPASS_OPTIONAL => t('Users may enter a password on registration. If not, a random password will be generated.'),
93          GENPASS_RESTRICTED => t('Users cannot choose a password on registration. It will be generated.')
94        ),
95        '#description' => t('Choose a password handling mode for new users. Note that if "Require e-mail verification when a visitor creates an account" is selected above, then the third option always applies for the regular user registration form. Also note that for manual user creation by an administrator, the second option always applies.'),
96      );
97      $form['registration']['genpass_length'] = array(
98        '#type' => 'textfield',
99        '#title' => t('Generated password length'),
100        '#default_value' => variable_get('genpass_length', 8),
101        '#size' => 2,
102        '#maxlength' => 2,
103        '#description' => t('Set the length of generated passwords here. Allowed range: 5 to 32.'),
104      );
105      $form['registration']['genpass_entropy'] = array(
106        '#type' => 'textfield',
107        '#title' => t('Generated password entropy'),
108        '#default_value' => variable_get('genpass_entropy', _genpass_default_entropy()),
109        '#description' => t('Give a list of possible characters for a generated password. Note that the list must contain at least X different characters where X is defined by the length you have given above.'),
110      );
111      // Provide a selection mechanism to choose the preferred algorithm for
112      // generating passwords. Any module which implements hook_password() is
113      // displayed here.
114      $form['registration']['genpass_algorithm'] = array(
115        '#type' => 'radios',
116        '#title' => t('Password generation algorithm'),
117        '#default_value' => genpass_algorithm_module(),
118        '#options' => genpass_add_samples(genpass_algorithm_modules()),
119        '#description' => t('If third party modules define a password generation algorithm, you can select which one to use. Note that algorithms other than genpass will ignore the preferred entropy and password length. The currently selected algorithm produced the password @pw', array('@pw' => genpass_generate())),
120      );
121      $form['registration']['genpass_display'] = array(
122        '#type' => 'radios',
123        '#title' => t('Generated password display'),
124        '#default_value' => variable_get('genpass_display', GENPASS_DISPLAY_BOTH),
125        '#options' => array(
126          GENPASS_DISPLAY_NONE => t('Do not display.'),
127          GENPASS_DISPLAY_ADMIN => t('Display when site administrators create new user accounts.'),
128          GENPASS_DISPLAY_USER => t('Display when users create their own accounts.'),
129          GENPASS_DISPLAY_BOTH => t('Display to both site administrators and users.'),
130        ),
131        '#description' => t('Whether or not the generated password should display after a user account is created.'),
132      );
133      $form['#validate'][] = 'genpass_user_admin_settings_validate';
134      break;
135   
136    // User registration form
137    case 'user_register':
138      $mode = variable_get('genpass_mode', GENPASS_DEFAULT);
139     
140      // Add validation function, where password may get set
141      $form['#validate'][] = 'genpass_register_validate';
142     
143      // Administrator is creating the user
144      if ($_GET['q'] == 'admin/user/user/create') {
145        // Switch to optional mode
146        $mode = GENPASS_OPTIONAL;
147        // Help avoid obvious consequence of password being optional
148        $notify_item =& _genpass_get_form_item($form, 'notify');
149        $notify_item['#description'] = t('This is recommended when auto-generating the password; otherwise, neither you nor the new user will know the password.');
150      }
151     
152      // Pass mode to validation function
153      $form['genpass_mode'] = array(
154        '#type' => 'value',
155        '#value' => $mode,
156      );
157     
158      $pass_item =& _genpass_get_form_item($form, 'pass');
159      switch ($mode) {
160        // If password is optional, don't require it, and give the user an
161        // indication of what will happen if left blank
162        case GENPASS_OPTIONAL:
163          $pass_item['#required'] = FALSE;
164          $pass_item['#description'] .= (empty($pass_item['#description']) ? '' : $pass_item['#description'] . ' ') . t('If left blank, a password will be generated for you.');
165          break;
166        // If password is restricted, remove access
167        case GENPASS_RESTRICTED:
168          $pass_item['#access'] = FALSE;
169          $pass_item['#required'] = FALSE;
170          break;
171      }
172      break;
173  }
174 
175}
176
177/**
178 * User settings validation.
179 */
180function genpass_user_admin_settings_validate($form, &$form_state) {
181  // Validate length of password
182  $length = $form_state['values']['genpass_length'];
183  if (!is_numeric($length) || $length < 5 || $length > 32) {
184    form_set_error('genpass_length', t('The length of a generated password must be between 5 and 32.'));
185    return;
186  }
187  // Validate allowed characters
188  $chars = array_unique(preg_split('//', $form_state['values']['genpass_entropy'], -1, PREG_SPLIT_NO_EMPTY));
189  if (count($chars) < $length) {
190    form_set_error('genpass_entropy', t('The list of possible characters is not long or unique enough.'));
191    return;
192  }
193  return $form;
194}
195
196/**
197 * User registration validation.
198 */
199function genpass_register_validate($form, &$form_state) {
200  if (empty($form_state['values']['pass']) && !form_get_errors()) {
201   
202    // Generate and set password
203    $pass = genpass_generate();
204    $pass_item =& _genpass_get_form_item($form, 'pass');
205    form_set_value($pass_item, $pass, $form_state);
206
207    $display = variable_get('genpass_display', GENPASS_DISPLAY_BOTH);
208
209    // Administrator created the user.
210    if ($_GET['q'] == 'admin/user/user/create') {
211      $message = t('Since you did not provide a password, it was generated automatically for this account.');
212      if (in_array($display, array(GENPASS_DISPLAY_ADMIN, GENPASS_DISPLAY_BOTH))) {
213        $message .= ' ' . t('The password is: <strong class="genpass-password">!password</strong>', array('!password' => $pass));
214      }
215    }
216    // Optional - User did not provide password, so it was generated.
217    elseif ($form_state['values']['genpass_mode'] == GENPASS_OPTIONAL) {
218      $message = t('Since you did not provide a password, it was generated for you.');
219      if (in_array($display, array(GENPASS_DISPLAY_USER, GENPASS_DISPLAY_BOTH))) {
220        $message .= ' ' . t('Your password is: <strong class="genpass-password">!password</strong>', array('!password' => $pass));
221      }
222    }
223    // Restricted - User was forced to receive a generated password.
224    elseif ($form_state['values']['genpass_mode'] == GENPASS_RESTRICTED && in_array($display, array(GENPASS_DISPLAY_USER, GENPASS_DISPLAY_BOTH))) {
225      $message = t('The following password was generated for you: <strong class="genpass-password">!password</strong>', array('!password' => $pass));
226    }
227
228    if (!empty($message)) {
229      drupal_set_message($message);
230    }
231  }
232  return $form;
233}
234
235/**
236 * Return an array of all modules which implement hook_password.
237 *
238 * @return array of module names.
239 */
240function genpass_algorithm_modules() {
241  // Fetch a list of all modules which implement the password generation hook.
242  // To be in this list, a module must implement a hook, and return random
243  // passwords as strings.
244  $return = array();
245  foreach (module_implements('password') as $module) {
246    $return[$module] = $module;
247  }
248  return $return;
249}
250
251/**
252 * Return the currently activated module for generating passwords. Does some
253 * validation to make sure the variable contains a valid module name.
254 *
255 * @return the name of the module whose implementation of hook_password is
256 *    currently the preferred implementation.
257 */
258function genpass_algorithm_module() {
259  $modules = genpass_algorithm_modules();
260  $module = variable_get('genpass_algorithm', 'genpass');
261 
262  if (in_array($module, array_keys($modules))) {
263    return $module;
264  }
265  else {
266    return 'genpass';
267  }
268}
269
270/**
271 * Adds some sample passwords to each module in an array.
272 */
273function genpass_add_samples($array) {
274  $return = array();
275  foreach ($array as $module => $name) {
276    $return[$module] = $module . ' (' . t('examples') . ': <strong>' . htmlentities(module_invoke($module, 'password')) . '</strong>, <strong>' . htmlentities(module_invoke($module, 'password')) . '</strong>)';
277  }
278  return $return;
279}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.