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

Revision 1113, 36.0 kB (checked in by jalet, 21 years ago)

1.14 is out !

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