Subversion Repositories WP-SMF user management

Rev

Blame | Last modification | View Log | RSS feed

<?php
/*
Plugin Name: WP &#8594; SMF users management
Description: Registers new WordPress users in a SMF installation and manages their roles and password change.
Version: 1.0
Author: Iacopo Benesperi
Author URI: http://www.iacchi.org/
License: GPL3
*/

?>
<?php
/*  Copyright 2012 Iacopo Benesperi (posta@iacchi.org)

    This program is free software: you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 3 as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, see http://www.gnu.org/licenses.
*/

?>
<?php
/* Plugin domain for i18n */

load_plugin_textdomain('wp_smf_users_management', false, basename(dirname(__FILE__)).'/languages');

/* Let's start with displaying the admin panel */

// This function displays the admin page
function wp_smf_users_management_admin_page_display(){
  global $wp_roles;
 
  // Must check that the user has the required capability
  if (!current_user_can('manage_options')) wp_die(__('You do not have sufficient permissions to access this page.', 'wp_smf_users_management'));

  // I need to get wp and smf user roles now because I need the in functions
  $smf_path_ok = get_option('wp_smf_users_management_smf_path');
  if ($smf_path_ok != '' && file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$smf_path_ok)){
    $roles = $wp_roles->role_names;
   
    // Inclusion of Settings.php
    $wp_smf_users_management_smf_path = get_option('wp_smf_users_management_smf_path');
    include($_SERVER['DOCUMENT_ROOT'].'/'.$wp_smf_users_management_smf_path);
   
    // Connection to the smf database
    $smf_conn = mysqli_connect($db_server, $db_user, $db_passwd) or wp_die(__('Error in SMF server parameters. Check Settings.php', 'wp_smf_users_management'));
    mysqli_select_db($smf_conn,$db_name) or wp_die(__('Error in SMF database selection. Check Settings.php', 'wp_smf_users_management'));
   
    // Fetch the smf user roles list
    $results = mysqli_query($smf_conn,'SELECT id_group, group_name FROM smf_membergroups');
    $smf_roles = array();
    while ($row = mysqli_fetch_array($results)){
      $smf_roles[$row[id_group]] = $row[group_name];
    }
  }

  // Update and sync functions
  function wp_smf_users_management_smf_path_update($path){
    if (file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$path) && $path != get_option('wp_smf_users_management_smf_path')){
      echo '<div class="updated"><p><strong>'; _e('Settings.php path saved successfully.', 'wp_smf_users_management'); echo '</strong></p></div>';
      update_option('wp_smf_users_management_smf_path',$path);
      return true;
    }
    elseif (!file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$path)){
      echo '<div class="error"><p><strong>'; _e('The given path for Settings.php is wrong. Remember to add the file name at the end.', 'wp_smf_users_management'); echo '</strong></p></div>';
      return false;
    }
    else return true;
  }
  function wp_smf_users_management_conversion_table_update($settings,$roles,$smf_roles){
    foreach ($roles as $key => $value){
      update_option('wp_smf_users_management_'.$key,array_search($settings['wp_smf_users_management_'.$key],$smf_roles));
    }
    echo '<div class="updated"><p><strong>'; _e('Roles conversion table saved successfully.', 'wp_smf_users_management'); echo '</strong></p></div>';
  }
  function wp_smf_users_management_user_sync(){
    global $wpdb;
    // Connection to the smf database
    include($_SERVER['DOCUMENT_ROOT'].'/'.get_option('wp_smf_users_management_smf_path'));
    $smf_conn = mysqli_connect($db_server, $db_user, $db_passwd) or wp_die(__('Error in SMF server parameters. Check Settings.php', 'wp_smf_users_management'));
    mysqli_select_db($smf_conn,$db_name) or wp_die(__('Error in SMF database selection. Check Settings.php', 'wp_smf_users_management'));
   
    // Get an array of wp users
    $wp_users = $wpdb->get_col($wpdb->prepare("SELECT $wpdb->users.user_login FROM $wpdb->users ORDER BY ID ASC"));
   
    //Get an array of smf users
    $results = mysqli_query($smf_conn,'SELECT id_member, member_name FROM smf_members');
    $smf_users = array();
    while ($row = mysqli_fetch_array($results)){
      $smf_users[$row[id_member]] = $row[member_name];
    }
   
    // Security check, if some smf user doesn't exist in wp, the sync ends
    // Sleep 1 ms every 100 scanned users
    $i = 0;
    $j = 0;
    foreach ($smf_users as $user){
      if (!in_array($user,$wp_users)){
        $user_error[$i] = $user;
        $i++;
      }
      $j++;
      if ($j % 100 == 0) usleep(1000);
    }
    if (isset($user_error)){
      $user_number = count($user_error);
      $user_error = implode(', ',$user_error);
      echo '<div class="error"><p><strong>'; printf(_n('The SMF users table contains an user not present in WordPress. The synchronization will be stopped for security reasons. User cause of the error: %s.','The SMF users table contains users not present in WordPress. The synchronization will be stopped for security reasons. Users cause of the error: %s.',$user_number, 'wp_smf_users_management'),$user_error); echo '</strong></p></div>';
      return;
    }
   
    // Swipe through all wp users
    // Sleep 0.1 s every 3 added users and 1 ms every 100 scanned users
    $i = 0;
    $j = 0;
    foreach ($wp_users as $user){
      if (!in_array($user,$smf_users)){
       
        // Get user data
        $data = get_user_by('login',$user);
       
        // Get the user role as $user_role
        $user_role = new WP_User($data->ID);
        $user_role = $user_role->roles[0];
       
        // Write the query do add the user to SMF
        $smf_table = $db_prefix.'members';
        $time = time();
        $group = get_option('wp_smf_users_management_'.$user_role);
        $salt = substr(md5(mt_rand()),0,4);
        $password_gen = substr(md5(mt_rand()),0,8);
        $password = sha1(strtolower($user).$password_gen);
        $email = $data->user_email;
        $query = "INSERT INTO $smf_table SET
                    member_name = '$user',
                    date_registered = $time,
                    posts = 0,
                    id_group = $group,
                    last_login = 0,
                    real_name = '$user',
                    instant_messages = 0,
                    unread_messages = 0,
                    new_pm = 0,
                    pm_prefs = 0,
                    passwd = '$password',
                    email_address = '$email',
                    gender = 0,
                    birthdate = '0001-01-01',
                    hide_email = 0,
                    show_online = 1,
                    time_offset = 0,
                    pm_email_notify = 1,
                    karma_bad = 0,
                    karma_good = 0,
                    notify_announcements = 1,
                    notify_regularity = 1,
                    notify_send_body = 0,
                    notify_types = 2,
                    member_ip = '0.0.0.0',
                    member_ip2 = '0.0.0.0',
                    id_theme = 0,
                    is_activated = 1,
                    id_msg_last_visit = 0,
                    id_post_group = 4,
                    total_time_logged_in = 0,
                    password_salt = '$salt',
                    warning = 0,
                    pm_receive_from = 1"
;
        if (!mysqli_query($smf_conn,$query)) wp_die(__('MySQL error while adding the new user: ', 'wp_smf_users_management').mysqli_error($smf_conn));
       
        // Send an e-mail to the user with the forum password
        $subject = 'La tua nuova password per accedere al forum di eBook Club Italia';
        $message = 'Ciao,
ti sta arrivando questa e-mail perché recentemente abbiamo effettuato una sincronizzazione del database utenti del nostro sito con quello del nostro forum ed è risultato che sei iscritto/a al primo ma non al secondo.
Abbiamo provveduto noi a creare per te un account sul nostro forum, in modo da rendere completa la tua partecipazione ad ebci.it
Questi sono i tuoi nuovi dati di accesso al forum:

Nome utente: '
.$user.'
Password: '
.$password_gen.'

Per modificare la password ti basterà accedere al tuo profilo utente, indifferentemente sul sito o sul forum di ebci.it, e digitare la nuova password.
Per avere gli stessi dati di accesso sia al sito che al forum, ti consigliamo di accedere al sito di ebci.it e dalla pagina del tuo profilo personale reinserire la tua password attuale nei due campi per la nuova password; in questo modo la tua password per il forum diverrà uguale a quella per il sito.

Grazie,
Lo staff di eBook Club Italia'
;
        $message = wordwrap($message,70);
        $headers = array();
        $headers[] = "MIME-Version: 1.0";
        $headers[] = "Content-type: text/plain; charset=utf-8";
        $headers[] = "From: Forum di eBook Club Italia <forum@ebci.it>";
        $headers[] = "Subject: {$subject}";
        $headers[] = "X-Mailer: PHP/".phpversion();
        mail($email,$subject,$message,implode("\r\n", $headers));
       
        $user_added[$i] = $user;
        $i++;
        if ($i % 3 == 0) usleep(100000);
      }
      $j++;
      if ($j % 100 == 0) usleep(1000);
    }
    if (isset($user_added)){
      $user_number = count($user_added);
      $user_added = implode(', ',$user_added);
      echo '<div class="updated"><p><strong>'; printf(_n('Sinchronization finished successfully. New user added on SMF: %s. The password to login on the forum has been sent to the user.','Sinchronization finished successfully. New users added on SMF: %s. The password to login on the forum has been sent to each user.',$user_number, 'wp_smf_users_management'),$user_added); echo '</strong></p></div>';
    }
    else{
      echo '<div class="updated"><p><strong>'; _e('Sinchronization finished successfully. No new users added on SMF.', 'wp_smf_users_management'); echo '</strong></p></div>';
    }
  }

  // Update options (just wp_smf_users_management_smf_path or everything) or sync
  if (isset($_POST['wp_smf_users_management_smf_path']) && isset($_POST['wp_smf_users_management_unique'])){
    wp_smf_users_management_smf_path_update($_POST['wp_smf_users_management_smf_path']);
  }
  elseif (isset($_POST['wp_smf_users_management_smf_path']) && !isset($_POST['wp_smf_users_management_unique'])){
    if (wp_smf_users_management_smf_path_update($_POST['wp_smf_users_management_smf_path'])) wp_smf_users_management_conversion_table_update($_POST,$roles,$smf_roles);
  }
  elseif (isset($_POST['wp_smf_users_management_sync'])){
    wp_smf_users_management_user_sync();
  }
?>
<div class="wrap">
<div id="icon-options-general" class="icon32"></div><h2><?php _e('WP &#8594; SMF users management settings', 'wp_smf_users_management'); ?></h2>
<?php
  // Check if Settings.php has been set correctly
  $smf_path_ok = get_option('wp_smf_users_management_smf_path');
  if ($smf_path_ok == '' || !file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$smf_path_ok)){
    $smf_path_ok = 'no';
    update_option('wp_smf_users_management_smf_path',''); // This is needed to always display the update message
  }

  // Switch admin page depending on smf path declaration
  switch ($smf_path_ok) {
    case 'no':
?>
<form name="wp_smf_users_management_settings" method="post" action="">
  <h3><?php _e('Settings.php file path', 'wp_smf_users_management'); ?></h3>
  <table class="form-table">
    <tr>
      <th><label><?php _e('Path:', 'wp_smf_users_management'); ?></label></th>
      <td><?php echo $_SERVER['DOCUMENT_ROOT'].'/'; ?><input name="wp_smf_users_management_smf_path" value="" class="regular-text" type="text"> <span class="description"><?php _e('write Settings.php at the end', 'wp_smf_users_management'); ?></span></td>
    </tr>
  </table>
  <input type="hidden" name="wp_smf_users_management_unique" value="y">
  <p class="submit"><input name="submit" id="submit" class="button-primary" value="<?php _e('Save settings', 'wp_smf_users_management'); ?>" type="submit"></p>
</form>
<?php
    break;
    default:
      // I know it's a repetition from above, but I need it to simplify the code
      // This will be run only once or twice anyway
      $roles = $wp_roles->role_names;
   
      // Inclusion of Settings.php
      $wp_smf_users_management_smf_path = get_option('wp_smf_users_management_smf_path');
      include_once($_SERVER['DOCUMENT_ROOT'].'/'.$wp_smf_users_management_smf_path);
     
      // Connection to the smf database
      $smf_conn = mysqli_connect($db_server, $db_user, $db_passwd) or wp_die(__('Error in SMF server parameters. Check Settings.php', 'wp_smf_users_management'));
      mysqli_select_db($smf_conn,$db_name) or wp_die(__('Error in SMF database selection. Check Settings.php', 'wp_smf_users_management'));
     
      // Fetch the smf user roles list
      $results = mysqli_query($smf_conn,'SELECT id_group, group_name FROM smf_membergroups');
      $smf_roles = array();
      while ($row = mysqli_fetch_array($results)){
        $smf_roles[$row[id_group]] = $row[group_name];
      }
?>
<form name="wp_smf_users_management_settings" method="post" action="">
  <h3><?php _e('Settings.php file path', 'wp_smf_users_management'); ?></h3>
  <table class="form-table">
    <tr>
      <th><label><?php _e('Path:', 'wp_smf_users_management'); ?></label></th>
      <td><?php echo $_SERVER['DOCUMENT_ROOT'].'/'; ?><input name="wp_smf_users_management_smf_path" value="<?php echo $wp_smf_users_management_smf_path; ?>" class="regular-text" type="text"> <span class="description"><?php _e('write Settings.php at the end', 'wp_smf_users_management'); ?></span></td>
    </tr>
  </table>

  <h3><?php _e('Roles conversion table', 'wp_smf_users_management'); ?></h3>
  <table class="form-table">
<?php
      // Display the wp user roles list
      foreach ($roles as $key => $value){
?>
    <tr>
      <th><label><?php echo $value.':'; ?></label></th>
      <td>
        <select name="<?php echo 'wp_smf_users_management_'.$key; ?>">
<?php
        $smf_roles_select = $smf_roles;
        foreach ($smf_roles_select as $key2 => $value2){
          $display = '<option';
          $option = get_option('wp_smf_users_management_'.$key);
          if (!$option) $option = '4';
          if ($option == $key2) $display .= ' selected="selected"';
          $display .= '>'.$value2.'</option>';
          echo $display;
        }
?>
        </select>
      </td>
    </tr>
<?php
      }
?>
  </table>
  <p class="submit"><input name="submit" id="submit" class="button-primary" value="<?php _e('Save settings', 'wp_smf_users_management'); ?>" type="submit"></p>
</form>
<form name="wp_smf_users_management_sync" method="post" action="">
  <input type="hidden" name="wp_smf_users_management_sync" value="y">
  <h3><?php _e('Users table synchronization', 'wp_smf_users_management'); ?></h3>
  <p><?php _e('<strong>Warning:</strong> this function may be heavy on the server, use it only when the server load is low. Even in this case it may overload the server and damage your database, so be sure to have a backup of both WordPress and SMF databases before you begin. In short: use it carefully. The synchronization is one way only from WordPress to SMF.', 'wp_smf_users_management'); ?></p>
   <p class="submit"><input name="submit" id="submit" class="button-primary" value="<?php _e('Sync users', 'wp_smf_users_management'); ?>" type="submit"></p>
</form>
<?php
    break;
  }
?>
</div>
<?php
}

// This function loads the admin page
function wp_smf_users_management_admin_page_load(){
  add_users_page( __('WP &#8594; SMF users management', 'wp_smf_users_management'), __('WP &#8594; SMF', 'wp_smf_users_management'), manage_options, 'wp_smf_users_management', 'wp_smf_users_management_admin_page_display');
}

// Hook for adding admin menu
add_action('admin_menu', 'wp_smf_users_management_admin_page_load');
?>
<?php
/* Now we care about user registration */

function wp_smf_users_management_add_user_registration($user_id){
 
  // Inclusion of Settings.php, check if it exists first
  if (!get_option('wp_smf_users_management_smf_path')) return;
  $wp_smf_users_management_smf_path = get_option('wp_smf_users_management_smf_path');
  include($_SERVER['DOCUMENT_ROOT'].'/'.$wp_smf_users_management_smf_path);
 
  // Connection to the smf database
  $smf_conn = mysqli_connect($db_server, $db_user, $db_passwd) or wp_die(__('Error in SMF server parameters. Check Settings.php', 'wp_smf_users_management'));
  mysqli_select_db($smf_conn,$db_name) or wp_die(__('Error in SMF database selection. Check Settings.php', 'wp_smf_users_management'));
 
  // Let's check again that the password has been inserted correctly
  // and if it's a user registering or an admin registering an user
  if (isset($_POST['ws_plugin__s2member_custom_reg_field_user_pass1'])){
    if ($_POST['ws_plugin__s2member_custom_reg_field_user_pass1'] != $_POST['ws_plugin__s2member_custom_reg_field_user_pass2']) return;
    else $password = $_POST['ws_plugin__s2member_custom_reg_field_user_pass1'];
  }
  elseif (isset($_POST['pass1'])){
    if ($_POST['pass1'] != $_POST['pass2']) return;
    else $password = $_POST['pass1'];
  }
  else return;
 
  // We do something only if the user exists. It should actually,
  // or s2member should have given an error already
  if ($user_id && is_object($user = new WP_User($user_id)) && $user_id == $user->ID){
    $data = get_userdata($user_id);
   
    // Write the query do add the user to SMF
    $smf_table = $db_prefix.'members';
    $username = $data->user_login;
    $time = time();
    $group = get_option('wp_smf_users_management_'.$user->roles[0]);
    $salt = substr(md5(mt_rand()),0,4);
    $password = sha1(strtolower($username).$password);
    $email = $data->user_email;
    if (!current_user_can('create_users')) $ip = $_SERVER["REMOTE_ADDR"];
    else $ip = '0.0.0.0';
    $query = "INSERT INTO $smf_table SET
                member_name = '$username',
                date_registered = $time,
                posts = 0,
                id_group = $group,
                last_login = 0,
                real_name = '$username',
                instant_messages = 0,
                unread_messages = 0,
                new_pm = 0,
                pm_prefs = 0,
                passwd = '$password',
                email_address = '$email',
                gender = 0,
                birthdate = '0001-01-01',
                hide_email = 0,
                show_online = 1,
                time_offset = 0,
                pm_email_notify = 1,
                karma_bad = 0,
                karma_good = 0,
                notify_announcements = 1,
                notify_regularity = 1,
                notify_send_body = 0,
                notify_types = 2,
                member_ip = '$ip',
                member_ip2 = '$ip',
                id_theme = 0,
                is_activated = 1,
                id_msg_last_visit = 0,
                id_post_group = 4,
                total_time_logged_in = 0,
                password_salt = '$salt',
                warning = 0,
                pm_receive_from = 1"
;
    if (!mysqli_query($smf_conn,$query)) wp_die(__('MySQL error while adding the new user: ', 'wp_smf_users_management').mysqli_error($smf_conn));
  }
}

// Do something on user registration with low priority,
// so that security checks are done by someone else
add_action('user_register', 'wp_smf_users_management_add_user_registration',100);
?>
<?php
/* Now we care about user profile update */

function wp_smf_users_management_update_user_profile($user_id){
 
  // Inclusion of Settings.php, check if it exists first
  if (!get_option('wp_smf_users_management_smf_path')) return;
  $wp_smf_users_management_smf_path = get_option('wp_smf_users_management_smf_path');
  include($_SERVER['DOCUMENT_ROOT'].'/'.$wp_smf_users_management_smf_path);
 
  // Connection to the smf database
  $smf_conn = mysqli_connect($db_server, $db_user, $db_passwd) or wp_die(__('Error in SMF server parameters. Check Settings.php', 'wp_smf_users_management'));
  mysqli_select_db($smf_conn,$db_name) or wp_die(__('Error in SMF database selection. Check Settings.php', 'wp_smf_users_management'));
 
  // Let's check again that the password has been inserted correctly
  // and if it's a user registering or an admin registering an user
  if (isset($_POST['pass1'])){
    if ($_POST['pass1'] != $_POST['pass2']) return;
    else $password = $_POST['pass1'];
  }
  else $password = '';
 
  // We do something only if the user exists. It should actually, or
  // s2member should have given an error already
  if ($user_id && is_object($user = new WP_User($user_id)) && $user_id == $user->ID){
    $data = get_userdata($user_id);
   
    // Write the query do edit user info on SMF and
    // we check that the user exists in SMF
    $smf_table = $db_prefix.'members';
    $username = $data->user_login;
    $group = get_option('wp_smf_users_management_'.$user->roles[0]);
    if ($password != '') $password = sha1(strtolower($username).$password);
    $email = $data->user_email;
    if (!mysqli_query($smf_conn,"SELECT * FROM $smf_table WHERE member_name = '$username'")) return;
    $query = "UPDATE $smf_table SET
                id_group = $group,"
;
                if ($password != '') $query .= "passwd = '$password',";
    $query .= " email_address = '$email'
                WHERE member_name = '$username'"
;
    if (!mysqli_query($smf_conn,$query)) wp_die(__('MySQL error while editing user data: ', 'wp_smf_users_management').mysqli_error($smf_conn));
  }
}

// Do something on profile update with low priority,
// so that security checks are done by someone else
add_action('profile_update', 'wp_smf_users_management_update_user_profile',100);
?>
<?php
/* Now we care about user deletion */

function wp_smf_users_management_delete_user($user_id){
 
  // Inclusion of Settings.php, check if it exists first
  if (!get_option('wp_smf_users_management_smf_path')) return;
  $wp_smf_users_management_smf_path = get_option('wp_smf_users_management_smf_path');
  include($_SERVER['DOCUMENT_ROOT'].'/'.$wp_smf_users_management_smf_path);
 
  // Connection to the smf database
  $smf_conn = mysqli_connect($db_server, $db_user, $db_passwd) or wp_die(__('Error in SMF server parameters. Check Settings.php', 'wp_smf_users_management'));
  mysqli_select_db($smf_conn,$db_name) or wp_die(__('Error in SMF database selection. Check Settings.php', 'wp_smf_users_management'));
 
  // We do something only if the user exists. It should actually, or
  // s2member should have given an error already
  if ($user_id){
    $data = get_userdata($user_id);
   
    // We check that the user exists in SMF and delete it
    $smf_table = $db_prefix.'members';
    $username = $data->user_login;
    if ($results = mysqli_query($smf_conn,"SELECT * FROM $smf_table WHERE member_name = '$username'")){
      $results = mysqli_fetch_array($results);
      $smf_id = $results['id_member'];
    }
    else return;
    // Delete the user from the users table
    if (!mysqli_query($smf_conn,"DELETE FROM $smf_table WHERE member_name = '$username'")) wp_die(__('MySQL error while deleting user from user table: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Make user posts guest posts
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}messages SET id_member = 0, poster_email = '' WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while setting deleted user\'s posts as guest posts: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}polls SET id_member = 0 WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while setting user\'s poll votes as guest votes: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Make user posts guest first posts and last posts
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}topics SET id_member_updated = 0 WHERE id_member_updated = '$smf_id'")) wp_die(__('MySQL error while setting user\'s last posts as guest posts: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}topics SET id_member_started = 0 WHERE id_member_started = '$smf_id'")) wp_die(__('MySQL error while seting user\'s first posts as guest posts: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Make user logs guest logs
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}log_actions SET id_member = 0 WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while giving user\'s log actions to the guest user: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}log_banned SET id_member = 0 WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while giving user\'s log banned to the guest user: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}log_errors SET id_member = 0 WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while giving user\'s log errors to the guest user: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}log_polls SET id_member = 0 WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while giving user\'s log polls to the guest user: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Delete user logs
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_actions WHERE id_log = 2 AND id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log actions: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_boards WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log boards: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_comments WHERE id_recipient = '$smf_id' AND comment_type = 'warntpl'")) wp_die(__('MySQL error while deleting the user from log comments: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_group_requests WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log group_requests: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_karma WHERE id_target = '$smf_id' OR id_executor = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log karma: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_mark_read WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log mark_read: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_notify WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log notify: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_online WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log online: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_subscribed WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log subscribed: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}log_topics WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from log topics: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Delete user from collapsed_categories
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}collapsed_categories WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting the user from collapsed_categories: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Delete user PMs
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}personal_messages SET deleted_by_sender = 1 WHERE id_member_from = '$smf_id' AND deleted_by_sender = 0")) wp_die(__('MySQL error while deleting user\'s PM sent folder: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}pm_recipients SET deleted = 1 WHERE id_member = '$smf_id' AND deleted = 0")) wp_die(__('MySQL error while deletinguser\'s PMs from folders other than sent: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if ($results = mysqli_query($smf_conn,"SELECT pm.id_pm AS sender, pmr.id_pm FROM {$db_prefix}personal_messages AS pm LEFT JOIN {$db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm AND pmr.deleted = 0) WHERE pm.deleted_by_sender = 1 GROUP BY sender, pmr.id_pm HAVING pmr.id_pm IS null")){
      $remove_pms = array();
      while ($row = mysqli_fetch_assoc($results)) $remove_pms[] = $row['sender'];
      if (!empty($remove_pms)){
        if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}personal_messages WHERE id_pm IN ($remove_pms)")) wp_die(__('MySQL error while deleting PMs: ', 'wp_smf_users_management').mysqli_error($smf_conn));
        if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}pm_recipients WHERE id_pm IN ($remove_pms)")) wp_die(__('MySQL error while deleting PMs: ', 'wp_smf_users_management').mysqli_error($smf_conn));
      }
    }
    else wp_die(__('MySQL error while deleting PMs: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}personal_messages SET id_member_from = 0 WHERE id_member_from = '$smf_id'")) wp_die(__('MySQL error while giving user\'s PMs in other user\'s mailboxes to the guest user: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}pm_recipients WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting user from recipient lists: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Delete user avatar: I will not delete user avatar:
    // the function is a mess if not done inside SMF;
    // all the other bridges don't do it, too.
    // Remove user from moderation groups
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}moderators WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting user from moderators group: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}group_moderators WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting user from global moderators group: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Remove user from ban list
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}ban_items WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting user from bannable users list: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Remove user theme settings
    if (!mysqli_query($smf_conn,"DELETE FROM {$db_prefix}themes WHERE id_member = '$smf_id'")) wp_die(__('MySQL error while deleting user\'s theme settings: ', 'wp_smf_users_management').mysqli_error($smf_conn));
    // Remove user from buddy lists
    if ($results = mysqli_query($smf_conn,"SELECT id_member, pm_ignore_list, buddy_list FROM {$db_prefix}members WHERE FIND_IN_SET('$smf_id', pm_ignore_list) != 0 OR FIND_IN_SET('$smf_id', buddy_list) != 0")){
      while ($row = mysqli_fetch_assoc($results)){
        $pm_ignore_list = implode(',', array_diff(explode(',', $row['pm_ignore_list']), $users));
        $buddy_list = implode(',', array_diff(explode(',', $row['buddy_list']), $users));
        if (!mysqli_query($smf_conn,"UPDATE {$db_prefix}members SET pm_ignore_list = '$pm_ignore_list', buddy_list = '$buddy_list' WHERE id_member = '{$row['id_member']}'")) wp_die(__('MySQL error for buddy lists: ', 'wp_smf_users_management').mysqli_error($smf_conn));
      }
    }
    else wp_die(__('MySQL error while deleting user from buddy lists: ', 'wp_smf_users_management').mysqli_error($smf_conn));
  }
}
// Do something on user deletion
add_action('delete_user', 'wp_smf_users_management_delete_user');
?>
<?php
/* Now we care about automatic user role degradation or upgrade by s2members */

function wp_smf_users_management_auto_role_update($user_id, $role){
 
  // Inclusion of Settings.php, check if it exists first
  if (!get_option('wp_smf_users_management_smf_path')) return;
  $wp_smf_users_management_smf_path = get_option('wp_smf_users_management_smf_path');
  include($_SERVER['DOCUMENT_ROOT'].'/'.$wp_smf_users_management_smf_path);
 
  // Connection to the smf database
  $smf_conn = mysqli_connect($db_server, $db_user, $db_passwd) or wp_die(__('Error in SMF server parameters. Check Settings.php', 'wp_smf_users_management'));
  mysqli_select_db($smf_conn,$db_name) or wp_die(__('Error in SMF database selection. Check Settings.php', 'wp_smf_users_management'));
 
  // We do something only if the user exists. It should actually, or
  // s2member should have given an error already
  if ($user_id && is_object($user = new WP_User($user_id)) && $user_id == $user->ID){
    $data = get_userdata($user_id);
   
    // Write the query do edit user role on SMF and
    // we check that the user exists in SMF
    $smf_table = $db_prefix.'members';
    $username = $data->user_login;
    $group = get_option('wp_smf_users_management_'.$role);
    if (!mysqli_query($smf_conn,"SELECT * FROM $smf_table WHERE member_name = '$username'")) return;
    $query = "UPDATE $smf_table SET id_group = '$group' WHERE member_name = '$username'";
    if (!mysqli_query($smf_conn,$query)) wp_die(__('MySQL error while updating user role: ', 'wp_smf_users_management').mysqli_error($smf_conn));
  }
}

// Do something on automatic role update with low priority,
// so that security checks are done by someone else
add_action('set_user_role', 'wp_smf_users_management_auto_role_update',101);
?>