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

Revision 1051, 33.2 kB (checked in by jalet, 21 years ago)

Sorts by user / group name

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