root / pykota / trunk / pykota / storages / ldapstorage.py @ 1119

Revision 1119, 36.1 kB (checked in by jalet, 21 years ago)

Better user and group deletion

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2#
3# PyKota : Print Quotas for CUPS and LPRng
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.25  2003/08/20 15:56:24  jalet
24# Better user and group deletion
25#
26# Revision 1.24  2003/07/29 20:55:17  jalet
27# 1.14 is out !
28#
29# Revision 1.23  2003/07/29 19:52:32  jalet
30# Forgot to read the email field from LDAP
31#
32# Revision 1.22  2003/07/29 09:54:03  jalet
33# Added configurable LDAP mail attribute support
34#
35# Revision 1.21  2003/07/28 09:11:12  jalet
36# PyKota now tries to add its attributes intelligently in existing LDAP
37# directories.
38#
39# Revision 1.20  2003/07/25 10:41:30  jalet
40# Better documentation.
41# pykotme now displays the current user's account balance.
42# Some test changed in ldap module.
43#
44# Revision 1.19  2003/07/14 14:18:16  jalet
45# Wrong documentation strings
46#
47# Revision 1.18  2003/07/11 14:23:13  jalet
48# When adding an user only adds one object containing both the user and
49# its account balance instead of two objects.
50#
51# Revision 1.17  2003/07/07 12:51:07  jalet
52# Small fix
53#
54# Revision 1.16  2003/07/07 12:11:13  jalet
55# Small fix
56#
57# Revision 1.15  2003/07/07 11:49:24  jalet
58# Lots of small fixes with the help of PyChecker
59#
60# Revision 1.14  2003/07/07 08:33:18  jalet
61# Bug fix due to a typo in LDAP code
62#
63# Revision 1.13  2003/07/05 07:46:50  jalet
64# The previous bug fix was incomplete.
65#
66# Revision 1.12  2003/06/30 13:54:21  jalet
67# Sorts by user / group name
68#
69# Revision 1.11  2003/06/25 14:10:01  jalet
70# Hey, it may work (edpykota --reset excepted) !
71#
72# Revision 1.10  2003/06/16 21:55:15  jalet
73# More work on LDAP, again. Problem detected.
74#
75# Revision 1.9  2003/06/16 11:59:09  jalet
76# More work on LDAP
77#
78# Revision 1.8  2003/06/15 22:26:52  jalet
79# More work on LDAP
80#
81# Revision 1.7  2003/06/14 22:44:21  jalet
82# More work on LDAP storage backend.
83#
84# Revision 1.6  2003/06/13 19:07:57  jalet
85# Two big bugs fixed, time to release something ;-)
86#
87# Revision 1.5  2003/06/10 16:37:54  jalet
88# Deletion of the second user which is not needed anymore.
89# Added a debug configuration field in /etc/pykota.conf
90# All queries can now be sent to the logger in debug mode, this will
91# greatly help improve performance when time for this will come.
92#
93# Revision 1.4  2003/06/10 10:45:32  jalet
94# Not implemented methods now raise an exception when called.
95#
96# Revision 1.3  2003/06/06 20:49:15  jalet
97# Very latest schema. UNTESTED.
98#
99# Revision 1.2  2003/06/06 14:21:08  jalet
100# New LDAP schema.
101# Small bug fixes.
102#
103# Revision 1.1  2003/06/05 11:19:13  jalet
104# More good work on LDAP storage.
105#
106#
107#
108
109#
110# My IANA assigned number, for
111# "Conseil Internet & Logiciels Libres, J�me Alet"
112# is 16868. Use this as a base to create the LDAP schema.
113#
114
115import time
116import md5
117
118from pykota.storage import PyKotaStorageError
119from pykota.storage import StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
120
121try :
122    import ldap
123    from ldap import modlist
124except ImportError :   
125    import sys
126    # TODO : to translate or not to translate ?
127    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
128   
129class Storage :
130    def __init__(self, pykotatool, host, dbname, user, passwd) :
131        """Opens the LDAP connection."""
132        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
133        self.closed = 1
134        self.tool = pykotatool
135        self.debug = pykotatool.config.getDebug()
136        self.info = pykotatool.config.getLDAPInfo()
137        try :
138            self.database = ldap.initialize(host) 
139            self.database.simple_bind_s(user, passwd)
140            self.basedn = dbname
141        except ldap.SERVER_DOWN :   
142            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
143        except ldap.LDAPError :   
144            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
145        else :   
146            self.closed = 0
147            if self.debug :
148                self.tool.logger.log_message("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user), "debug")
149           
150    def __del__(self) :       
151        """Ensures that the database connection is closed."""
152        self.close()
153       
154    def close(self) :   
155        """Closes the database connection."""
156        if not self.closed :
157            del self.database
158            self.closed = 1
159            if self.debug :
160                self.tool.logger.log_message("Database closed.", "debug")
161       
162    def genUUID(self) :   
163        """Generates an unique identifier.
164       
165           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
166        """
167        return md5.md5("%s" % time.time()).hexdigest()
168       
169    def beginTransaction(self) :   
170        """Starts a transaction."""
171        if self.debug :
172            self.tool.logger.log_message("Transaction begins... WARNING : No transactions in LDAP !", "debug")
173       
174    def commitTransaction(self) :   
175        """Commits a transaction."""
176        if self.debug :
177            self.tool.logger.log_message("Transaction committed. WARNING : No transactions in LDAP !", "debug")
178       
179    def rollbackTransaction(self) :     
180        """Rollbacks a transaction."""
181        if self.debug :
182            self.tool.logger.log_message("Transaction aborted. WARNING : No transaction in LDAP !", "debug")
183       
184    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
185        """Does an LDAP search query."""
186        try :
187            base = base or self.basedn
188            if self.debug :
189                self.tool.logger.log_message("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields), "debug")
190            result = self.database.search_s(base or self.basedn, scope, key, fields)
191        except ldap.LDAPError :   
192            raise PyKotaStorageError, _("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)
193        else :     
194            if self.debug :
195                self.tool.logger.log_message("QUERY : Result : %s" % result, "debug")
196            return result
197           
198    def doAdd(self, dn, fields) :
199        """Adds an entry in the LDAP directory."""
200        try :
201            if self.debug :
202                self.tool.logger.log_message("QUERY : ADD(%s, %s)" % (dn, str(fields)), "debug")
203            self.database.add_s(dn, modlist.addModlist(fields))
204        except ldap.LDAPError :
205            raise PyKotaStorageError, _("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))
206        else :
207            return dn
208           
209    def doDelete(self, dn) :
210        """Deletes an entry from the LDAP directory."""
211        try :
212            if self.debug :
213                self.tool.logger.log_message("QUERY : Delete(%s)" % dn, "debug")
214            self.database.delete_s(dn)
215        except ldap.LDAPError :
216            raise PyKotaStorageError, _("Problem deleting LDAP entry (%s)") % dn
217           
218    def doModify(self, dn, fields, ignoreold=1) :
219        """Modifies an entry in the LDAP directory."""
220        try :
221            oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)
222            if self.debug :
223                self.tool.logger.log_message("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields), "debug")
224            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
225        except ldap.LDAPError :
226            raise PyKotaStorageError, _("Problem modifying LDAP entry (%s, %s)") % (dn, fields)
227        else :
228            return dn
229           
230    def getUser(self, username) :   
231        """Extracts user information given its name."""
232        user = StorageUser(self, username)
233        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
234        if result :
235            fields = result[0][1]
236            user.ident = result[0][0]
237            user.Email = fields.get(self.info["usermail"])
238            if user.Email is not None :
239                user.Email = user.Email[0]
240            user.LimitBy = fields.get("pykotaLimitBy")
241            if user.LimitBy is not None :
242                user.LimitBy = user.LimitBy[0]
243            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"], base=self.info["balancebase"])
244            if result :
245                fields = result[0][1]
246                user.idbalance = result[0][0]
247                user.AccountBalance = fields.get("pykotaBalance")
248                if user.AccountBalance is not None :
249                    if user.AccountBalance[0].upper() == "NONE" :
250                        user.AccountBalance = None
251                    else :   
252                        user.AccountBalance = float(user.AccountBalance[0])
253                user.AccountBalance = user.AccountBalance or 0.0       
254                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
255                if user.LifeTimePaid is not None :
256                    if user.LifeTimePaid[0].upper() == "NONE" :
257                        user.LifeTimePaid = None
258                    else :   
259                        user.LifeTimePaid = float(user.LifeTimePaid[0])
260                user.LifeTimePaid = user.LifeTimePaid or 0.0       
261            user.Exists = 1
262        return user
263       
264    def getGroup(self, groupname) :   
265        """Extracts group information given its name."""
266        group = StorageGroup(self, groupname)
267        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"], base=self.info["groupbase"])
268        if result :
269            fields = result[0][1]
270            group.ident = result[0][0]
271            group.LimitBy = fields.get("pykotaLimitBy")
272            if group.LimitBy is not None :
273                group.LimitBy = group.LimitBy[0]
274            group.AccountBalance = 0.0
275            group.LifeTimePaid = 0.0
276            group.Members = self.getGroupMembers(group)
277            for member in group.Members :
278                if member.Exists :
279                    group.AccountBalance += member.AccountBalance
280                    group.LifeTimePaid += member.LifeTimePaid
281            group.Exists = 1
282        return group
283       
284    def getPrinter(self, printername) :       
285        """Extracts printer information given its name."""
286        printer = StoragePrinter(self, printername)
287        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
288        if result :
289            fields = result[0][1]
290            printer.ident = result[0][0]
291            printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
292            printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
293            printer.LastJob = self.getPrinterLastJob(printer)
294            printer.Exists = 1
295        return printer   
296           
297    def getUserGroups(self, user) :       
298        """Returns the user's groups list."""
299        groups = []
300        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"]], base=self.info["groupbase"])
301        if result :
302            for (groupid, fields) in result :
303                groups.append(self.getGroup(fields.get(self.info["grouprdn"])[0]))
304        return groups       
305       
306    def getGroupMembers(self, group) :       
307        """Returns the group's members list."""
308        groupmembers = []
309        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
310        if result :
311            for username in result[0][1].get(self.info["groupmembers"], []) :
312                groupmembers.append(self.getUser(username))
313        return groupmembers       
314       
315    def getUserPQuota(self, user, printer) :       
316        """Extracts a user print quota."""
317        userpquota = StorageUserPQuota(self, user, printer)
318        if user.Exists :
319            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
320            if result :
321                fields = result[0][1]
322                userpquota.ident = result[0][0]
323                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
324                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
325                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
326                if userpquota.SoftLimit is not None :
327                    if userpquota.SoftLimit[0].upper() == "NONE" :
328                        userpquota.SoftLimit = None
329                    else :   
330                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
331                userpquota.HardLimit = fields.get("pykotaHardLimit")
332                if userpquota.HardLimit is not None :
333                    if userpquota.HardLimit[0].upper() == "NONE" :
334                        userpquota.HardLimit = None
335                    elif userpquota.HardLimit is not None :   
336                        userpquota.HardLimit = int(userpquota.HardLimit[0])
337                userpquota.DateLimit = fields.get("pykotaDateLimit")
338                if userpquota.DateLimit is not None :
339                    if userpquota.DateLimit[0].upper() == "NONE" : 
340                        userpquota.DateLimit = None
341                    else :   
342                        userpquota.DateLimit = userpquota.DateLimit[0]
343                userpquota.Exists = 1
344        return userpquota
345       
346    def getGroupPQuota(self, group, printer) :       
347        """Extracts a group print quota."""
348        grouppquota = StorageGroupPQuota(self, group, printer)
349        if group.Exists :
350            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
351            if result :
352                fields = result[0][1]
353                grouppquota.ident = result[0][0]
354                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
355                if grouppquota.SoftLimit is not None :
356                    if grouppquota.SoftLimit[0].upper() == "NONE" :
357                        grouppquota.SoftLimit = None
358                    else :   
359                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
360                grouppquota.HardLimit = fields.get("pykotaHardLimit")
361                if grouppquota.HardLimit is not None :
362                    if grouppquota.HardLimit[0].upper() == "NONE" :
363                        grouppquota.HardLimit = None
364                    else :   
365                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
366                grouppquota.DateLimit = fields.get("pykotaDateLimit")
367                if grouppquota.DateLimit is not None :
368                    if grouppquota.DateLimit[0].upper() == "NONE" : 
369                        grouppquota.DateLimit = None
370                    else :   
371                        grouppquota.DateLimit = grouppquota.DateLimit[0]
372                grouppquota.PageCounter = 0
373                grouppquota.LifePageCounter = 0
374                if (not hasattr(group, "Members")) or (group.Members is None) :
375                    group.Members = self.getGroupMembers(group)
376                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in group.Members])
377                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
378                if result :
379                    for userpquota in result :   
380                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter")[0] or 0)
381                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter")[0] or 0)
382                grouppquota.Exists = 1
383        return grouppquota
384       
385    def getPrinterLastJob(self, printer) :       
386        """Extracts a printer's last job information."""
387        lastjob = StorageLastJob(self, printer)
388        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
389        if result :
390            lastjob.lastjobident = result[0][0]
391            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
392            result = self.doSearch("objectClass=pykotaJob", ["pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
393            if result :
394                fields = result[0][1]
395                lastjob.ident = result[0][0]
396                lastjob.JobId = fields.get("pykotaJobId")[0]
397                lastjob.User = self.getUser(fields.get("pykotaUserName")[0])
398                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
399                lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
400                lastjob.JobAction = fields.get("pykotaAction")[0]
401                date = fields.get("createTimestamp")[0]
402                year = int(date[:4])
403                month = int(date[4:6])
404                day = int(date[6:8])
405                hour = int(date[8:10])
406                minute = int(date[10:12])
407                second = int(date[12:14])
408                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
409                lastjob.Exists = 1
410        return lastjob
411       
412    def getMatchingPrinters(self, printerpattern) :
413        """Returns the list of all printers for which name matches a certain pattern."""
414        printers = []
415        # see comment at the same place in pgstorage.py
416        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
417        if result :
418            for (printerid, fields) in result :
419                printername = fields["pykotaPrinterName"][0]
420                if self.tool.matchString(printername, [ printerpattern ]) :
421                    printer = StoragePrinter(self, printername)
422                    printer.ident = printerid
423                    printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
424                    printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
425                    printer.LastJob = self.getPrinterLastJob(printer)
426                    printer.Exists = 1
427                    printers.append(printer)
428        return printers       
429       
430    def getPrinterUsersAndQuotas(self, printer, names=None) :       
431        """Returns the list of users who uses a given printer, along with their quotas."""
432        usersandquotas = []
433        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
434        if result :
435            for (userquotaid, fields) in result :
436                user = self.getUser(fields["pykotaUserName"][0])
437                if (names is None) or self.tool.matchString(user.Name, names) :
438                    userpquota = StorageUserPQuota(self, user, printer)
439                    userpquota.ident = userquotaid
440                    userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
441                    userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
442                    userpquota.SoftLimit = fields.get("pykotaSoftLimit")
443                    if userpquota.SoftLimit is not None :
444                        if userpquota.SoftLimit[0].upper() == "NONE" :
445                            userpquota.SoftLimit = None
446                        else :   
447                            userpquota.SoftLimit = int(userpquota.SoftLimit[0])
448                    userpquota.HardLimit = fields.get("pykotaHardLimit")
449                    if userpquota.HardLimit is not None :
450                        if userpquota.HardLimit[0].upper() == "NONE" :
451                            userpquota.HardLimit = None
452                        elif userpquota.HardLimit is not None :   
453                            userpquota.HardLimit = int(userpquota.HardLimit[0])
454                    userpquota.DateLimit = fields.get("pykotaDateLimit")
455                    if userpquota.DateLimit is not None :
456                        if userpquota.DateLimit[0].upper() == "NONE" : 
457                            userpquota.DateLimit = None
458                        else :   
459                            userpquota.DateLimit = userpquota.DateLimit[0]
460                    userpquota.Exists = 1
461                    usersandquotas.append((user, userpquota))
462        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
463        return usersandquotas
464               
465    def getPrinterGroupsAndQuotas(self, printer, names=None) :       
466        """Returns the list of groups which uses a given printer, along with their quotas."""
467        groupsandquotas = []
468        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
469        if result :
470            for (groupquotaid, fields) in result :
471                group = self.getGroup(fields.get("pykotaGroupName")[0])
472                if (names is None) or self.tool.matchString(group.Name, names) :
473                    grouppquota = self.getGroupPQuota(group, printer)
474                    groupsandquotas.append((group, grouppquota))
475        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
476        return groupsandquotas
477       
478    def addPrinter(self, printername) :       
479        """Adds a printer to the quota storage, returns it."""
480        fields = { self.info["printerrdn"] : printername,
481                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
482                   "cn" : printername,
483                   "pykotaPrinterName" : printername,
484                   "pykotaPricePerPage" : "0.0",
485                   "pykotaPricePerJob" : "0.0",
486                 } 
487        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
488        self.doAdd(dn, fields)
489        return self.getPrinter(printername)
490       
491    def addUser(self, user) :       
492        """Adds a user to the quota storage, returns it."""
493        newfields = {
494                       "pykotaUserName" : user.Name,
495                       "pykotaLimitBY" : (user.LimitBy or "quota"),
496                       "pykotaBalance" : str(user.AccountBalance or 0.0),
497                       "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0),
498                    }   
499        mustadd = 1
500        if self.info["newuser"].lower() != 'below' :
501            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newuser"], self.info["userrdn"], user.Name), None, base=self.info["userbase"])
502            if result :
503                (dn, fields) = result[0]
504                fields["objectClass"].extend(["pykotaAccount", "pykotaAccountBalance"])
505                fields.update(newfields)
506                self.doModify(dn, fields)
507                mustadd = 0
508               
509        if mustadd :
510            fields = { self.info["userrdn"] : user.Name,
511                       "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
512                       "cn" : user.Name,
513                     } 
514            fields.update(newfields)         
515            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
516            self.doAdd(dn, fields)
517        return self.getUser(user.Name)
518       
519    def addGroup(self, group) :       
520        """Adds a group to the quota storage, returns it."""
521        newfields = { 
522                      "pykotaGroupName" : group.Name,
523                      "pykotaLimitBY" : (group.LimitBy or "quota"),
524                    } 
525        mustadd = 1
526        if self.info["newgroup"].lower() != 'below' :
527            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newgroup"], self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
528            if result :
529                (dn, fields) = result[0]
530                fields["objectClass"].extend(["pykotaGroup"])
531                fields.update(newfields)
532                self.doModify(dn, fields)
533                mustadd = 0
534               
535        if mustadd :
536            fields = { self.info["grouprdn"] : group.Name,
537                       "objectClass" : ["pykotaObject", "pykotaGroup"],
538                       "cn" : group.Name,
539                     } 
540            fields.update(newfields)         
541            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
542            self.doAdd(dn, fields)
543        return self.getGroup(group.Name)
544       
545    def addUserToGroup(self, user, group) :   
546        """Adds an user to a group."""
547        if user.Name not in [u.Name for u in group.Members] :
548            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
549            if result :
550                fields = result[0][1]
551                if not fields.has_key(self.info["groupmembers"]) :
552                    fields[self.info["groupmembers"]] = []
553                fields[self.info["groupmembers"]].append(user.Name)
554                self.doModify(group.ident, fields)
555                group.Members.append(user)
556               
557    def addUserPQuota(self, user, printer) :
558        """Initializes a user print quota on a printer."""
559        uuid = self.genUUID()
560        fields = { "cn" : uuid,
561                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
562                   "pykotaUserName" : user.Name,
563                   "pykotaPrinterName" : printer.Name,
564                   "pykotaDateLimit" : "None",
565                   "pykotaPageCounter" : "0",
566                   "pykotaLifePageCounter" : "0",
567                 } 
568        dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
569        self.doAdd(dn, fields)
570        return self.getUserPQuota(user, printer)
571       
572    def addGroupPQuota(self, group, printer) :
573        """Initializes a group print quota on a printer."""
574        uuid = self.genUUID()
575        fields = { "cn" : uuid,
576                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
577                   "pykotaGroupName" : group.Name,
578                   "pykotaPrinterName" : printer.Name,
579                   "pykotaDateLimit" : "None",
580                 } 
581        dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
582        self.doAdd(dn, fields)
583        return self.getGroupPQuota(group, printer)
584       
585    def writePrinterPrices(self, printer) :   
586        """Write the printer's prices back into the storage."""
587        fields = {
588                   "pykotaPricePerPage" : str(printer.PricePerPage),
589                   "pykotaPricePerJob" : str(printer.PricePerJob),
590                 }
591        self.doModify(printer.ident, fields)
592       
593    def writeUserLimitBy(self, user, limitby) :   
594        """Sets the user's limiting factor."""
595        fields = {
596                   "pykotaLimitBy" : limitby,
597                 }
598        self.doModify(user.ident, fields)         
599       
600    def writeGroupLimitBy(self, group, limitby) :   
601        """Sets the group's limiting factor."""
602        fields = {
603                   "pykotaLimitBy" : limitby,
604                 }
605        self.doModify(group.ident, fields)         
606       
607    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
608        """Sets the date limit permanently for a user print quota."""
609        fields = {
610                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
611                 }
612        return self.doModify(userpquota.ident, fields)
613           
614    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
615        """Sets the date limit permanently for a group print quota."""
616        fields = {
617                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
618                 }
619        return self.doModify(grouppquota.ident, fields)
620       
621    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
622        """Sets the new page counters permanently for a user print quota."""
623        fields = {
624                   "pykotaPageCounter" : str(newpagecounter),
625                   "pykotaLifePageCounter" : str(newlifepagecounter),
626                 } 
627        return self.doModify(userpquota.ident, fields)         
628       
629    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
630        """Sets the new account balance and eventually new lifetime paid."""
631        fields = {
632                   "pykotaBalance" : str(newbalance),
633                 }
634        if newlifetimepaid is not None :
635            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
636        return self.doModify(user.idbalance, fields)         
637           
638    def writeLastJobSize(self, lastjob, jobsize) :       
639        """Sets the last job's size permanently."""
640        fields = {
641                   "pykotaJobSize" : str(jobsize),
642                 }
643        self.doModify(lastjob.ident, fields)         
644       
645    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :   
646        """Adds a job in a printer's history."""
647        uuid = self.genUUID()
648        fields = {
649                   "objectClass" : ["pykotaObject", "pykotaJob"],
650                   "cn" : uuid,
651                   "pykotaUserName" : user.Name,
652                   "pykotaPrinterName" : printer.Name,
653                   "pykotaJobId" : jobid,
654                   "pykotaPrinterPageCounter" : str(pagecounter),
655                   "pykotaAction" : action,
656                 }
657        if jobsize is not None :         
658            fields.update({ "pykotaJobSize" : str(jobsize) })
659        dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
660        self.doAdd(dn, fields)
661        if printer.LastJob.Exists :
662            fields = {
663                       "pykotaLastJobIdent" : uuid,
664                     }
665            self.doModify(printer.LastJob.lastjobident, fields)         
666        else :   
667            lastjuuid = self.genUUID()
668            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
669            fields = {
670                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
671                       "cn" : lastjuuid,
672                       "pykotaPrinterName" : printer.Name,
673                       "pykotaLastJobIdent" : uuid,
674                     } 
675            self.doAdd(lastjdn, fields)         
676           
677    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
678        """Sets soft and hard limits for a user quota."""
679        fields = { 
680                   "pykotaSoftLimit" : str(softlimit),
681                   "pykotaHardLimit" : str(hardlimit),
682                 }
683        self.doModify(userpquota.ident, fields)
684       
685    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
686        """Sets soft and hard limits for a group quota on a specific printer."""
687        fields = { 
688                   "pykotaSoftLimit" : str(softlimit),
689                   "pykotaHardLimit" : str(hardlimit),
690                 }
691        self.doModify(grouppquota.ident, fields)
692           
693    def deleteUser(self, user) :   
694        """Completely deletes an user from the Quota Storage."""
695        # TODO : What should we do if we delete the last person who used a given printer ?
696        # TODO : we can't reassign the last job to the previous one, because next user would be
697        # TODO : incorrectly charged (overcharged).
698        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaUserName=%s))" % user.Name, base=self.info["lastjobbase"])
699        for (ident, fields) in result :
700            self.doDelete(ident)
701        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
702        for (ident, fields) in result :
703            self.doDelete(ident)
704        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["userquotabase"])
705        for (ident, fields) in result :
706            self.doDelete(ident)
707        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
708        if result :
709            fields = result[0][1]
710            for k in fields.keys() :
711                if k.startswith("pykota") :
712                    del fields[k]
713                elif k.lower() == "objectclass" :   
714                    todelete = []
715                    for i in range(len(fields[k])) :
716                        if fields[k][i].startswith("pykota") : 
717                            todelete.append(i)
718                    todelete.sort()       
719                    todelete.reverse()
720                    for i in todelete :
721                        del fields[k][i]
722            if fields.get("objectClass") or fields.get("objectclass") :
723                self.doModify(user.ident, fields, ignoreold=0)       
724            else :   
725                self.doDelete(user.ident)
726        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
727        for (ident, fields) in result :
728            self.doDelete(ident)
729       
730    def deleteGroup(self, group) :   
731        """Completely deletes a group from the Quota Storage."""
732        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
733        for (ident, fields) in result :
734            self.doDelete(ident)
735        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
736        if result :
737            fields = result[0][1]
738            for k in fields.keys() :
739                if k.startswith("pykota") :
740                    del fields[k]
741                elif k.lower() == "objectclass" :   
742                    todelete = []
743                    for i in range(len(fields[k])) :
744                        if fields[k][i].startswith("pykota") : 
745                            todelete.append(i)
746                    todelete.sort()       
747                    todelete.reverse()
748                    for i in todelete :
749                        del fields[k][i]
750            if fields.get("objectClass") or fields.get("objectclass") :
751                self.doModify(group.ident, fields, ignoreold=0)       
752            else :   
753                self.doDelete(group.ident)
754           
Note: See TracBrowser for help on using the browser.