Drupal - How can I programmatically delete a user?

This is not that hard, for D6 it would look like this:

  1. Delete record from Drupal database users table;

    user_delete(array(), $uid);
    
  2. Change author on any content created by deleted user to Anonymous;

    handled by the node module.

  3. Send an email to our internal support address letting them know that the user should be removed from other non-connected systems

    drupal_mail(...);
    

    See hook_mail for details.


Is it even worth it to use user_delete()? Would it be less trouble to just write my own queries to delete the user record and change any content records to "Anonymous"?

To delete a user account, and assign all the nodes the user authored to the anonymous user, you simply need to call user_delete(array(), $account->uid), or user_delete(array(), $uid), depending if you have an user object, or a user ID.

As for assigning the nodes created with the user account being deleted, user_delete() invokes all the implementations of hook_user() passing "delete" as value for $op. The Node module implements the hook using the following code:

function node_user($op, &$edit, &$user) {
  if ($op == 'delete') {
    db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
    db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
  }
}

As you see, the function already updates the nodes authored by the user account being deleted, and any node revisions where associated with that user account.

The first parameter required from user_delete() is normally not used from the implementations of hook_user(), when the $op parameter is set to "delete." In most of the cases, the modules just use $account->uid to identify the user data they wrote in their own database tables. Even supposing the modules saved the data using another value to identify the user account, it is a value contained in the user object.

As per writing your own queries to delete the user account, I would not suggest doing it, as there could be modules that need to be informed when a user account is delete, usually to delete the data the module associated to that account. Rewriting code when there is already a function for this specific purpose could mean also to update the code when passing to a new Drupal version. The code would not be as generic as the code already used by Drupal.

Tags:

Users

Hooks

6