Skip to content

Instantly share code, notes, and snippets.

@jondcampbell
Created December 12, 2014 23:02
Show Gist options
  • Save jondcampbell/f7210dcc2c82ee6278fb to your computer and use it in GitHub Desktop.
Save jondcampbell/f7210dcc2c82ee6278fb to your computer and use it in GitHub Desktop.
grab user data from drupal and import it into wordpress
<?php
// Drupal User Migration Class
class UserMigrate{
// Things that can be overridden by GET variables
public $users_start = 0;
public $users_limit = 5;
public $mode = 'preview';
public $confirm_cleanup = false;
private $errors = '';
// For status updates
private $users_found = 0;
private $users_added = 0;
private $users_existed = 0;
private $users_skipped = 0;
/**
* Main function that starts the migration
*/
public function Run(){
if($this->mode == 'preview'):
$this->DoPreview();
elseif($this->mode == 'cleanup'):
$this->DoCleanup();
elseif($this->mode == 'migrate'):
$this->DoMigration();
endif;
}
/**
* Check for items to import, and give us a status report
*
*/
private function DoPreview(){
echo "<h2>Preview</h2>";
$drupal_users = $this->GetDrupalUsers();
$this->users_found = count($drupal_users);
$this->UpdateStatus();
}
/**
* Do the actual migration process
*/
private function DoMigration(){
echo "<h2>Do Migration</h2>";
$drupal_users = $this->GetDrupalUsers();
$this->users_found = count($drupal_users);
$this->UpdateWpUsers($drupal_users);
$this->UpdateStatus();
}
/**
*
* Find users with our particular user_status value and remove them if its been confirmed
*/
private function DoCleanup(){
global $wpdb;
echo "<h2>Do Cleanup</h2>";
// Find users that are "imported" status
$imported_users = $wpdb->get_results('SELECT * FROM wp_users WHERE user_status = 77');
// Count them
$cleanup_count = count($imported_users);
if($this->confirm_cleanup && $cleanup_count > 0):
// remove the users
require_once(ABSPATH.'wp-admin/includes/user.php' );
echo "<h3>Deleted Users</h3>";
foreach($imported_users as $imported_user):
wp_delete_user($imported_user->ID);
echo $imported_user->ID ." " .$imported_user->user_login ."<br />";
endforeach;
elseif($cleanup_count === 0):
echo "There is no users to delete";
else:
echo '
<h3>Are you sure you want to remove the ' .$cleanup_count .' imported users? </h3><br />
<a href="' .get_permalink() .'?mode=cleanup&confirm-cleanup=true">Yes, remove the users</a>
';
endif;
}
/**
* A quick update on what we found in the database and what we have done with it
*/
private function UpdateStatus(){
echo "<h5>Status Update:</h5>";
echo "Users Found in Database(using current search parameters) " .$this->users_found ."<br />";
echo "Users Added " .$this->users_added ."<br />";
echo "Users Existed Previously " .$this->users_existed ."<br />";
echo "Users Skipped " .$this->users_skipped;
}
/**
* Connect to the drupal database and get users
*
* @return mixed
*/
private function GetDrupalUsers(){
global $wpdb;
$wpdb->show_errors();
// Query our three drupal tables(users, users_roles, profile_values), the mutiple roles in drupal table are concatinated into a comma seperated list
$results = $wpdb->get_results( '
SELECT users.*, GROUP_CONCAT(DISTINCT users_roles.rid ORDER BY users_roles.rid) AS role_id_list, profile_values.value as organization_type FROM users
LEFT JOIN users_roles on users_roles.uid = users.uid
LEFT JOIN profile_values on profile_values.uid = users.uid
WHERE profile_values.fid = 34
GROUP BY users.uid
ORDER BY users.uid
LIMIT ' .$this->users_limit
.' OFFSET ' . $this->users_start
);
return $results;
}
/**
* Echo out details about this user for troubleshooting
*
* @param $drupal_user
*/
private function OutputDrupalUserDetails($drupal_user){
echo "Name: " .$drupal_user->name ." Email: " .$drupal_user->mail ." Role: " .$drupal_user->role_id_list ."<br />";
}
/**
* Main function for updating the wordpress users based on the drupal user
* @param $users
*/
private function UpdateWpUsers($wp_users){
global $wpdb;
foreach ($wp_users as $user):
if(!$user->mail):
// No email on this user
$this->users_skipped++;
echo "Skipped, No Email: ";
$this->OutputDrupalUserDetails($user);
continue;
elseif( $conflicting_user_id = email_exists( $user->mail )):
// User exists, just add to the count and move on
$this->users_existed++;
echo "Skipped, Email existed already: ";
$this->OutputDrupalUserDetails($user);
$conflict_user = get_userdata($conflicting_user_id);
echo "Wordpress User: " .$conflict_user->user_login ."<br />";
continue;
elseif( username_exists( $user->name )):
// User exists, just add to the count and move on
echo "Skipped, Username existed already: ";
$this->OutputDrupalUserDetails($user);
$this->users_existed++;
continue;
else:
// New user time
$wp_user_pass = $user->pass;
$wp_user_login = $user->name;
$wp_user_nicename = $user->name;
$wp_display_name = $user->name;
$wp_user_email = $user->mail;
$wp_user_registered = date("Y-m-d H:i:s",$user->created);
$wp_user_status = 77; // So we know this user was an imported one
$wp_user_groups = array();
// Build an array of the users roles from the comma seperated list
$drupal_roles_array = explode(',', $user->role_id_list);
// Convert their first role to a wordpress user role
$wp_user_role = $this->ConvertUserRole($drupal_roles_array[0]);
// Convert their organization type to a group membership id, groups can have multiple so using an array
$wp_user_groups[] = $this->ConvertUserOrganization($user->organization_type);
// Loop through their drupal roles and add them to the equivalent groups
foreach($drupal_roles_array as $drupal_role):
$wp_user_groups = $this->AddUserGroupsByDrupalRole($drupal_role, $wp_user_groups);
endforeach;
// Insert the users into the database
$user_insert = $wpdb->insert(
'wp_users',
array(
'user_login' =>$wp_user_login,
'user_pass' =>$wp_user_pass,
'user_nicename' =>$wp_user_nicename,
'user_email' =>$wp_user_email,
'user_registered' =>$wp_user_registered,
'user_status' => $wp_user_status,
'display_name' =>$wp_display_name
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%d',
'%s'
)
);
if($user_insert):
$this->users_added++;
$wp_user_id = $wpdb->insert_id;
else:
// It didnt insert
endif;
// Set user level
$this->SetWpUserRole($wp_user_id, $wp_user_role);
// Set capabilities
$this->SetWpUserGroups($wp_user_id, $wp_user_groups);
// Set the company type in their profile
update_user_meta( $wp_user_id, '_company_type', $user->organization_type);
// Output the new user ids, for fun
echo "User ID: " .$wp_user_id ." Email: " .$wp_user_email ."<br />";
endif;
endforeach;
}
/**
* Review our drupal roles and convert to wordpress roles, as we are reviewing the wordpress roles we will also add the group ids they need to an array.
*
*
* @param $drupal_role_id
* @return string
*/
private function ConvertUserRole($drupal_role_id){
// Map the users role from drupal, to something useful for wordpress
/*
* Drupal roles:
* 1 anonymous user
* 2 authenticated user
* 3 job seeker
* 4 job seeker (featured)
* 5 employer
* 6 employer (branded page)
* 9 manager
*
* Wordpress roles:
* administrator
* subscriber
* customer
* candidate
* employer
*/
switch($drupal_role_id):
case 1:
break;
case 2:
$wp_role_id = 'customer';
break;
case 3:
$wp_role_id = 'candidate';
break;
case 4:
$wp_role_id = 'candidate';
break;
case 5:
$wp_role_id = 'employer';
break;
case 6:
$wp_role_id = 'employer';
break;
case 9:
$wp_role_id = 'administrator';
break;
default:
$wp_role_id = 'subscriber';
endswitch;
return $wp_role_id;
}
/**
* For the particular drupal role we want to add the user groups to our user groups array
*
* @param $drupal_role_id
* @param $our_user_groups
* @return array
*/
private function AddUserGroupsByDrupalRole($drupal_role_id, $our_user_groups){
switch($drupal_role_id):
case 3:
// Candidates
$our_user_groups[] = 3;
break;
case 4:
// Special candidate
// They should be a part of the Job Seeker Group and Featured Talent Group
$our_user_groups[] = 3;
$our_user_groups[] = 2;
break;
case 5:
// They should be a part of the employer group
$our_user_groups[] = 4;
break;
case 6:
// They should be a part of the employer group, in drupal this was a branded page employer
$our_user_groups[] = 4;
break;
case 9:
break;
default:
break;
endswitch;
return $our_user_groups;
}
/**
*
*
* @param $drupal_organization_type
* @return int
*/
private function ConvertUserOrganization($drupal_organization_type){
// Map the users organization type from drupal, to something useful for wordpress groups
/*
* Drupal organizations:
* 0
* Commercial
* Not for Profit
* Government
* Recruiter
*
*/
// Assign user a specific group based on selection.
switch ($drupal_organization_type):
case 'Commercial':
$wp_organization_type = 7;
break;
case 'Not for Profit':
$wp_organization_type = 6;
break;
case 'Government':
$wp_organization_type = 8;
break;
case 'Recruiter':
$wp_organization_type = 9;
break;
default:
break;
endswitch;
return $wp_organization_type;
}
/**
* For a particular user set their wordpress user role
*
* @param $wp_user_id
* @param $wp_user_role
*/
private function SetWpUserRole($wp_user_id,$wp_user_role){
$user_id = wp_update_user( array( 'ID' => $wp_user_id, 'role' => $wp_user_role ) );
if ( is_wp_error( $user_id ) ):
// There was an error, probably that user doesn't exist.
else:
// Success
endif;
}
/**
* @param $wp_user_id
* @param $wp_user_groups
* - Array of groups
*/
private function SetWpUserGroups($wp_user_id, $wp_user_groups){
$result = false;
// Loop through our array of groups we want to add to
foreach($wp_user_groups as $wp_user_group):
$result = Groups_User_Group::create(array( 'user_id' => $wp_user_id, 'group_id' => $wp_user_group ) );
endforeach;
}
// TODO: one day possibly add a method for bringing in more profile data from drupal
}
// Lets do this
$Migration = new UserMigrate();
// Check for get variables in the url
$Migration->users_limit = (isset($_GET['limit']) ? $_GET['limit'] : 10);
$Migration->users_start = (isset($_GET['start']) ? $_GET['start'] : 0);
$Migration->mode = (isset($_GET['mode']) ? $_GET['mode'] : 'preview');
if(isset($_GET['confirm-cleanup']) && $Migration->mode === 'cleanup' && $_GET['confirm-cleanup'] === 'true'):
$Migration->confirm_cleanup = true;
endif;
$Migration->Run();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment