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

Revision 1067, 33.6 kB (checked in by jalet, 21 years ago)

Bug fix due to a typo in LDAP code

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