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

Revision 1068, 33.7 kB (checked in by jalet, 21 years ago)

Lots of small fixes with the help of PyChecker?

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