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

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

Forgot to read the email field from LDAP

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