Newer
Older
Digital_Repository / Repositories / Misc / import_users.pl
nstanger on 23 Mar 2010 2 KB - Added bulk user import script.
#!/usr/bin/perl -w -I/home/eprints3/perl_lib

use EPrints::DataObj::User;
use EPrints::Session;
use strict;

my $session = EPrints::Session->new( 1 , $ARGV[0] );
exit unless( defined $session );

# Set to 1 to actually make changes to the database
my $forreal = 1;

# Get user dataset
my $user_ds = $session->get_archive()->get_dataset( "user" );


my $input_filename = $ARGV[1];

( defined $input_filename ) or die "No input filename specified.\n";

# Try to open the input file.
open INFILE, "<$input_filename"
	or die "ERROR: couldn't open file '$input_filename' for reading.\n";


while( <INFILE> )
{

	next if /^#/;
	next if /^$/;
	
	#username	type	password	given name	family name	email	department	organisation	address	country	homepage
	/^([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t"?([^"]+)"?\t([^\t]+)\t(.*)$/;

	my $username = $1;
	my $usertype = $2;
	my $password = EPrints::Utils::crypt_password( $3 );
	my $givenname = $4;
	my $familyname = $5;
	my $email = $6;
	my $department = $7;
	my $organisation = $8;
	my $address = $9;
	my $country = $10;
	my $homepage = $11;
	
	# Does account already exist?
	my $searchexp = new EPrints::SearchExpression( session=>$session, dataset=>$user_ds );
	$searchexp->add_field( $user_ds->get_field( "username" ), $username );
	my $searchid = $searchexp->perform_search;
	my( $user ) = $searchexp->get_records;
	$searchexp->dispose( );

	if( !defined $user )
	{

		# New account
		if( $forreal )
		{
			$user = EPrints::User::create( $session, $usertype );
			$user->set_value( "username", $username );
			print "CREATING: $username\n";
		}
		else
		{
			print "(WOULD BE) CREATING: $username\n";
		}

	} 
	else 
	{

		# Update account
		if( $forreal )
		{
			print "UPDATING: $username\n";
		} 
		else 
		{
			print "(WOULD BE) UPDATING: $username\n";
		}

	}

	# Set metadata
	if( $forreal )
	{

		my $name = {};
		$name->{family} = $familyname;
		$name->{given} = $givenname;
		$user->set_value( "name", $name );
		$user->set_value( "email", $email );
		$user->set_value( "password", $password );
		$user->set_value( "dept", $department );
		$user->set_value( "org", $organisation );
		$user->set_value( "address", $address );
		$user->set_value( "country", $country );
		$user->set_value( "url", $homepage );
		
		$user->commit();

	} 
	else 
	{

		print "FAMILY = $familyname\n";
		print "GIVEN = $givenname\n";
		print "EMAIL = $email\n";
		print "PASSWORD = $password\n";
		print "DEPARTMENT = $department\n";
		print "ORGANISATION = $organisation\n";
		print "ADDRESS = $address\n";
		print "COUNTRY = $country\n";
		print "URL = $homepage\n\n";

	}

}

# Clean up.
close INFILE;