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

Revision 1099, 34.1 kB (checked in by jalet, 21 years ago)

Better documentation.
pykotme now displays the current user's account balance.
Some test changed in ldap module.

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