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

Revision 1041, 33.0 kB (checked in by jalet, 21 years ago)

Hey, it may work (edpykota --reset excepted) !

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