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

Revision 1144, 36.1 kB (checked in by jalet, 21 years ago)

Character encoding added to please latest version of Python

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