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

Revision 1070, 33.8 kB (checked in by jalet, 21 years ago)

Small fix

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