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

Revision 1137, 35.7 kB (checked in by jalet, 21 years ago)

More work on caching

  • 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.29  2003/10/06 13:12:28  jalet
24# More work on caching
25#
26# Revision 1.28  2003/10/03 12:27:02  jalet
27# Several optimizations, especially with LDAP backend
28#
29# Revision 1.27  2003/10/03 08:57:55  jalet
30# Caching mechanism now caches all that's cacheable.
31#
32# Revision 1.26  2003/10/02 20:23:18  jalet
33# Storage caching mechanism added.
34#
35# Revision 1.25  2003/08/20 15:56:24  jalet
36# Better user and group deletion
37#
38# Revision 1.24  2003/07/29 20:55:17  jalet
39# 1.14 is out !
40#
41# Revision 1.23  2003/07/29 19:52:32  jalet
42# Forgot to read the email field from LDAP
43#
44# Revision 1.22  2003/07/29 09:54:03  jalet
45# Added configurable LDAP mail attribute support
46#
47# Revision 1.21  2003/07/28 09:11:12  jalet
48# PyKota now tries to add its attributes intelligently in existing LDAP
49# directories.
50#
51# Revision 1.20  2003/07/25 10:41:30  jalet
52# Better documentation.
53# pykotme now displays the current user's account balance.
54# Some test changed in ldap module.
55#
56# Revision 1.19  2003/07/14 14:18:16  jalet
57# Wrong documentation strings
58#
59# Revision 1.18  2003/07/11 14:23:13  jalet
60# When adding an user only adds one object containing both the user and
61# its account balance instead of two objects.
62#
63# Revision 1.17  2003/07/07 12:51:07  jalet
64# Small fix
65#
66# Revision 1.16  2003/07/07 12:11:13  jalet
67# Small fix
68#
69# Revision 1.15  2003/07/07 11:49:24  jalet
70# Lots of small fixes with the help of PyChecker
71#
72# Revision 1.14  2003/07/07 08:33:18  jalet
73# Bug fix due to a typo in LDAP code
74#
75# Revision 1.13  2003/07/05 07:46:50  jalet
76# The previous bug fix was incomplete.
77#
78# Revision 1.12  2003/06/30 13:54:21  jalet
79# Sorts by user / group name
80#
81# Revision 1.11  2003/06/25 14:10:01  jalet
82# Hey, it may work (edpykota --reset excepted) !
83#
84# Revision 1.10  2003/06/16 21:55:15  jalet
85# More work on LDAP, again. Problem detected.
86#
87# Revision 1.9  2003/06/16 11:59:09  jalet
88# More work on LDAP
89#
90# Revision 1.8  2003/06/15 22:26:52  jalet
91# More work on LDAP
92#
93# Revision 1.7  2003/06/14 22:44:21  jalet
94# More work on LDAP storage backend.
95#
96# Revision 1.6  2003/06/13 19:07:57  jalet
97# Two big bugs fixed, time to release something ;-)
98#
99# Revision 1.5  2003/06/10 16:37:54  jalet
100# Deletion of the second user which is not needed anymore.
101# Added a debug configuration field in /etc/pykota.conf
102# All queries can now be sent to the logger in debug mode, this will
103# greatly help improve performance when time for this will come.
104#
105# Revision 1.4  2003/06/10 10:45:32  jalet
106# Not implemented methods now raise an exception when called.
107#
108# Revision 1.3  2003/06/06 20:49:15  jalet
109# Very latest schema. UNTESTED.
110#
111# Revision 1.2  2003/06/06 14:21:08  jalet
112# New LDAP schema.
113# Small bug fixes.
114#
115# Revision 1.1  2003/06/05 11:19:13  jalet
116# More good work on LDAP storage.
117#
118#
119#
120
121#
122# My IANA assigned number, for
123# "Conseil Internet & Logiciels Libres, J�me Alet"
124# is 16868. Use this as a base to create the LDAP schema.
125#
126
127import time
128import md5
129
130from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
131
132try :
133    import ldap
134    from ldap import modlist
135except ImportError :   
136    import sys
137    # TODO : to translate or not to translate ?
138    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
139   
140class Storage(BaseStorage) :
141    def __init__(self, pykotatool, host, dbname, user, passwd) :
142        """Opens the LDAP connection."""
143        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
144        BaseStorage.__init__(self, pykotatool)
145        self.info = pykotatool.config.getLDAPInfo()
146        try :
147            self.database = ldap.initialize(host) 
148            self.database.simple_bind_s(user, passwd)
149            self.basedn = dbname
150        except ldap.SERVER_DOWN :   
151            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
152        except ldap.LDAPError :   
153            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
154        else :   
155            self.closed = 0
156            self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user))
157           
158    def close(self) :   
159        """Closes the database connection."""
160        if not self.closed :
161            del self.database
162            self.closed = 1
163            self.tool.logdebug("Database closed.")
164       
165    def genUUID(self) :   
166        """Generates an unique identifier.
167       
168           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
169        """
170        return md5.md5("%s" % time.time()).hexdigest()
171       
172    def beginTransaction(self) :   
173        """Starts a transaction."""
174        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
175       
176    def commitTransaction(self) :   
177        """Commits a transaction."""
178        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
179       
180    def rollbackTransaction(self) :     
181        """Rollbacks a transaction."""
182        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
183       
184    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
185        """Does an LDAP search query."""
186        try :
187            base = base or self.basedn
188            self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
189            result = self.database.search_s(base or self.basedn, scope, key, fields)
190        except ldap.LDAPError :   
191            raise PyKotaStorageError, _("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)
192        else :     
193            self.tool.logdebug("QUERY : Result : %s" % result)
194            return result
195           
196    def doAdd(self, dn, fields) :
197        """Adds an entry in the LDAP directory."""
198        try :
199            self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
200            self.database.add_s(dn, modlist.addModlist(fields))
201        except ldap.LDAPError :
202            raise PyKotaStorageError, _("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))
203        else :
204            return dn
205           
206    def doDelete(self, dn) :
207        """Deletes an entry from the LDAP directory."""
208        try :
209            self.tool.logdebug("QUERY : Delete(%s)" % dn)
210            self.database.delete_s(dn)
211        except ldap.LDAPError :
212            raise PyKotaStorageError, _("Problem deleting LDAP entry (%s)") % dn
213           
214    def doModify(self, dn, fields, ignoreold=1) :
215        """Modifies an entry in the LDAP directory."""
216        try :
217            oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)
218            self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields))
219            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
220        except ldap.LDAPError :
221            raise PyKotaStorageError, _("Problem modifying LDAP entry (%s, %s)") % (dn, fields)
222        else :
223            return dn
224           
225    def getUserFromBackend(self, username) :   
226        """Extracts user information given its name."""
227        user = StorageUser(self, username)
228        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
229        if result :
230            fields = result[0][1]
231            user.ident = result[0][0]
232            user.Email = fields.get(self.info["usermail"])
233            if user.Email is not None :
234                user.Email = user.Email[0]
235            user.LimitBy = fields.get("pykotaLimitBy")
236            if user.LimitBy is not None :
237                user.LimitBy = user.LimitBy[0]
238            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"], base=self.info["balancebase"])
239            if result :
240                fields = result[0][1]
241                user.idbalance = result[0][0]
242                user.AccountBalance = fields.get("pykotaBalance")
243                if user.AccountBalance is not None :
244                    if user.AccountBalance[0].upper() == "NONE" :
245                        user.AccountBalance = None
246                    else :   
247                        user.AccountBalance = float(user.AccountBalance[0])
248                user.AccountBalance = user.AccountBalance or 0.0       
249                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
250                if user.LifeTimePaid is not None :
251                    if user.LifeTimePaid[0].upper() == "NONE" :
252                        user.LifeTimePaid = None
253                    else :   
254                        user.LifeTimePaid = float(user.LifeTimePaid[0])
255                user.LifeTimePaid = user.LifeTimePaid or 0.0       
256            user.Exists = 1
257        return user
258       
259    def getGroupFromBackend(self, groupname) :   
260        """Extracts group information given its name."""
261        group = StorageGroup(self, groupname)
262        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"], base=self.info["groupbase"])
263        if result :
264            fields = result[0][1]
265            group.ident = result[0][0]
266            group.LimitBy = fields.get("pykotaLimitBy")
267            if group.LimitBy is not None :
268                group.LimitBy = group.LimitBy[0]
269            group.AccountBalance = 0.0
270            group.LifeTimePaid = 0.0
271            for member in self.getGroupMembers(group) :
272                if member.Exists :
273                    group.AccountBalance += member.AccountBalance
274                    group.LifeTimePaid += member.LifeTimePaid
275            group.Exists = 1
276        return group
277       
278    def getPrinterFromBackend(self, printername) :       
279        """Extracts printer information given its name."""
280        printer = StoragePrinter(self, printername)
281        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
282        if result :
283            fields = result[0][1]
284            printer.ident = result[0][0]
285            printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
286            printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
287            printer.LastJob = self.getPrinterLastJob(printer)
288            printer.Exists = 1
289        return printer   
290       
291    def getUserPQuotaFromBackend(self, user, printer) :       
292        """Extracts a user print quota."""
293        userpquota = StorageUserPQuota(self, user, printer)
294        if user.Exists :
295            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
296            if result :
297                fields = result[0][1]
298                userpquota.ident = result[0][0]
299                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
300                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
301                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
302                if userpquota.SoftLimit is not None :
303                    if userpquota.SoftLimit[0].upper() == "NONE" :
304                        userpquota.SoftLimit = None
305                    else :   
306                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
307                userpquota.HardLimit = fields.get("pykotaHardLimit")
308                if userpquota.HardLimit is not None :
309                    if userpquota.HardLimit[0].upper() == "NONE" :
310                        userpquota.HardLimit = None
311                    elif userpquota.HardLimit is not None :   
312                        userpquota.HardLimit = int(userpquota.HardLimit[0])
313                userpquota.DateLimit = fields.get("pykotaDateLimit")
314                if userpquota.DateLimit is not None :
315                    if userpquota.DateLimit[0].upper() == "NONE" : 
316                        userpquota.DateLimit = None
317                    else :   
318                        userpquota.DateLimit = userpquota.DateLimit[0]
319                userpquota.Exists = 1
320        return userpquota
321       
322    def getGroupPQuotaFromBackend(self, group, printer) :       
323        """Extracts a group print quota."""
324        grouppquota = StorageGroupPQuota(self, group, printer)
325        if group.Exists :
326            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
327            if result :
328                fields = result[0][1]
329                grouppquota.ident = result[0][0]
330                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
331                if grouppquota.SoftLimit is not None :
332                    if grouppquota.SoftLimit[0].upper() == "NONE" :
333                        grouppquota.SoftLimit = None
334                    else :   
335                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
336                grouppquota.HardLimit = fields.get("pykotaHardLimit")
337                if grouppquota.HardLimit is not None :
338                    if grouppquota.HardLimit[0].upper() == "NONE" :
339                        grouppquota.HardLimit = None
340                    else :   
341                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
342                grouppquota.DateLimit = fields.get("pykotaDateLimit")
343                if grouppquota.DateLimit is not None :
344                    if grouppquota.DateLimit[0].upper() == "NONE" : 
345                        grouppquota.DateLimit = None
346                    else :   
347                        grouppquota.DateLimit = grouppquota.DateLimit[0]
348                grouppquota.PageCounter = 0
349                grouppquota.LifePageCounter = 0
350                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in group.Members])
351                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
352                if result :
353                    for userpquota in result :   
354                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter")[0] or 0)
355                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter")[0] or 0)
356                grouppquota.Exists = 1
357        return grouppquota
358       
359    def getPrinterLastJobFromBackend(self, printer) :       
360        """Extracts a printer's last job information."""
361        lastjob = StorageLastJob(self, printer)
362        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
363        if result :
364            lastjob.lastjobident = result[0][0]
365            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
366            result = self.doSearch("objectClass=pykotaJob", ["pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
367            if result :
368                fields = result[0][1]
369                lastjob.ident = result[0][0]
370                lastjob.JobId = fields.get("pykotaJobId")[0]
371                lastjob.User = self.getUser(fields.get("pykotaUserName")[0])
372                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
373                lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
374                lastjob.JobAction = fields.get("pykotaAction")[0]
375                date = fields.get("createTimestamp")[0]
376                year = int(date[:4])
377                month = int(date[4:6])
378                day = int(date[6:8])
379                hour = int(date[8:10])
380                minute = int(date[10:12])
381                second = int(date[12:14])
382                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
383                lastjob.Exists = 1
384        return lastjob
385       
386    def getGroupMembersFromBackend(self, group) :       
387        """Returns the group's members list."""
388        groupmembers = []
389        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
390        if result :
391            for username in result[0][1].get(self.info["groupmembers"], []) :
392                groupmembers.append(self.getUser(username))
393        return groupmembers       
394       
395    def getUserGroupsFromBackend(self, user) :       
396        """Returns the user's groups list."""
397        groups = []
398        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"]], base=self.info["groupbase"])
399        if result :
400            for (groupid, fields) in result :
401                groups.append(self.getGroup(fields.get(self.info["grouprdn"])[0]))
402        return groups       
403       
404    def getMatchingPrinters(self, printerpattern) :
405        """Returns the list of all printers for which name matches a certain pattern."""
406        printers = []
407        # see comment at the same place in pgstorage.py
408        result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)" % pname for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
409        if result :
410            for (printerid, fields) in result :
411                printername = fields["pykotaPrinterName"][0]
412                printer = StoragePrinter(self, printername)
413                printer.ident = printerid
414                printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
415                printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
416                printer.LastJob = self.getPrinterLastJob(printer)
417                printer.Exists = 1
418                printers.append(printer)
419                self.cacheEntry("PRINTERS", printer.Name, printer)
420        return printers       
421       
422    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
423        """Returns the list of users who uses a given printer, along with their quotas."""
424        usersandquotas = []
425        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaUserName=%s)" % uname for uname in names])), ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
426        if result :
427            for (userquotaid, fields) in result :
428                user = self.getUser(fields.get("pykotaUserName")[0])
429                userpquota = StorageUserPQuota(self, user, printer)
430                userpquota.ident = userquotaid
431                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
432                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
433                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
434                if userpquota.SoftLimit is not None :
435                    if userpquota.SoftLimit[0].upper() == "NONE" :
436                        userpquota.SoftLimit = None
437                    else :   
438                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
439                userpquota.HardLimit = fields.get("pykotaHardLimit")
440                if userpquota.HardLimit is not None :
441                    if userpquota.HardLimit[0].upper() == "NONE" :
442                        userpquota.HardLimit = None
443                    elif userpquota.HardLimit is not None :   
444                        userpquota.HardLimit = int(userpquota.HardLimit[0])
445                userpquota.DateLimit = fields.get("pykotaDateLimit")
446                if userpquota.DateLimit is not None :
447                    if userpquota.DateLimit[0].upper() == "NONE" : 
448                        userpquota.DateLimit = None
449                    else :   
450                        userpquota.DateLimit = userpquota.DateLimit[0]
451                userpquota.Exists = 1
452                usersandquotas.append((user, userpquota))
453                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
454        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
455        return usersandquotas
456               
457    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
458        """Returns the list of groups which uses a given printer, along with their quotas."""
459        groupsandquotas = []
460        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=self.info["groupquotabase"])
461        if result :
462            for (groupquotaid, fields) in result :
463                group = self.getGroup(fields.get("pykotaGroupName")[0])
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.