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

Revision 1130, 35.5 kB (checked in by jalet, 21 years ago)

Storage caching mechanism added.

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