/[drupal]/contributions/modules/userprotect/userprotect.module
ViewVC logotype

Contents of /contributions/modules/userprotect/userprotect.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.52 - (show annotations) (download) (as text)
Tue Nov 3 04:25:17 2009 UTC (3 weeks, 5 days ago) by thehunmonkgroup
Branch: MAIN
Changes since 1.51: +5 -5 lines
File MIME type: text/x-php
7.x upgrade -- documentation corrections.
1 <?php
2
3 // $Id: userprotect.module,v 1.51 2009/11/03 00:58:07 thehunmonkgroup Exp $
4
5 /**
6 * Implement hook_help().
7 *
8 * Returns various help texts.
9 */
10 function userprotect_help($path, $arg) {
11 switch ($path) {
12 case 'admin/config/people/userprotect':
13 case 'admin/config/people/userprotect/protected_users':
14 $output = t('These settings override any <a href="!protected_roles">role-based protections</a> for the user in question. For more information on how to configure userprotect settings, see the <a href="!help">help section</a>.', array('!help' => url('admin/help/userprotect'), '!protected_roles' => url('admin/config/people/userprotect/protected_roles')));
15 return $output;
16 case 'admin/config/people/userprotect/protected_roles':
17 $output = t('These settings add protections to any user who is in the specified role. They are overridden by any <a href="!protected_users">per-user protections</a> for the user in question. For more information on how to configure userprotect settings, see the <a href="!help">help section</a>.', array('!help' => url('admin/help/userprotect'), '!protected_users' => url('admin/config/people/userprotect/protected_users')));
18 return $output;
19 case 'admin/config/people/userprotect/administrator_bypass':
20 $output = t('These settings add bypasses to any user who has the \'administer users\' permission. They override the <a href="!protection_defaults">defaults</a> for the user in question. For more information on how to configure userprotect settings, see the <a href="!help">help section</a>.', array('!help' => url('admin/help/userprotect'), '!protection_defaults' => url('admin/config/people/userprotect/protection_defaults')));
21 return $output;
22 case 'admin/config/people/userprotect/protection_defaults':
23 $output = t('Set global default protection values here. For more information on how to configure userprotect settings, see the <a href="!help">help section</a>.', array('!help' => url('admin/help/userprotect')));
24 return $output;
25 case 'admin/help#userprotect':
26
27 $output = t('<p>This module provides various editing protection for users.
28 The protections can be specific to a user, or applied to all users in a role.
29 The following protections are supported:</p>
30 <ul>
31 <li>username</li>
32 <li>e-mail address</li>
33 <li>password</li>
34 <li>status changes</li>
35 <li>roles</li>
36 <li>cancellation</li>
37 <li>OpenID identities (both adding and deleting)</li>
38 <li>all edits (any accessed via user/X/edit)</li>
39 </ul>
40
41 <p>When a protection is enabled for a specified user (or the protection is
42 enabled because the user belongs to a role that has the protection), it
43 prevents the editing operation in question that anyone might try to perform
44 on the user -- unless an administrator who is permitted to bypass the protection
45 is editing the specified user. The module will protect fields by disabling
46 them at user/X/edit.<p>
47
48 <p>User administrators may be configured to bypass specified protections, on either
49 a global or per-administrator basis.</p>
50
51 <p>These protections are valid both when trying to edit the user directly from their
52 user/X/edit page, or using the <a href="!admin_people">mass user editing
53 operations</a>.</p>
54
55 <p>The module also provides protection at the paths user/X/edit and user/X/cancel,
56 should anyone try to visit those paths directly.</p>
57
58 <p><em>Note: this module is compatible with the <a href="!roleassign">
59 RoleAssign</a> module.</em></p>
60
61 <h4>SETTINGS:</h4>
62
63 <p>At the <a href="!userprotect_settings">User Protect settings page</a>,
64 you\'ll find the settings for the module. When the module is initially enabled,
65 the default settings are such:</p>
66
67 <ul>
68 <li>User administrators bypass all protections.</li>
69 <li>The root user specifically bypasses all protections.</li>
70 <li>The anonymous user (uid 0) and root user (uid 1) are protected
71 from all edits, cancellation, and OpenID operations.</li>
72 <li>All role protections are disabled.</li>
73 <li>The \'change own e-mail\', \'change own password\' and \change own openid\'
74 permissions are enabled for authenticated users in the <a href="!permissions">
75 User Protect permissions settings</a>.
76 </ul>
77
78 <p>This effectively amounts to no protections. It is suggested that you turn off
79 as many default administrator bypass settings as possible, and set bypass settings
80 for specific user administrators -- this allows you to take advantage
81 of the status, roles, cancellation, openid and edit protections in a meaningful
82 way. Because of the per-user bypass/protection settings for the anonymous and
83 root user, this will also begin protecting those users, without compromising
84 the root user\'s access to the entire site.</p>
85
86 <p>Important note: In order to protect a user from cancellation (by visiting
87 user/X/cancel directly) and/or OpenID edits (by visiting user/X/openid
88 directly), you must enable the \'cancel\' and/or \'openid\' protection specifically.
89 Enabling \'all account edits\' does not enable these protections!</p>
90
91 <p>Also note that this module only provides protection against actions via the website
92 interface--operations that a module takes directly are not protected! This module
93 should play well with other contributed modules, but there is no guarantee that all
94 protections will remain intact if you install modules outside of the drupal core
95 installation.</p>
96
97 <h4>ADDING PROTECTIONS FOR A SINGLE USER:</h4>
98
99 <p>This is done at <a href="!protected_users">per-user protections</a>.
100 Any time a user is added for protection, they will initially receive the
101 <a href="!protection_defaults">default protections</a>.</p>
102
103
104 <h4>ADDING PROTECTIONS FOR ROLES:</h4>
105
106 <p>This is done at <a href="!protected_roles">role-based protections</a>.
107 <em>Be cautious</em> about adding protections by role, or you can lock out users
108 from things unintentionally!</p>
109
110 <p>In particular, note the if you enable role protections for a specific role, and
111 you have no bypasses enabled, you\'ve effectively locked out any role editing for
112 that role by anybody, unless you come back to the settings page and disable the role
113 protection!</p>
114
115 <h4>ADDING ADMINISTRATOR BYPASS RULES:</h4>
116
117 <p>One of the more powerful features of the module is administrator bypass
118 Any user that has been granted the \'administer users\' permission can
119 be configured to bypass any protection, either via the
120 <a href="!protection_defaults">default administrator bypass settings</a>,
121 or via a <a href="!administrator_bypass">per-administrator setting</a>.
122 If a bypass is enabled for a user administrator, they will be given editing rights
123 on that protection regardless if it is enabled for a single user or an entire role.</p>
124
125 <p>Note that the per-administrator bypass settings override the default bypass
126 settings.</p>
127
128 <h4>DEFAULT PROTECTION SETTINGS:</h4>
129
130 <p>Set the <a href="!protection_defaults">default protections</a> for newly protected users.
131 In addition, you can enable the auto-protect feature, which will automatically
132 add the default protections to any newly created user accounts, and set default
133 bypass options for all user administrators.</p>
134
135
136 <h4>HOW THE MODULE DETERMINES A PROTECTION:</h4>
137
138 <p>In order to properly use User Protect, it\'s important to understand how the
139 module determines if a specified field is to be protected. Here is the basic
140 logic:</p>
141 <ol>
142 <li>If the current user is a user administrator, check if they have
143 per-administrator bypass settings. If so, then check to see if they are allowed
144 to bypass the protection. If so, then stop the checks and allow editing
145 of the field.</li>
146 <li>If not, then if the current user is a user administrator, check if the
147 default administrator bypass is enabled for the protection in question. If
148 so, then stop the checks and allow editing of the field.
149 <li>If not, check if the user is editing their own account. If so, determine
150 the protections for e-mail, password, and openid by examining the userprotect permissions
151 for \'change own e-mail\', \'change own password\' and \'change own openid\',
152 then continue with the rest of the checks below.
153 <li>If not, check if the protection is set for the individual user being edited.
154 If so, then stop the checks here, and prevent editing of the field (this effectively
155 means that individual protections override role protections).</li>
156 <li>If not, then examine all the roles for the user being edited. If any of
157 those roles have the protection enabled, then prevent editing of the field.</li>
158 <li>If not, then allow the field to be edited.</li>
159 </ol>
160 </p>', array('!admin_people' => url('admin/people'), '!userprotect_settings' => url('admin/config/people/userprotect/protected_users'), '!protected_users' => url('admin/config/people/userprotect/protected_users'), '!protected_roles' => url('admin/config/people/userprotect/protected_roles'), '!administrator_bypass' => url('admin/config/people/userprotect/administrator_bypass'), '!protection_defaults' => url('admin/config/people/userprotect/protection_defaults'), '!roleassign' => url('http://drupal.org/project/roleassign', array('attributes' => array('target' => 'X'), 'absolute' => TRUE)), '!permissions' => url('admin/config/people/permissions', array('fragment' => 'module-userprotect'))));
161 return $output;
162 }
163 }
164
165 /**
166 * Implement hook_form_alter().
167 */
168 function userprotect_form_alter(&$form, &$form_state, $form_id) {
169
170 switch ($form_id) {
171
172 // These are complex cases, and are best handled by manipulating the form values
173 // in a custom validate function.
174 case 'user_admin_account':
175 case 'user_multiple_cancel_confirm':
176 // Ensure an array.
177 $form['#validate'] = isset($form['#validate']) ? $form['#validate'] : array();
178 array_unshift($form['#validate'], 'userprotect_user_admin_account_validate');
179 break;
180 case 'openid_user_add':
181 case 'openid_user_delete_form':
182 $account = user_load(arg(1));
183 $protected = array();
184 if (!userprotect_check_bypass('up_openid') && userprotect_get_user_protection($account, 'up_openid')) {
185 switch ($form_id) {
186 case 'openid_user_add':
187 if (isset($form['openid_identifier'])) {
188 $form['openid_identifier']['#disabled'] = TRUE;
189 $form['submit']['#disabled'] = TRUE;
190 }
191 break;
192 case 'openid_user_delete_form':
193 if (isset($form['actions']['submit'])) {
194 $form['actions']['submit']['#disabled'] = TRUE;
195 $form['confirm']['#value'] = 0;
196 }
197 break;
198 }
199 $protected['up_openid'] = TRUE;
200 }
201 userprotect_form_display_protections($account, $protected);
202 break;
203 }
204 }
205
206
207 /**
208 * Implement hook_form_user_profile_form_alter().
209 */
210 function userprotect_form_user_profile_form_alter(&$form, &$form_state) {
211
212 // For each of the fields, first check if any of the user's roles are protecting
213 // it, then check if the user themselves is protected from it. if either is TRUE,
214 // then disable the field, and mark a fixed form value so it will be properly submitted.
215 $account = user_load(arg(1));
216 $protected = array();
217 if (isset($form['account']['name']) && !userprotect_check_bypass('up_name') && userprotect_get_user_protection($account, 'up_name')) {
218 // If for some reason this field has no initial value, then don't protect it.
219 if ($account->name) {
220 $form['account']['name']['#disabled'] = TRUE;
221 $form['account']['name']['#value'] = $account->name;
222 $protected['up_name'] = TRUE;
223 }
224 }
225 if (isset($form['account']['mail']) && !userprotect_check_bypass('up_mail') && userprotect_get_user_protection($account, 'up_mail')) {
226 // If for some reason this field has no initial value, then don't protect it.
227 if ($account->mail) {
228 $form['account']['mail']['#disabled'] = TRUE;
229 $form['account']['mail']['#value'] = $account->mail;
230 $protected['up_mail'] = TRUE;
231 }
232 }
233 // Password is an exception, as it needs no value, Just unset it, as
234 // there's no need to display two empty boxes that are disabled.
235 if (isset($form['account']['pass']) && !userprotect_check_bypass('up_pass') && userprotect_get_user_protection($account, 'up_pass')) {
236 unset($form['account']['pass']);
237 $protected['up_pass'] = TRUE;
238 }
239 if (isset($form['account']['status']) && !userprotect_check_bypass('up_status') && userprotect_get_user_protection($account, 'up_status')) {
240 $form['account']['status']['#disabled'] = TRUE;
241 $form['account']['status']['#value'] = $account->status;
242 $protected['up_status'] = TRUE;
243 }
244 // Special hack for RoleAssign module compatibility.
245 if (isset($form['account']['roleassign_roles'])) {
246 $roles = 'roleassign_roles';
247 }
248 else {
249 $roles = 'roles';
250 }
251 // Roles is a special case, since it's a tree'd item that needs values.
252 // We'll handle that in a custom validation function. Also here we slip
253 // the user's account info into the form so it's available to gleen the role
254 // info from.
255 if (isset($form['account'][$roles]) && !userprotect_check_bypass('up_roles') && userprotect_get_user_protection($account, 'up_roles')) {
256 $form['account'][$roles]['#disabled'] = TRUE;
257 // Ensure an array.
258 $form['account'][$roles]['#element_validate'] = isset($form['account'][$roles]['#element_validate']) ? $form['account'][$roles]['#element_validate'] : array();
259 array_unshift($form['account'][$roles]['#element_validate'], 'userprotect_user_edit_fields_validate');
260 $form_state['userprotect']['account'] = $account;
261 $form_state['userprotect']['field'] = 'roles';
262 $protected['up_roles'] = TRUE;
263 }
264
265 // At this point, we only need the userprotect-specific validation if the
266 // current user and the edited user are not the same.
267 if (isset($form['cancel']) && ($GLOBALS['user']->uid != $account->uid)) {
268 // Nothing special for cancel--just disable.
269 if (!userprotect_check_bypass('up_cancel') && userprotect_get_user_protection($account, 'up_cancel')) {
270 $form['cancel']['#disabled'] = TRUE;
271 $protected['up_cancel'] = TRUE;
272 }
273 }
274 userprotect_form_display_protections($account, $protected);
275 }
276
277 /**
278 * Custom validation function for complex field protections.
279 */
280 function userprotect_user_edit_fields_validate($form, &$form_state) {
281 $account = $form_state['userprotect']['account'];
282 $field = $form_state['userprotect']['field'];
283
284 switch ($field) {
285 case 'roles':
286 // Authenticated user isn't a valid checked item.
287 unset($account->roles[DRUPAL_AUTHENTICATED_RID]);
288 // Add values for all role checkboxes that are valid roles for this user.
289 foreach ($account->roles as $rid => $role) {
290 if (isset($form[$rid])) {
291 form_set_value($form[$rid], 1, $form_state);
292 }
293 }
294 break;
295 }
296 }
297
298 /**
299 * Implement hook_menu().
300 */
301 function userprotect_menu() {
302 $items = array();
303 $admin = array('administer userprotect');
304
305 // Admin page link.
306 $items['admin/config/people/userprotect'] = array(
307 'title' => 'User Protect',
308 'page callback' => 'drupal_get_form',
309 'page arguments' => array('userprotect_protected_users'),
310 'access callback' => 'user_access',
311 'access arguments' => $admin,
312 'description' => t('Protect inidividual users and/or roles from editing operations.'),
313 );
314 // Default tab.
315 $items['admin/config/people/userprotect/protected_users'] = array(
316 'title' => 'Protected users',
317 'type' => MENU_DEFAULT_LOCAL_TASK,
318 'access callback' => 'user_access',
319 'access arguments' => $admin,
320 'weight' => 1,
321 );
322 // Protected roles tab.
323 $items['admin/config/people/userprotect/protected_roles'] = array(
324 'title' => 'Protected roles',
325 'page callback' => 'drupal_get_form',
326 'page arguments' => array('userprotect_protected_roles'),
327 'access callback' => 'user_access',
328 'access arguments' => $admin,
329 'type' => MENU_LOCAL_TASK,
330 'weight' => 2,
331 );
332 // Administrator bypass tab.
333 $items['admin/config/people/userprotect/administrator_bypass'] = array(
334 'title' => 'Administrator bypass',
335 'page callback' => 'drupal_get_form',
336 'page arguments' => array('userprotect_administrator_bypass'),
337 'access callback' => 'user_access',
338 'access arguments' => $admin,
339 'type' => MENU_LOCAL_TASK,
340 'weight' => 3,
341 );
342 // Default settings.
343 $items['admin/config/people/userprotect/protection_defaults'] = array(
344 'title' => 'Protection defaults',
345 'page callback' => 'drupal_get_form',
346 'page arguments' => array('userprotect_protection_defaults'),
347 'access callback' => 'user_access',
348 'access arguments' => $admin,
349 'type' => MENU_LOCAL_TASK,
350 'weight' => 4,
351 );
352 // Remove a user from being protected.
353 $items['userprotect/delete'] = array(
354 'title' => 'Delete protected user',
355 'page callback' => 'userprotect_protected_users_delete',
356 'type' => MENU_CALLBACK,
357 'access callback' => 'user_access',
358 'access arguments' => $admin,
359 );
360
361 return $items;
362 }
363 /**
364 * Implement hook_menu_alter().
365 *
366 * Since we also have to guard against menu items being called
367 * directly from a URL, this page check is necessary. The checks
368 * are invoked for user/x/edit and user/x/cancel, and replace user
369 * modules's default access checks.
370 */
371 function userprotect_menu_alter(&$callbacks) {
372 $callbacks['user/%user/edit']['access callback'] = 'userprotect_user_edit_access';
373 $callbacks['user/%user/cancel']['access callback'] = 'userprotect_user_cancel_access';
374 }
375
376 /**
377 * Access callback for user edit pages.
378 *
379 * This replaces user_edit_access from user.module.
380 *
381 * @param $account
382 * An object representing the user to be edited.
383 */
384 function userprotect_user_edit_access($account) {
385 // Perform core's access check.
386 if ((($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0) {
387 // Check to see if the user's roles are protecting edits, or the user
388 // account itself is protected.
389 if (!userprotect_check_bypass('up_edit') && userprotect_get_user_protection($account, 'up_edit')) {
390 // If so, and we're at /user/X/edit, set a message.
391 if (arg(0) == 'user' && is_numeric(arg(1)) && arg(2) == 'edit') {
392 drupal_set_message(t('%user is currently being protected from any edits.', array('%user' => $account->name)), 'error');
393 }
394 return FALSE;
395 }
396 else {
397 return TRUE;
398 }
399 }
400 else {
401 return FALSE;
402 }
403 }
404
405 /**
406 * Access callback for user cancel pages.
407 *
408 * This replaces the logic from user.module.
409 *
410 * @param $account
411 * An object representing the user to be cancelled.
412 */
413 function userprotect_user_cancel_access($account) {
414 // Perform core's access check.
415 if (((($GLOBALS['user']->uid == $account->uid) && user_access('cancel account')) || user_access('administer users')) && $account->uid > 0) {
416 // At this point, we only need the userprotect-specific validation if:
417 // 1. The current user and the edited user are not the same.
418 // 2. The current user is a user administrator.
419 if (($GLOBALS['user']->uid != $account->uid) && user_access('administer users')) {
420 // Check to see if the user's roles are protecting cancellation, or the user
421 // account itself is protected.
422 if (!userprotect_check_bypass('up_cancel') && userprotect_get_user_protection($account, 'up_cancel')) {
423 // If so, and we're at /user/X/cancel, set a message.
424 if (arg(0) == 'user' && is_numeric(arg(1)) && arg(2) == 'cancel') {
425 drupal_set_message(t('%user is currently being protected from cancellation.', array('%user' => $account->name)), 'error');
426 }
427 return FALSE;
428 }
429 }
430 else {
431 return TRUE;
432 }
433 }
434 else {
435 return FALSE;
436 }
437 }
438
439 /**
440 * Implement hook_permission().
441 */
442 function userprotect_permission() {
443 return array(
444 'change own e-mail' => array(
445 'title' => t('Change own e-mail'),
446 'description' => t('Allow users to edit their own e-mail address.'),
447 ),
448 'change own password' => array(
449 'title' => t('Change own password'),
450 'description' => t('Allow users to edit their own password.'),
451 ),
452 'change own openid' => array(
453 'title' => t('Change own OpenID'),
454 'description' => t('Allow users to edit their own OpenID identities.'),
455 ),
456 'administer userprotect' => array(
457 'title' => t('Administer User Protect'),
458 'description' => t('Set up access rules for user administrators for various user-related edits.'),
459 ),
460 );
461 }
462
463 /**
464 * Implement hook_theme().
465 */
466 function userprotect_theme() {
467 return array(
468 'userprotect_admin_role_table' => array(
469 'render element' => 'form',
470 ),
471 'userprotect_protections_bypass' => array(
472 'render element' => 'form',
473 ),
474 );
475 }
476
477 /**
478 * Implement hook_user_insert().
479 */
480 function userprotect_user_insert(&$edit, $account) {
481
482 // A new user is being added. If auto-protect is enabled, then add protection.
483 if (variable_get('userprotect_autoprotect', FALSE)) {
484 userprotect_add_user($account->uid, 'user');
485 $protected = array_filter(variable_get('userprotect_protection_defaults', userprotect_user_protection_defaults()));
486 drupal_set_message(userprotect_display_protections($account, $protected));
487 }
488 }
489
490
491 /**
492 * Implement hook_user_cancel().
493 */
494 function userprotect_user_cancel($edit, $account, $method) {
495 switch ($method) {
496 // Remove a deleted user from the protections table.
497 case 'user_cancel_reassign':
498 case 'user_cancel_delete':
499 db_delete('userprotect')
500 ->condition('uid', $account->uid)
501 ->execute();
502 break;
503 }
504 }
505
506 /**
507 * Builds a table of protected users, and their protections.
508 *
509 * @return A form array representing the table.
510 */
511 function userprotect_protected_users() {
512 return userprotect_protections_bypass('user');
513 }
514
515 /**
516 * Builds a table of user admin bypass values.
517 *
518 * @return A form array representing the table.
519 */
520 function userprotect_administrator_bypass() {
521 return userprotect_protections_bypass('admin');
522 }
523
524 /**
525 * Helper funtion. Builds tables for protected users and admin bypass.
526 *
527 * @return A form array representing the table.
528 */
529 function userprotect_protections_bypass($type) {
530
531 // Build the header.
532 $header = array(array('data' => t('User'), 'field' => 'name', 'sort' => 'asc'));
533
534 $protect_columns = userprotect_get_protection_display();
535 foreach ($protect_columns as $field => $data) {
536 $header[] = array('data' => $data, 'field' => $field);
537 }
538 $header[] = array('data' => t('Operations'));
539
540 $query = db_select('userprotect', 'up');
541 $query->innerJoin('users', 'u', 'up.uid = u.uid');
542 $query->condition('up.up_type', $type);
543
544 $count_query = clone $query;
545 $count_query->addExpression('COUNT(DISTINCT u.uid)');
546
547 $query = $query->extend('PagerDefault')->extend('TableSort');
548
549 // These are all protection fields in the database.
550 $protection_fields = array_keys(userprotect_get_protection_display());
551
552 // Grab the protected users.
553 $query
554 ->fields('up', $protection_fields)
555 ->fields('u', array('uid', 'name'))
556 ->limit(25)
557 ->orderByHeader($header)
558 ->setCountQuery($count_query);
559 $protected_users = $query->execute();
560
561 // Set some initial values.
562 $delete = t('delete');
563 $options = array();
564
565 // These are all available protections.
566 $protections = array_keys(userprotect_user_protection_defaults());
567
568 // Pass in the header and list of protections to the form so they'll be available
569 // to the theming function.
570 $form = array();
571 $form['protection']['#tree'] = TRUE;
572 $form['#header'] = $header;
573 $form['#protections'] = $protections;
574 $form['#submit'][] = 'userprotect_protections_bypass_submit';
575 $form['#theme'] = 'userprotect_protections_bypass';
576
577 // Build the checkboxes options.
578 foreach ($protections as $protection) {
579 $options[$protection] = '';
580 }
581
582 // For each protected user, build their table row.
583 foreach ($protected_users as $protected_user) {
584 $defaults = array();
585
586 $user = user_load($protected_user->uid);
587
588 $form['user'][$user->uid]['uid'] = array(
589 '#type' => 'value',
590 '#value' => $user->uid
591 );
592 $form[$user->uid]['name'] = array(
593 '#theme' => 'username',
594 '#account' => $user,
595 );
596 $form[$user->uid]['operations'] = array('#markup' => $user->uid ? l($delete, "userprotect/delete/$user->uid/$type") : '');
597 // Build the protections for the user row.
598 foreach ($protections as $protection) {
599 if ($protected_user->$protection) {
600 $defaults[] = $protection;
601 }
602 }
603
604 // The checkboxes for this user.
605 $form['protection'][$user->uid] = array(
606 '#type' => 'checkboxes',
607 '#options' => $options,
608 '#default_value' => $defaults,
609 );
610 }
611
612 // An autocomplete field to add new users for protection.
613 // This needs a custom validation function to check the user
614 // to be added.
615 $form['up_add'] = array(
616 '#type' => 'textfield',
617 '#maxlength' => 60,
618 '#autocomplete_path' => 'user/autocomplete',
619 '#element_validate' => array('userprotect_up_add_validate'),
620 '#userprotect_type' => $type,
621 );
622 $form['up_add_text'] = array('#markup' => t('Add user'),);
623 $form['userprotect_type'] = array(
624 '#type' => 'value',
625 '#value' => $type,
626 );
627
628 $form['pager'] = array(
629 '#theme' => 'pager',
630 '#tags' => NULL,
631 );
632
633 $form['submit'] = array(
634 '#type' => 'submit',
635 '#value' => t('Save')
636 );
637 return $form;
638 }
639
640 /**
641 * Themes the protected users table.
642 *
643 * @param $form The form to theme.
644 * @return An HTML string representing the constructed form.
645 */
646 function theme_userprotect_protections_bypass($variables) {
647 $form = $variables['form'];
648 $rows = array();
649 // Buikd the row for each user.
650 foreach (element_children($form['user']) as $uid) {
651 $row = array();
652 $row[] = drupal_render($form[$uid]['name']);
653 // Build the protections for the user row.
654 foreach ($form['#protections'] as $protection) {
655 $row[] = drupal_render($form['protection'][$uid][$protection]);
656 }
657 $row[] = drupal_render($form[$uid]['operations']);
658 $rows[] = $row;
659 }
660
661 // Add the last row with the add textfield.
662 $rows[] = array(
663 array('data' => drupal_render($form['up_add']), 'colspan' => strval(count($form['#header']) - 1)),
664 array('data' => drupal_render($form['up_add_text']), 'colspan' => '1')
665 );
666
667 // Theme the table.
668 $output = theme('table', array('header' => $form['#header'], 'rows' => $rows));
669 $output .= drupal_render_children($form);
670
671 return $output;
672 }
673
674 /**
675 * Custom validation function for adding a user for protection.
676 */
677 function userprotect_up_add_validate($form, &$form_state) {
678 // If a user has been submitted
679 if ($username = $form['#value']) {
680 $type = $form['#userprotect_type'];
681 // If the user is valid, and they are not already being protected...
682 if ($uid = db_query("SELECT uid FROM {users} WHERE name = :name", array(
683 ':name' => $username,
684 ))->fetchField()) {
685 if (!db_query("SELECT uid FROM {userprotect} WHERE uid = :uid AND up_type = :up_type", array(
686 ':uid' => $uid,
687 ':up_type' => $type,
688 ))->fetchField()) {
689 if ($uid != 1 && $type == 'admin' && !db_query("SELECT ur.uid FROM {users_roles} ur INNER JOIN {role_permission} rp ON ur.rid = rp.rid WHERE rp.permission = :permission AND ur.uid = :uid", array(
690 ':permission' => 'administer users',
691 ':uid' => $uid,
692 ))->fetchField()) {
693 form_set_error('up_add', t('%user does not have user administration privileges.', array('%user' => $username)));
694 }
695 else {
696 // Transform the username into a uid.
697 form_set_value($form, $uid, $form_state);
698 }
699 }
700 // Can't add a user twice
701 else {
702 form_set_error('up_add', t('%user is already on this list.', array('%user' => $username)));
703 }
704
705 }
706 // Can't add a user that doesn't exist.
707 else {
708 form_set_error('up_add', t('The username is invalid.'));
709 }
710 }
711 }
712
713 /**
714 * Processes the submitted user protection form.
715 */
716 function userprotect_protections_bypass_submit($form, &$form_state) {
717
718 $type = $form_state['values']['userprotect_type'];
719
720 // A user was added, so add them to the protected users table.
721 if ($uid = $form_state['values']['up_add']) {
722 userprotect_add_user($uid, $type);
723 $username = userprotect_get_username($uid);
724 if ($type == 'user') {
725 drupal_set_message(t('%user is now protected.', array('%user' => $username)));
726 }
727 elseif ($type == 'admin') {
728 drupal_set_message(t('%user now has bypass capabilities matching the default protections for newly protected users.', array('%user' => $username)));
729 }
730 }
731 if (is_array($form_state['values']['protection'])) {
732 // Load the defaults as a reference to all protections.
733 $protections_values = userprotect_user_protection_defaults();
734 // Loop through each user.
735 foreach ($form_state['values']['protection'] as $uid => $protections) {
736 $fields = array();
737 // Loop through the submitted user's protections, setting them enabled or
738 // disabled as appropriate for the update query. Note: $protection is
739 // a module generated string, so it's safe.
740 foreach ($protections_values as $protection => $value) {
741 $fields[$protection] = $protections[$protection] ? 1 : 0;
742 }
743
744 // Update the user's protections.
745 db_update('userprotect')
746 ->fields($fields)
747 ->condition('uid', $uid)
748 ->condition('up_type', $type)
749 ->execute();
750 }
751 if ($type == 'user') {
752 drupal_set_message(t('Protection settings updated.'));
753 }
754 elseif ($type == 'admin') {
755 drupal_set_message(t('Bypass settings updated.'));
756 }
757 }
758 }
759
760 /**
761 * Menu callback. Removes a user from being protected.
762 *
763 * @param $uid The user ID to remove.
764 */
765 function userprotect_protected_users_delete($uid, $type) {
766 if ($uid) {
767 db_delete('userprotect')
768 ->condition('uid', $uid)
769 ->condition('up_type', $type)
770 ->execute();
771 $username = userprotect_get_username($uid);
772 if ($type == 'user') {
773 drupal_set_message(t('%user is no longer protected.', array('%user' => $username)));
774 drupal_goto('admin/config/people/userprotect/protected_users');
775 }
776 elseif ($type == 'admin') {
777 drupal_set_message(t('%user is no longer enabled for bypass.', array('%user' => $username)));
778 drupal_goto('admin/config/people/userprotect/administrator_bypass');
779 }
780 }
781 else {
782 drupal_set_message(t('Invalid selection.'), 'error');
783 drupal_goto('admin/config/people/userprotect');
784 }
785 }
786
787 /**
788 * Builds a form for the role protection settings.
789 *
790 * @return An array representing the form.
791 */
792 function userprotect_protected_roles() {
793
794 $form = array();
795
796 // Get the list of all protections, and the current default settings.
797 $options = userprotect_get_protection_display();
798
799 // Build the header.
800 $header = array(t('Role'));
801 foreach ($options as $field => $data) {
802 $header[] = $data;
803 }
804
805 // Grab all roles but the anonymous role, and grab the current default settings.
806 $roles = user_roles(TRUE);
807 $protected_roles = variable_get('userprotect_role_protections', array());
808
809 // This is a complete list of protections for reference.
810 $protections = array_keys(userprotect_user_protection_defaults());
811
812 // Pass in the header and protections so they're available for the theme function.
813 // Also, we want this as one big array to save in the variables table, so tree it.
814 $form['role_table']['#header'] = $header;
815 $form['role_table']['#theme'] = 'userprotect_admin_role_table';
816 $form['role_table']['#protections'] = $protections;
817 $form['role_table']['userprotect_role_protections']['#tree'] = TRUE;
818
819 // Build a row for each role.
820 foreach ($roles as $rid => $role) {
821 $form['role_table']['userprotect_role_protections'][$rid]['name'] = array('#markup' => $role);
822 // Build protections for the row.
823 foreach ($protections as $protection) {
824 $form['role_table']['userprotect_role_protections'][$rid][$protection] = array(
825 '#type' => 'checkbox',
826 );
827 if (isset($protected_roles[$rid][$protection])) {
828 $form['role_table']['userprotect_role_protections'][$rid][$protection]['#default_value'] = $protected_roles[$rid][$protection];
829 }
830 }
831 }
832
833 return system_settings_form($form);
834 }
835
836 /**
837 * Builds a form for the userprotect default settings.
838 *
839 * @return An array representing the form.
840 */
841 function userprotect_protection_defaults() {
842
843 // Get the list of all protections, and the current default settings.
844 $options = userprotect_get_protection_display();
845 $current_defaults = variable_get('userprotect_protection_defaults', userprotect_user_protection_defaults());
846
847 // Transform the defaults into proper checkboxes defaults.
848 $defaults = array_keys(array_filter($current_defaults));
849
850 // A set of checkboxes that lists the default protection settings.
851 $form['userprotect_protection_defaults'] = array(
852 '#type' => 'checkboxes',
853 '#title' => t('User protection defaults'),
854 '#description' => t('The selected protections will be assigned to users when they are first added for protection.'),
855 '#options' => $options,
856 '#default_value' => $defaults,
857 );
858 // A checkbox to enable the auto-protect functionality.
859 $form['userprotect_autoprotect'] = array(
860 '#type' => 'checkbox',
861 '#title' => t('Auto-protect new users'),
862 '#description' => t('If selected, all newly created users will automatically be protected and assigned the default protections above.'),
863 '#default_value' => variable_get('userprotect_autoprotect', FALSE),
864 );
865 // A set of checkboxes that lists the default protection settings.
866 $form['userprotect_administrator_bypass_defaults'] = array(
867 '#type' => 'checkboxes',
868 '#title' => t('Administrator bypass defaults'),
869 '#description' => t('If selected, all users with the \'administer users\' permission will be allowed to bypass the protection<br \><em>Note: this default setting is overridden by the <a href="!per_user_bypass">per-user administrator bypass settings</a>.</em>.', array('!per_user_bypass' => url('admin/config/people/userprotect/administrator_bypass'))),
870 '#options' => $options,
871 '#default_value' => variable_get('userprotect_administrator_bypass_defaults', userprotect_administrator_bypass_defaults()),
872 );
873
874 return system_settings_form($form);
875 }
876
877 /**
878 * Themes the role protections table.
879 *
880 * @param $form The form for the table.
881 * @return An HTML string representing the table.
882 */
883 function theme_userprotect_admin_role_table($variables) {
884 $form = $variables['form'];
885 $rows = array();
886 // Build a row for each role
887 foreach (element_children($form['userprotect_role_protections']) as $rid) {
888 $row = array();
889 $row[] = drupal_render($form['userprotect_role_protections'][$rid]['name']);
890 // Build the protections for each row.
891 foreach ($form['#protections'] as $protection) {
892 $row[] = drupal_render($form['userprotect_role_protections'][$rid][$protection]);
893 }
894 $rows[] = $row;
895 }
896
897 // Theme the table.
898 $output = t('<h3>Protections by role</h3>');
899 $output .= theme('table', array('header' => $form['#header'], 'rows' => $rows));
900 $output .= t('<div class="description">Setting a protection for a role will enable that protection for all users in the role.</div>');
901 $output .= drupal_render_children($form);
902
903 return $output;
904 }
905
906 /**
907 * Custom validation function for protecting users from the user
908 * administration operations.
909 */
910 function userprotect_user_admin_account_validate($form, &$form_state) {
911
912 // Get the checked users, and the operation name.
913 $uids = array_filter($form_state['values']['accounts']);
914 $operation_rid = explode('-', $form_state['values']['operation']);
915 $operation = $operation_rid[0];
916
917 // Perform the check for each submitted user.
918 foreach ($uids as $uid) {
919 $account = user_load($uid);
920
921 switch ($operation) {
922 case 'block':
923 case 'unblock':
924 // Check to see if any of the user's roles are protected from status changes,
925 // then check to see if the user is protected.
926 if (!userprotect_check_bypass('up_status') && userprotect_get_user_protection($account, 'up_status')) {
927 // If so, then unset the checked user so they will not be processed, and display a warning.
928 form_set_value($form['accounts'][$uid], 0, $form_state);
929 drupal_set_message(t('%user is protected from status changes, and was not updated.', array('%user' => $account->name)), 'error');
930 unset($uids[$uid]);
931 }
932 break;
933 case 'cancel':
934 // Check to see if any of the user's roles are protected from cancellation,
935 // then check to see if the user is protected.
936 if (!userprotect_check_bypass('up_cancel') && userprotect_get_user_protection($account, 'up_cancel')) {
937 // If so, then unset the checked user so they will not be processed, and display a warning.
938 // Note that the array element has to be completely removed here in order to prevent the
939 // user from being cancelled, due to the nature of the mass cancellation callback.
940 unset($form_state['values']['accounts'][$uid]);
941 drupal_set_message(t('%user is protected from cancellation, and was not cancelled.', array('%user' => $account->name)), 'error');
942 unset($uids[$uid]);
943 }
944 break;
945 case 'add_role':
946 case 'remove_role':
947 // RoleAssign module compatibility hack.
948 case 'roleassign_add_role':
949 case 'roleassign_remove_role':
950 // Check to see if any of the user's roles are protected from status changes,
951 // then check to see if the user is protected.
952 if (!userprotect_check_bypass('up_roles') && userprotect_get_user_protection($account, 'up_roles')) {
953 // If so, then unset the checked user so they will not be processed, and display a warning.
954 form_set_value($form['accounts'][$uid], 0, $form_state);
955 drupal_set_message(t('%user is protected from role changes, and was not updated.', array('%user' => $account->name)), 'error');
956 unset($uids[$uid]);
957 }
958 break;
959 }
960 }
961
962 // If we've unset all of the users that were checked, then don't continue
963 // with the form processing.
964 if (!count($uids)) {
965 drupal_set_message('No users selected.', 'error');
966 drupal_goto('admin/people');
967 }
968 }
969
970 /**
971 * Builds an array of the inital default protections.
972 *
973 * @return The default protections array.
974 */
975 function userprotect_user_protection_defaults() {
976 return array('up_name' => 0,
977 'up_mail' => 0,
978 'up_pass' => 0,
979 'up_status' => 1,
980 'up_roles' => 0,
981 'up_openid' => 0,
982 'up_cancel' => 1,
983 'up_edit' => 0,
984 );
985 }
986
987 /**
988 * Builds an array of the inital default bypass settings for user admins.
989 *
990 * @return The default bypass array.
991 */
992 function userprotect_administrator_bypass_defaults() {
993
994 $defaults = array();
995 $protections = userprotect_user_protection_defaults();
996 foreach ($protections as $protection => $value) {
997 $defaults[$protection] = $protection;
998 }
999
1000 return $defaults;
1001 }
1002
1003 /**
1004 * Builds an array of all protections and their human-readable text string.
1005 *
1006 * @return The constructed array.
1007 */
1008 function userprotect_get_protection_display() {
1009 return array('up_name' => t('username'),
1010 'up_mail' => t('e-mail'),
1011 'up_pass' => t('password'),
1012 'up_status' => t('status'),
1013 'up_roles' => t('roles'),
1014 'up_openid' => t('openid'),
1015 'up_cancel' => t('cancel'),
1016 'up_edit' => t('all account edits'),
1017 );
1018 }
1019
1020 /**
1021 * Conditionally displays a user message on edit forms listing current
1022 * protections.
1023 *
1024 * @param $account The user account object.
1025 * @param $protected An array of protections the current user is receiving.
1026 */
1027 function userprotect_form_display_protections($account, $protected) {
1028 // If we're initially displaying an edit form, throw a message if
1029 // there are any protected fields, so the editor has a clue.
1030 if (!empty($protected) && !$_POST) {
1031 drupal_set_message(userprotect_display_protections($account, $protected));
1032 }
1033 }
1034
1035 /**
1036 * Builds a displayable text string of the protections currently in effect for
1037 * the specified user.
1038 *
1039 * @param $account The user account object.
1040 * @param $protected An array of protections the current user is receiving.
1041 *
1042 * @return A text string representing the current protections.
1043 */
1044 function userprotect_display_protections($account, $protected) {
1045
1046 // Get the protections display text.
1047 $display = userprotect_get_protection_display();
1048
1049 $protections = array();
1050 // For each protection, check if any of the user's roles are protected, or the user is
1051 // protected.
1052 foreach ($protected as $protection => $value) {
1053 $protections[] = $display[$protection];
1054 }
1055 // Display if there are protections and it's an admin user.
1056 if (count($protections) && user_access('administer users')) {
1057 $output = t('%user has been protected from the following editing operations: !operations', array('%user' => $account->name, '!operations' => implode(', ', $protections)));
1058 }
1059 else {
1060 $output = '';
1061 }
1062
1063 return $output;
1064 }
1065
1066 /**
1067 * Adds a user to the protections table.
1068 *
1069 * @param $uid The UID of the user to be added.
1070 * @param $type The type of protection to add, either 'user', or 'admin'.
1071 */
1072 function userprotect_add_user($uid, $type) {
1073 // Grab the default protections to enable for this user.
1074 $protections = variable_get('userprotect_protection_defaults', userprotect_user_protection_defaults());
1075
1076 // Set initial fields.
1077 $fields = array(
1078 'uid' => $uid,
1079 'up_type' => $type,
1080 );
1081
1082 // Add the protections.
1083 foreach ($protections as $protection => $value) {
1084 $fields[$protection] = $protections[$protection] ? 1 : 0;
1085 }
1086
1087 db_insert('userprotect')
1088 ->fields($fields)
1089 ->execute();
1090 }
1091
1092 /**
1093 * Gives the username of a protected user.
1094 *
1095 * @param $uid The user ID.
1096 * @return The username.
1097 */
1098 function userprotect_get_username($uid) {
1099 return db_query('SELECT name FROM {users} WHERE uid = :uid', array(
1100 ':uid' => $uid,
1101 ))->fetchField();
1102 }
1103
1104 /**
1105 * Checks to see if the current user can bypass a protection.
1106 *
1107 * @param $protection The protection to check for bypass.
1108 * @param $uid An optional user to perform the bypass check on (default is current user).
1109 *
1110 * @return TRUE if the user can bypass, FALSE otherwise.
1111 */
1112 function userprotect_check_bypass($protection, $uid = NULL) {
1113
1114 $bypass = &drupal_static(__FUNCTION__, array());
1115 $bypass_defaults = &drupal_static(__FUNCTION__ . '_defaults', NULL);
1116
1117 // If not a user admin, no checks necessary.
1118 if (!user_access('administer users')) {
1119 return FALSE;
1120 }
1121
1122 // Take the current user unless otherwise specified.
1123 $uid = isset($uid) ? $uid : $GLOBALS['user']->uid;
1124
1125 // Set the static array for the current admin.
1126 if (!isset($bypass[$uid])) {
1127 $result = db_query("SELECT * FROM {userprotect} WHERE uid = :uid AND up_type = :up_type", array(
1128 ':uid' => $uid,
1129 ':up_type' => 'admin',
1130 ));
1131 if ($admin_array = $result->fetchAssoc()) {
1132 $bypass[$uid] = $admin_array;
1133 }
1134 }
1135
1136 // If a per administrator bypass setting exists, return it.
1137 if (isset($bypass[$uid][$protection])) {
1138 return $bypass[$uid][$protection];
1139 }
1140 // Otherwise return the default bypass setting.
1141 else {
1142 if (!isset($bypass_defaults)) {
1143 $bypass_defaults = variable_get('userprotect_administrator_bypass_defaults', userprotect_administrator_bypass_defaults());
1144 }
1145
1146 return isset($bypass_defaults[$protection]) ? $bypass_defaults[$protection] : FALSE;
1147 }
1148
1149 }
1150
1151 /**
1152 * Checks to see if the specified user has the specified protection.
1153 *
1154 * @param $account The user object to check.
1155 * @param $protection The protection to check for.
1156 * @return TRUE if the user has the specified protection, FALSE otherwise.
1157 */
1158 function userprotect_get_user_protection($account, $protection) {
1159
1160 $protections = &drupal_static(__FUNCTION__, array());
1161 $role_protections = &drupal_static(__FUNCTION__ . '_roles', NULL);
1162
1163 $uid = $account->uid;
1164 $roles = $account->roles;
1165
1166 // Users editing their own accounts have the permissions for e-mail
1167 // and password determined by the role-based setting in the userprotect
1168 // section at admin/config/people/permissions. This is done for consistency
1169 // with the way core handles the self-editing of usernames.
1170 if ($uid == $GLOBALS['user']->uid && in_array($protection, array('up_name', 'up_mail', 'up_pass', 'up_openid', 'up_edit'))) {
1171 switch ($protection) {
1172 case 'up_name':
1173 return !user_access('change own username');
1174 case 'up_mail':
1175 return !user_access('change own e-mail');
1176 case 'up_pass':
1177 return !user_access('change own password');
1178 case 'up_openid':
1179 return !user_access('change own openid');
1180 // Always let user access their own edit page.
1181 case 'up_edit':
1182 return FALSE;
1183 }
1184 }
1185
1186 // If this user hasn't been added to the result array yet, then pull their information.
1187 if (!isset($protections[$uid])) {
1188
1189 $result = db_query("SELECT * FROM {userprotect} WHERE uid = :uid AND up_type = :up_type", array(
1190 ':uid' => $uid,
1191 ':up_type' => 'user',
1192 ));
1193 if ($user_array = $result->fetchAssoc()) {
1194 $protections[$uid] = $user_array;
1195 }
1196 }
1197
1198 // If per-user protections exist for this user, stop here and return the value of the protection.
1199 if (isset($protections[$uid][$protection])) {
1200 return $protections[$uid][$protection];
1201 }
1202
1203 // Grab the role protections if they haven't already been initialized.
1204 if (!isset($role_protections)) {
1205 $role_protections = variable_get('userprotect_role_protections', array());
1206 }
1207
1208 if (!empty($role_protections)) {
1209 // For each role, check to see if it's enabled for that protection.
1210 // Return TRUE as soon as we find a protected role.
1211 foreach ($roles as $rid => $role) {
1212 if ($role_protections[$rid][$protection]) {
1213 return TRUE;
1214 }
1215 }
1216 }
1217
1218 // No protection enabled.
1219 return FALSE;
1220 }

  ViewVC Help
Powered by ViewVC 1.1.2