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

Revision 1131, 35.8 kB (checked in by jalet, 21 years ago)

Caching mechanism now caches all that's cacheable.

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