Created
July 19, 2013 16:31
-
-
Save aaronott/6040509 to your computer and use it in GitHub Desktop.
Use drush to clean up users with no roles (except authenticated user) assigned to them.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env drush | |
<?php | |
/** | |
* This script removes all drupal users with no roles other than authenticated | |
* user assigned. | |
* | |
* This is useful in the case where a site's only users are admin or some | |
* other higher level role. | |
* | |
* Make sure to back up the database prior to running this as this cannot be | |
* undone. | |
**/ | |
$self = drush_sitealias_get_record('@self'); | |
if (empty($self)) { | |
drush_die("I can't bootstrap from the current location.", 0); | |
} | |
// we don't want to say yes each time. | |
drush_set_context('DRUSH_AFFIRMATIVE', TRUE); | |
$authenticated_user = array('authenticated user'); | |
$users_deleted = 0; | |
$users_not_deleted = 0; | |
$result = db_query("SELECT uid,name FROM users WHERE uid > 1 ORDER BY uid DESC LIMIT 500"); | |
foreach ($result as $user) { | |
$uid = $user->uid; | |
// make this runnable on d6 as well as d7 | |
if (drush_drupal_major_version() >= 7) { | |
$user = user_load($uid); | |
} | |
else { | |
$user = user_load(array('uid' => $uid)); | |
} | |
// strip out the authenticated user | |
$roles = array_diff(array_values($user->roles), $authenticated_user); | |
// if there are no roles left, we should delete this user | |
if (sizeof($roles) < 1) { | |
$users_deleted++; | |
// taken from the drush_user_cancel code | |
// http://api.drush.org/api/drush/commands%21user%21user.drush.inc/function/drush_user_cancel/5.x | |
if (drush_drupal_major_version() >= 7) { | |
if (drush_get_option('delete-content')) { | |
user_cancel(array(), $uid, 'user_cancel_delete'); | |
} | |
else { | |
user_cancel(array(), $uid, 'user_cancel_reassign'); | |
} | |
// I got the following technique here: http://drupal.org/node/638712 | |
$batch = &batch_get(); | |
$batch['progressive'] = FALSE; | |
batch_process(); | |
} | |
else { | |
user_delete(array(), $uid); | |
} | |
} | |
else { | |
$users_not_deleted++; | |
drush_print("save: $user->name"); | |
} | |
} | |
drush_print("Total users deleted: " . $users_deleted); | |
drush_print("Total users NOT deleted: " . $users_not_deleted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment