def setup(self):
		# login restriction
		rx = QRegExp('^[a-z][._0-9a-z]*')
		rx_validator = QRegExpValidator(rx,self)
		self.ed_login.setValidator(rx_validator)
		# present the domain name (This has been removed for the sake of smaller pupils)
		# self.lbl_domain_name.setText('@%s' % self.proxy.domain_name())
		self.connect(self.ed_login,SIGNAL("textChanged(const QString&)"),self.check_login)
		self.connect(self.cmb_usertype,SIGNAL("activated(int)"),self.usertype_changed)
		
		thisyear = QDateTime.currentDateTime().date().year()
		self.sbx_firstschoolyear.setValue(thisyear)
		self.sbx_firstschoolyear.setMinValue(thisyear-15)
		self.sbx_firstschoolyear.setMaxValue(thisyear+3)

		setupdict = {}
		self.typedict = {}
		for type_text in userdef.list_usertypes_by_text():
			self.typedict[self.tr(type_text).latin1()] = userdef.usertype_as_id(type_text)
			setupdict[type_text] = { 
				'id': userdef.usertype_as_id(type_text),
				'display': self.tr(type_text).latin1() }
		
		for usertype_text in config.usertype_order:
			if setupdict.has_key(usertype_text):
				self.cmb_usertype.insertItem(setupdict[usertype_text]['display'])
		
		self.usertype_changed()
		self.groups_to_combo()
	def updateUserView(self):
		usertype_id = None
		groupfilter = None
		idx = self.cmb_usertype_filter.currentIndex()
		if idx > -1:
			usertype_id,ok = self.cmb_usertype_filter.itemData(idx).toInt()
			if usertype_id == -1:
				usertype_id = None
	
		idx = self.cmb_groupfilter.currentIndex()
		if idx > -1:
			groupfilter = str(self.cmb_groupfilter.itemData(idx).toString().toUtf8())
			if groupfilter=='':
				# Group filter set to "All"
				groupfilter = None
		
		min_grade,max_grade = None,None
		if usertype_id==userdef.usertype_as_id('student'):
			self.lbl_gradefilter.setEnabled(True)
			self.lbl_gradefilter_to.setEnabled(True)
			self.sbx_firstschoolyear_min.setEnabled(True)
			self.sbx_firstschoolyear_max.setEnabled(True)
			min_grade = self.sbx_firstschoolyear_min.value()
			max_grade = self.sbx_firstschoolyear_max.value()
		else:
			self.lbl_gradefilter.setEnabled(False)
			self.lbl_gradefilter_to.setEnabled(False)
			self.sbx_firstschoolyear_min.setEnabled(False)
			self.sbx_firstschoolyear_max.setEnabled(False)

		self.usermodel.loadUsers(usertype_id=usertype_id,groupname=groupfilter,min_grade=min_grade,max_grade=max_grade)
			
		for colidx in xrange(self.usermodel.columnCount()):
			self.trv_userlist.resizeColumnToContents(colidx)
	def usertype_changed(self):
		usertype_id = self.typedict[self.cmb_usertype.currentText().latin1()]
		if usertype_id==userdef.usertype_as_id('student'):
			self.lbl_firstschoolyear.setEnabled(True)
			self.sbx_firstschoolyear.setEnabled(True)
		else:
			self.lbl_firstschoolyear.setEnabled(False)
			self.sbx_firstschoolyear.setEnabled(False)
	def slot_usertype_changed(self,idx):
		self.classyear_filter_enabled = False
		usertype_id = self.typedict[self.m_cb_usertype_filter.currentText().latin1()]
		if usertype_id==userdef.usertype_as_id('student'):
			self.classyear_filter_enabled = True
			self.lbl_firstschoolyear_to.setEnabled(True)
			self.sbx_firstschoolyear_min.setEnabled(True)
			self.sbx_firstschoolyear_max.setEnabled(True)
		else:
			self.lbl_firstschoolyear_to.setEnabled(False)
			self.sbx_firstschoolyear_min.setEnabled(False)
			self.sbx_firstschoolyear_max.setEnabled(False)
		
		self.update_list(usertype_id)
	def updateNamePage(self):
		self.setWindowTitle(self.tr("New User") + " - [ " + self.led_given_name.text() + " " + self.led_family_name.text() + " ]")
		usertype_cmb_idx = self.cmb_usertype.currentIndex()
		# Maybe enable the first school year box
		usertype_id,ok = self.cmb_usertype.itemData(usertype_cmb_idx).toInt()
		if usertype_id == userdef.usertype_as_id('student'):
			self.sbx_first_school_year.setEnabled(True)
		else:
			self.sbx_first_school_year.setEnabled(False)
		if not self.led_given_name.text().isEmpty() and \
			not self.led_family_name.text().isEmpty() and \
			usertype_cmb_idx!=-1:
			self.name_page_ok = True
		else:
			self.name_page_ok = False
		self.updateWizardButtons()
	def finish(self):
		uid = str(self.led_login.text().toUtf8())
		givenname = str(self.led_given_name.text().toUtf8())
		familyname = str(self.led_family_name.text().toUtf8())
		usertype_id,ok = self.cmb_usertype.itemData(self.cmb_usertype.currentIndex()).toInt()
		firstyear = None
		if usertype_id == userdef.usertype_as_id('student'):
			firstyear = self.sbx_first_school_year.value()
		primarygroup,ok = self.cmb_primary_group.itemData(self.cmb_primary_group.currentIndex()).toInt()
		passwd = str(self.led_passwd.text().toUtf8())
		proxy = cm.get_proxy_handle()
		res = proxy.createuser(uid,givenname,familyname,passwd,usertype_id,primarygroup,firstyear)
		if res>=0:
			import ss_mainwindow as mainwin
			mainwin.get_mainwindow().emitUserCreated(uid)
			
		for groupname in self.groupmodel.groupNames():
			proxy.groupadd(uid,groupname)
		
		self.accept()
	def __init__(self,parent):
		esm.EnhancedStandardItemModel.__init__(self,parent)
		self.proxy = cm.get_proxy_handle()
		self.users = {}
		self.columninfo = {
			'uidnumber': {'text': self.tr('User ID'), 'columnindex': 3},
			'uid': {'text': self.tr('Login'), 'columnindex': 1},
			'cn': {'text': self.tr('User name'), 'columnindex': 0},
			'usertype': {'text': self.tr('User type'), 'columnindex': 2} }
		self.initialSetup()
		self.tr("teacher","singular")
		self.tr("student","singular")
		self.tr("parent","singular")
		self.tr("other","singular")
		default_icon = paths.path_to('art/student.svg')
		self.icons = {}
		for usertype in userdef.list_usertypes_by_text():
			icon = default_icon
			if os.path.exists(paths.path_to('art/%s.svg') % usertype):
				icon = paths.path_to('art/%s.svg') % usertype
			self.icons[userdef.usertype_as_id(usertype)] = qt4tools.svg2pixmap(icon,24,24)
	def __init__(self,conn,parent = None,name = None,fl = 0):
		self.classyear_filter_enabled = False
		self.group_filter_enabled = False
		self.group_members = []
		UserManagerWdgBase.__init__(self,parent,name,fl)
		self.m_lv_userlist.addColumn(self.tr("Name"))
		self.m_lv_userlist.addColumn(self.tr("Type"))
		self.m_lv_userlist.addColumn(self.tr("Login"))
		
		self.conn = conn # For passing on to create/remove users
		self.soapproxy = conn.get_proxy_handle()
		self.userlist = []
		self.update_list()
		self.contextmenu_enabled = True

		# setup usertype combo
		setupdict = {}
		self.typedict = {}
		for type_text in userdef.list_usertypes_by_text():
			self.typedict[self.tr(type_text).latin1()] = userdef.usertype_as_id(type_text)
			setupdict[type_text] = self.tr(type_text).latin1()

		self.typedict[self.tr('all').latin1()] = None
		setupdict['all'] = self.tr('all').latin1()
		self.connect(self.m_cb_usertype_filter,SIGNAL("activated(int)"),self.slot_usertype_changed)
		self.connect(self.cmb_groupfilter,SIGNAL("activated(int)"),self.slot_groupfilter_changed)
		self.connect(self.sbx_firstschoolyear_min,SIGNAL("valueChanged(int)"),self.slot_classyear_span_changed)
		self.connect(self.sbx_firstschoolyear_max,SIGNAL("valueChanged(int)"),self.slot_classyear_span_changed)
		
		typeorder = ['all'] + config.usertype_order
		for usertype_text in typeorder:
			if setupdict.has_key(usertype_text):
				self.m_cb_usertype_filter.insertItem(setupdict[usertype_text])
		
		# Setup group combo
		self.groups_to_combo()
	def createuser(self,uid,givenname,familyname,passwd,usertype,primarygid=1000,firstyear=None):
		"""
		Add a user to the schools authentication directory service.
		The usertype must be one of the constants TEACHER,STUDENT,PARENT or OTHER
		"""
		# check if the group exists already
		if self.user_exists(uid):
			return -10001
		
		title = userdef.usertype_as_text(usertype)
		if not title:
			return -10005	# invalid usertype id
		usertype_ou = ldapdef.ou_confkey_by_usertype(usertype)
		objectclass = ldapdef.objectclass_by_usertype(usertype)
		if not objectclass:
			return -10006	# Object classes have not been defined for this usertype
			
		path = "uid=%s,%s" % (uid,ldapdef.basedn_by_usertype(usertype))
		
		# Check the group for existance
		import groupmanager as gman
		gm = gman.GroupManager()
		gl = gm.list_groups(None)
		glgid = {}
		for groupname in gl.keys():
			glgid[int(gl[groupname]['gidNumber'])]=groupname
		if not glgid.has_key(primarygid):
			return -10004
		
		
		#uidnumber = self.max(conf.get('LDAPSERVER','basedn'),
		#		'objectclass=posixaccount','uidNumber',
		#		int(conf.get('DOMAIN','uid_start')))+1
		
		uidnumber = None
		uidnumbers = []
		for pw in pwd.getpwall():
			if int(pw[2]) >= int(conf.get('DOMAIN','uid_start')):
				uidnumbers += [int(pw[2])]
		uidnumbers.sort()
		expect_uidnumber = int(conf.get('DOMAIN','uid_start'))
		for i in range(100000):
			if expect_uidnumber != uidnumbers[i]:
				uidnumber = expect_uidnumber
				break
			expect_uidnumber += 1
		
		if uidnumber == None:
			return -10007 # failed to pick an uidnumber
		
		cn = '%s %s' % (givenname,familyname)

		user_info = {'uid':uid,
			'givenname':'%s' % givenname,
			'cn':cn,
			'gidNumber': str(primarygid),
			'uidnumber': str(uidnumber),
			'homeDirectory':'%s/%s/users/%s/.linux' % (conf.get('DOMAIN','domain_root'),conf.get('DOMAIN','domain_name'),uid),
			'sn':'%s' % familyname,
			'objectclass':objectclass,
			'mail': uid,
			'title':title,
			'loginShell': '/bin/zsh',
			'userPassword':mkpasswd(passwd,3,'ssha')}
		if userdef.usertype_as_id(usertype) == userdef.usertype_as_id('student') and firstyear != None:
			user_info['firstSchoolYear'] = str(firstyear)
			
		
		self.bind(conf.get('LDAPSERVER','admin'),conf.get('LDAPSERVER','passwd'))
		self.touch_by_dict({path:user_info})
		
		try:
			posix_uid = pwd.getpwnam(uid)[2]
		except Exception, e:
			print e
			return -10002
			print "The given username is invalid."
			exit(0)
		
		um = UserManager()
		if um.user_exists(username):
			print "The user %s already exists" % username
			exit(0)
		
		if not options.givenname:
			options.givenname = raw_input("Input the user's given name (first name): ")
		if not options.familyname:
			options.familyname = raw_input("Input the user's family name (last name): ")
		if not options.usertype:
			options.usertype = raw_input("Input the user's account type (teacher,student,parent or other): ")
		
		options.usertype = userdef.usertype_as_id(options.usertype)
		if not options.usertype:
			print "Invalid usertype"
			exit(0)
		
		import groupmanager as groupman
		gm = groupman.GroupManager()
		gl = gm.list_groups(None)
		while not options.primarygroup:
			options.primarygroup = raw_input("Input the user's primary group (type \"?\" to view all groups): ")
			if options.primarygroup.strip() == '?':
				gl = gm.list_groups(None)
				for group in gl.keys():
					desc = ''
					if gl[group].has_key('description'):
						desc = gl[group]['description']