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

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

Added configurable LDAP mail attribute support

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