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

Revision 1348, 49.0 kB (checked in by jalet, 20 years ago)

Preliminary work on low-level LDAP specific cache.

  • 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-2004 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.52  2004/02/17 23:41:48  jalet
25# Preliminary work on low-level LDAP specific cache.
26#
27# Revision 1.51  2004/02/04 13:24:41  jalet
28# pkprinters can now remove printers from printers groups.
29#
30# Revision 1.50  2004/02/04 11:17:00  jalet
31# pkprinters command line tool added.
32#
33# Revision 1.49  2004/01/29 22:35:45  jalet
34# Small fix from Matt.
35#
36# Revision 1.48  2004/01/12 14:35:02  jalet
37# Printing history added to CGI script.
38#
39# Revision 1.47  2004/01/10 09:44:02  jalet
40# Fixed potential accuracy problem if a user printed on several printers at
41# the very same time.
42#
43# Revision 1.46  2004/01/08 16:33:27  jalet
44# Additionnal check to not create a circular printers group.
45#
46# Revision 1.45  2004/01/08 16:24:49  jalet
47# edpykota now supports adding printers to printer groups.
48#
49# Revision 1.44  2004/01/08 14:10:33  jalet
50# Copyright year changed.
51#
52# Revision 1.43  2004/01/06 14:24:59  jalet
53# Printer groups should be cached now, if caching is enabled.
54#
55# Revision 1.42  2003/12/29 14:12:48  uid67467
56# Tries to workaround possible integrity violations when retrieving printer groups
57#
58# Revision 1.41  2003/12/27 16:49:25  uid67467
59# Should be ok now.
60#
61# Revision 1.40  2003/11/29 22:02:14  jalet
62# Don't try to retrieve the user print quota information if current printer
63# doesn't exist.
64#
65# Revision 1.39  2003/11/26 23:35:32  jalet
66# Added a bit of code to support the setting of the user's email address
67# which was ignored during writes for now.
68#
69# Revision 1.38  2003/11/24 09:54:06  jalet
70# Small fix for LDAP when pykotaOptions attribute wasn't present.
71#
72# Revision 1.37  2003/11/23 19:01:37  jalet
73# Job price added to history
74#
75# Revision 1.36  2003/11/21 14:28:46  jalet
76# More complete job history.
77#
78# Revision 1.35  2003/11/12 13:06:37  jalet
79# Bug fix wrt no user/group name command line argument to edpykota
80#
81# Revision 1.34  2003/10/24 08:37:55  jalet
82# More complete messages in case of LDAP failure.
83# LDAP database connection is now unbound on exit too.
84#
85# Revision 1.33  2003/10/08 07:01:20  jalet
86# Job history can be disabled.
87# Some typos in README.
88# More messages in setup script.
89#
90# Revision 1.32  2003/10/07 14:23:25  jalet
91# More work on cache
92#
93# Revision 1.31  2003/10/07 09:07:30  jalet
94# Character encoding added to please latest version of Python
95#
96# Revision 1.30  2003/10/06 14:42:36  jalet
97# LDAP group access will be slower when cache is disabled, but at least code
98# is consistent with the rest of the caching mechanis, but at least code
99# is consistent with the rest of the caching mechanism
100#
101# Revision 1.29  2003/10/06 13:12:28  jalet
102# More work on caching
103#
104# Revision 1.28  2003/10/03 12:27:02  jalet
105# Several optimizations, especially with LDAP backend
106#
107# Revision 1.27  2003/10/03 08:57:55  jalet
108# Caching mechanism now caches all that's cacheable.
109#
110# Revision 1.26  2003/10/02 20:23:18  jalet
111# Storage caching mechanism added.
112#
113# Revision 1.25  2003/08/20 15:56:24  jalet
114# Better user and group deletion
115#
116# Revision 1.24  2003/07/29 20:55:17  jalet
117# 1.14 is out !
118#
119# Revision 1.23  2003/07/29 19:52:32  jalet
120# Forgot to read the email field from LDAP
121#
122# Revision 1.22  2003/07/29 09:54:03  jalet
123# Added configurable LDAP mail attribute support
124#
125# Revision 1.21  2003/07/28 09:11:12  jalet
126# PyKota now tries to add its attributes intelligently in existing LDAP
127# directories.
128#
129# Revision 1.20  2003/07/25 10:41:30  jalet
130# Better documentation.
131# pykotme now displays the current user's account balance.
132# Some test changed in ldap module.
133#
134# Revision 1.19  2003/07/14 14:18:16  jalet
135# Wrong documentation strings
136#
137# Revision 1.18  2003/07/11 14:23:13  jalet
138# When adding an user only adds one object containing both the user and
139# its account balance instead of two objects.
140#
141# Revision 1.17  2003/07/07 12:51:07  jalet
142# Small fix
143#
144# Revision 1.16  2003/07/07 12:11:13  jalet
145# Small fix
146#
147# Revision 1.15  2003/07/07 11:49:24  jalet
148# Lots of small fixes with the help of PyChecker
149#
150# Revision 1.14  2003/07/07 08:33:18  jalet
151# Bug fix due to a typo in LDAP code
152#
153# Revision 1.13  2003/07/05 07:46:50  jalet
154# The previous bug fix was incomplete.
155#
156# Revision 1.12  2003/06/30 13:54:21  jalet
157# Sorts by user / group name
158#
159# Revision 1.11  2003/06/25 14:10:01  jalet
160# Hey, it may work (edpykota --reset excepted) !
161#
162# Revision 1.10  2003/06/16 21:55:15  jalet
163# More work on LDAP, again. Problem detected.
164#
165# Revision 1.9  2003/06/16 11:59:09  jalet
166# More work on LDAP
167#
168# Revision 1.8  2003/06/15 22:26:52  jalet
169# More work on LDAP
170#
171# Revision 1.7  2003/06/14 22:44:21  jalet
172# More work on LDAP storage backend.
173#
174# Revision 1.6  2003/06/13 19:07:57  jalet
175# Two big bugs fixed, time to release something ;-)
176#
177# Revision 1.5  2003/06/10 16:37:54  jalet
178# Deletion of the second user which is not needed anymore.
179# Added a debug configuration field in /etc/pykota.conf
180# All queries can now be sent to the logger in debug mode, this will
181# greatly help improve performance when time for this will come.
182#
183# Revision 1.4  2003/06/10 10:45:32  jalet
184# Not implemented methods now raise an exception when called.
185#
186# Revision 1.3  2003/06/06 20:49:15  jalet
187# Very latest schema. UNTESTED.
188#
189# Revision 1.2  2003/06/06 14:21:08  jalet
190# New LDAP schema.
191# Small bug fixes.
192#
193# Revision 1.1  2003/06/05 11:19:13  jalet
194# More good work on LDAP storage.
195#
196#
197#
198
199#
200# My IANA assigned number, for
201# "Conseil Internet & Logiciels Libres, J�me Alet"
202# is 16868. Use this as a base to create the LDAP schema.
203#
204
205import types
206import time
207import md5
208
209from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
210
211try :
212    import ldap
213    from ldap import modlist
214except ImportError :   
215    import sys
216    # TODO : to translate or not to translate ?
217    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
218   
219class Storage(BaseStorage) :
220    def __init__(self, pykotatool, host, dbname, user, passwd) :
221        """Opens the LDAP connection."""
222        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
223        BaseStorage.__init__(self, pykotatool)
224        self.info = pykotatool.config.getLDAPInfo()
225        try :
226            self.database = ldap.initialize(host) 
227            self.database.simple_bind_s(user, passwd)
228            self.basedn = dbname
229        except ldap.SERVER_DOWN :   
230            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
231        except ldap.LDAPError :   
232            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
233        else :   
234            self.ldapcache = {} # low-level cache specific to LDAP backend
235            self.closed = 0
236            self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user))
237           
238    def close(self) :   
239        """Closes the database connection."""
240        if not self.closed :
241            self.database.unbind_s()
242            self.closed = 1
243            self.tool.logdebug("Database closed.")
244       
245    def genUUID(self) :   
246        """Generates an unique identifier.
247       
248           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
249        """
250        return md5.md5("%s" % time.time()).hexdigest()
251       
252    def normalizeFields(self, fields) :   
253        """Ensure all items are lists."""
254        for (k, v) in fields.items() :
255            if type(v) not in (types.TupleType, types.ListType) :
256                if not v :
257                    del fields[k]
258                else :   
259                    fields[k] = [ v ]
260        return fields       
261       
262    def beginTransaction(self) :   
263        """Starts a transaction."""
264        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
265       
266    def commitTransaction(self) :   
267        """Commits a transaction."""
268        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
269       
270    def rollbackTransaction(self) :     
271        """Rollbacks a transaction."""
272        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
273       
274    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
275        """Does an LDAP search query."""
276        try :
277            base = base or self.basedn
278            self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
279            result = self.database.search_s(base, scope, key, fields) # TODO : put 'None' instead of 'fields'
280        except ldap.LDAPError, msg :   
281            raise PyKotaStorageError, (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg)
282        else :     
283            self.tool.logdebug("QUERY : Result : %s" % result)
284            for (dn, attributes) in result :
285                self.tool.logdebug("LDAP cache store (%s)" % dn)
286                self.ldapcache[dn] = attributes
287            return result
288           
289    def doAdd(self, dn, fields) :
290        """Adds an entry in the LDAP directory."""
291        # TODO : store into LDAP specific cache
292        fields = self.normalizeFields(fields)
293        try :
294            self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
295            self.database.add_s(dn, modlist.addModlist(fields))
296        except ldap.LDAPError, msg :
297            raise PyKotaStorageError, (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
298        else :
299            return dn
300           
301    def doDelete(self, dn) :
302        """Deletes an entry from the LDAP directory."""
303        # TODO : delete from LDAP specific cache
304        try :
305            self.tool.logdebug("QUERY : Delete(%s)" % dn)
306            self.database.delete_s(dn)
307        except ldap.LDAPError, msg :
308            raise PyKotaStorageError, (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
309           
310    def doModify(self, dn, fields, ignoreold=1) :
311        """Modifies an entry in the LDAP directory."""
312        try :
313            # TODO : take care of, and update LDAP specific cache
314            if self.ldapcache.has_key(dn) :
315                self.tool.logdebug("LDAP cache hit (%s)" % dn)
316            else :   
317                self.tool.logdebug("LDAP cache miss (%s)" % dn)
318            oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)
319            for (k, v) in fields.items() :
320                if type(v) == type({}) :
321                    try :
322                        oldvalue = v["convert"](oldentry[0][1].get(k, [0])[0])
323                    except ValueError :   
324                        self.tool.logdebug("Error converting %s with %s(%s)" % (oldentry[0][1].get(k), k, v))
325                        oldvalue = 0
326                    if v["operator"] == '+' :
327                        newvalue = oldvalue + v["value"]
328                    else :   
329                        newvalue = oldvalue - v["value"]
330                    fields[k] = str(newvalue)
331            fields = self.normalizeFields(fields)
332            self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields))
333            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
334        except ldap.LDAPError, msg :
335            raise PyKotaStorageError, (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
336        else :
337            return dn
338           
339    def getAllUsersNames(self) :   
340        """Extracts all user names."""
341        usernames = []
342        result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName"], base=self.info["userbase"])
343        if result :
344            usernames = [record[1]["pykotaUserName"][0] for record in result]
345        return usernames
346       
347    def getAllGroupsNames(self) :   
348        """Extracts all group names."""
349        groupnames = []
350        result = self.doSearch("objectClass=pykotaGroup", ["pykotaGroupName"], base=self.info["groupbase"])
351        if result :
352            groupnames = [record[1]["pykotaGroupName"][0] for record in result]
353        return groupnames
354       
355    def getUserFromBackend(self, username) :   
356        """Extracts user information given its name."""
357        user = StorageUser(self, username)
358        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
359        if result :
360            fields = result[0][1]
361            user.ident = result[0][0]
362            user.Email = fields.get(self.info["usermail"])
363            if user.Email is not None :
364                user.Email = user.Email[0]
365            user.LimitBy = fields.get("pykotaLimitBy")
366            if user.LimitBy is not None :
367                user.LimitBy = user.LimitBy[0]
368            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"], base=self.info["balancebase"])
369            if result :
370                fields = result[0][1]
371                user.idbalance = result[0][0]
372                user.AccountBalance = fields.get("pykotaBalance")
373                if user.AccountBalance is not None :
374                    if user.AccountBalance[0].upper() == "NONE" :
375                        user.AccountBalance = None
376                    else :   
377                        user.AccountBalance = float(user.AccountBalance[0])
378                user.AccountBalance = user.AccountBalance or 0.0       
379                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
380                if user.LifeTimePaid is not None :
381                    if user.LifeTimePaid[0].upper() == "NONE" :
382                        user.LifeTimePaid = None
383                    else :   
384                        user.LifeTimePaid = float(user.LifeTimePaid[0])
385                user.LifeTimePaid = user.LifeTimePaid or 0.0       
386            user.Exists = 1
387        return user
388       
389    def getGroupFromBackend(self, groupname) :   
390        """Extracts group information given its name."""
391        group = StorageGroup(self, groupname)
392        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"], base=self.info["groupbase"])
393        if result :
394            fields = result[0][1]
395            group.ident = result[0][0]
396            group.LimitBy = fields.get("pykotaLimitBy")
397            if group.LimitBy is not None :
398                group.LimitBy = group.LimitBy[0]
399            group.AccountBalance = 0.0
400            group.LifeTimePaid = 0.0
401            for member in self.getGroupMembers(group) :
402                if member.Exists :
403                    group.AccountBalance += member.AccountBalance
404                    group.LifeTimePaid += member.LifeTimePaid
405            group.Exists = 1
406        return group
407       
408    def getPrinterFromBackend(self, printername) :       
409        """Extracts printer information given its name."""
410        printer = StoragePrinter(self, printername)
411        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember"], base=self.info["printerbase"])
412        if result :
413            fields = result[0][1]
414            printer.ident = result[0][0]
415            printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
416            printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
417            printer.LastJob = self.getPrinterLastJob(printer)
418            printer.uniqueMember = fields.get("uniqueMember", [])
419            printer.Exists = 1
420        return printer   
421       
422    def getUserPQuotaFromBackend(self, user, printer) :       
423        """Extracts a user print quota."""
424        userpquota = StorageUserPQuota(self, user, printer)
425        if printer.Exists and user.Exists :
426            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
427            if result :
428                fields = result[0][1]
429                userpquota.ident = result[0][0]
430                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
431                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
432                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
433                if userpquota.SoftLimit is not None :
434                    if userpquota.SoftLimit[0].upper() == "NONE" :
435                        userpquota.SoftLimit = None
436                    else :   
437                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
438                userpquota.HardLimit = fields.get("pykotaHardLimit")
439                if userpquota.HardLimit is not None :
440                    if userpquota.HardLimit[0].upper() == "NONE" :
441                        userpquota.HardLimit = None
442                    elif userpquota.HardLimit is not None :   
443                        userpquota.HardLimit = int(userpquota.HardLimit[0])
444                userpquota.DateLimit = fields.get("pykotaDateLimit")
445                if userpquota.DateLimit is not None :
446                    if userpquota.DateLimit[0].upper() == "NONE" : 
447                        userpquota.DateLimit = None
448                    else :   
449                        userpquota.DateLimit = userpquota.DateLimit[0]
450                userpquota.Exists = 1
451        return userpquota
452       
453    def getGroupPQuotaFromBackend(self, group, printer) :       
454        """Extracts a group print quota."""
455        grouppquota = StorageGroupPQuota(self, group, printer)
456        if group.Exists :
457            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
458            if result :
459                fields = result[0][1]
460                grouppquota.ident = result[0][0]
461                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
462                if grouppquota.SoftLimit is not None :
463                    if grouppquota.SoftLimit[0].upper() == "NONE" :
464                        grouppquota.SoftLimit = None
465                    else :   
466                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
467                grouppquota.HardLimit = fields.get("pykotaHardLimit")
468                if grouppquota.HardLimit is not None :
469                    if grouppquota.HardLimit[0].upper() == "NONE" :
470                        grouppquota.HardLimit = None
471                    else :   
472                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
473                grouppquota.DateLimit = fields.get("pykotaDateLimit")
474                if grouppquota.DateLimit is not None :
475                    if grouppquota.DateLimit[0].upper() == "NONE" : 
476                        grouppquota.DateLimit = None
477                    else :   
478                        grouppquota.DateLimit = grouppquota.DateLimit[0]
479                grouppquota.PageCounter = 0
480                grouppquota.LifePageCounter = 0
481                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
482                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
483                if result :
484                    for userpquota in result :   
485                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter")[0] or 0)
486                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter")[0] or 0)
487                grouppquota.Exists = 1
488        return grouppquota
489       
490    def getPrinterLastJobFromBackend(self, printer) :       
491        """Extracts a printer's last job information."""
492        lastjob = StorageLastJob(self, printer)
493        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
494        if result :
495            lastjob.lastjobident = result[0][0]
496            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
497            result = self.doSearch("objectClass=pykotaJob", ["pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
498            if result :
499                fields = result[0][1]
500                lastjob.ident = result[0][0]
501                lastjob.JobId = fields.get("pykotaJobId")[0]
502                lastjob.User = self.getUser(fields.get("pykotaUserName")[0])
503                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
504                lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
505                lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
506                lastjob.JobAction = fields.get("pykotaAction")[0]
507                lastjob.JobFileName = fields.get("pykotaFileName", [""])[0]
508                lastjob.JobTitle = fields.get("pykotaTitle", [""])[0]
509                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
510                lastjob.JobOptions = fields.get("pykotaOptions", [""])[0]
511                date = fields.get("createTimestamp")[0]
512                year = int(date[:4])
513                month = int(date[4:6])
514                day = int(date[6:8])
515                hour = int(date[8:10])
516                minute = int(date[10:12])
517                second = int(date[12:14])
518                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
519                lastjob.Exists = 1
520        return lastjob
521       
522    def getGroupMembersFromBackend(self, group) :       
523        """Returns the group's members list."""
524        groupmembers = []
525        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
526        if result :
527            for username in result[0][1].get(self.info["groupmembers"], []) :
528                groupmembers.append(self.getUser(username))
529        return groupmembers       
530       
531    def getUserGroupsFromBackend(self, user) :       
532        """Returns the user's groups list."""
533        groups = []
534        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
535        if result :
536            for (groupid, fields) in result :
537                groupname = (fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0]
538                group = self.getFromCache("GROUPS", groupname)
539                if group is None :
540                    group = StorageGroup(self, groupname)
541                    group.ident = groupid
542                    group.LimitBy = fields.get("pykotaLimitBy")
543                    if group.LimitBy is not None :
544                        group.LimitBy = group.LimitBy[0]
545                    group.AccountBalance = 0.0
546                    group.LifeTimePaid = 0.0
547                    for member in self.getGroupMembers(group) :
548                        if member.Exists :
549                            group.AccountBalance += member.AccountBalance
550                            group.LifeTimePaid += member.LifeTimePaid
551                    group.Exists = 1
552                    self.cacheEntry("GROUPS", group.Name, group)
553                groups.append(group)
554        return groups       
555       
556    def getParentPrintersFromBackend(self, printer) :   
557        """Get all the printer groups this printer is a member of."""
558        pgroups = []
559        result = self.doSearch("(&(objectClass=pykotaPrinter)(uniqueMember=%s))" % printer.ident, ["pykotaPrinterName"], base=self.info["printerbase"])
560        if result :
561            for (printerid, fields) in result :
562                if printerid != printer.ident : # In case of integrity violation.
563                    parentprinter = self.getPrinter(fields.get("pykotaPrinterName")[0])
564                    if parentprinter.Exists :
565                        pgroups.append(parentprinter)
566        return pgroups
567       
568    def getMatchingPrinters(self, printerpattern) :
569        """Returns the list of all printers for which name matches a certain pattern."""
570        printers = []
571        # see comment at the same place in pgstorage.py
572        result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)" % pname for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember"], base=self.info["printerbase"])
573        if result :
574            for (printerid, fields) in result :
575                printername = fields["pykotaPrinterName"][0]
576                printer = StoragePrinter(self, printername)
577                printer.ident = printerid
578                printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
579                printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
580                printer.uniqueMember = fields.get("uniqueMember", [])
581                printer.LastJob = self.getPrinterLastJob(printer)
582                printer.Exists = 1
583                printers.append(printer)
584                self.cacheEntry("PRINTERS", printer.Name, printer)
585        return printers       
586       
587    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
588        """Returns the list of users who uses a given printer, along with their quotas."""
589        usersandquotas = []
590        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"])
591        if result :
592            for (userquotaid, fields) in result :
593                user = self.getUser(fields.get("pykotaUserName")[0])
594                userpquota = StorageUserPQuota(self, user, printer)
595                userpquota.ident = userquotaid
596                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
597                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
598                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
599                if userpquota.SoftLimit is not None :
600                    if userpquota.SoftLimit[0].upper() == "NONE" :
601                        userpquota.SoftLimit = None
602                    else :   
603                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
604                userpquota.HardLimit = fields.get("pykotaHardLimit")
605                if userpquota.HardLimit is not None :
606                    if userpquota.HardLimit[0].upper() == "NONE" :
607                        userpquota.HardLimit = None
608                    elif userpquota.HardLimit is not None :   
609                        userpquota.HardLimit = int(userpquota.HardLimit[0])
610                userpquota.DateLimit = fields.get("pykotaDateLimit")
611                if userpquota.DateLimit is not None :
612                    if userpquota.DateLimit[0].upper() == "NONE" : 
613                        userpquota.DateLimit = None
614                    else :   
615                        userpquota.DateLimit = userpquota.DateLimit[0]
616                userpquota.Exists = 1
617                usersandquotas.append((user, userpquota))
618                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
619        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
620        return usersandquotas
621               
622    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
623        """Returns the list of groups which uses a given printer, along with their quotas."""
624        groupsandquotas = []
625        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=self.info["groupquotabase"])
626        if result :
627            for (groupquotaid, fields) in result :
628                group = self.getGroup(fields.get("pykotaGroupName")[0])
629                grouppquota = self.getGroupPQuota(group, printer)
630                groupsandquotas.append((group, grouppquota))
631        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
632        return groupsandquotas
633       
634    def addPrinter(self, printername) :       
635        """Adds a printer to the quota storage, returns it."""
636        fields = { self.info["printerrdn"] : printername,
637                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
638                   "cn" : printername,
639                   "pykotaPrinterName" : printername,
640                   "pykotaPricePerPage" : "0.0",
641                   "pykotaPricePerJob" : "0.0",
642                 } 
643        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
644        self.doAdd(dn, fields)
645        return self.getPrinter(printername)
646       
647    def addUser(self, user) :       
648        """Adds a user to the quota storage, returns it."""
649        newfields = {
650                       "pykotaUserName" : user.Name,
651                       "pykotaLimitBY" : (user.LimitBy or "quota"),
652                       "pykotaBalance" : str(user.AccountBalance or 0.0),
653                       "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0),
654                    }   
655        if user.Email :
656            newfields.update({self.info["usermail"]: user.Email})
657        mustadd = 1
658        if self.info["newuser"].lower() != 'below' :
659            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newuser"], self.info["userrdn"], user.Name), None, base=self.info["userbase"])
660            if result :
661                (dn, fields) = result[0]
662                fields["objectClass"].extend(["pykotaAccount", "pykotaAccountBalance"])
663                fields.update(newfields)
664                self.doModify(dn, fields)
665                mustadd = 0
666               
667        if mustadd :
668            fields = { self.info["userrdn"] : user.Name,
669                       "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
670                       "cn" : user.Name,
671                     } 
672            fields.update(newfields)         
673            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
674            self.doAdd(dn, fields)
675        return self.getUser(user.Name)
676       
677    def addGroup(self, group) :       
678        """Adds a group to the quota storage, returns it."""
679        newfields = { 
680                      "pykotaGroupName" : group.Name,
681                      "pykotaLimitBY" : (group.LimitBy or "quota"),
682                    } 
683        mustadd = 1
684        if self.info["newgroup"].lower() != 'below' :
685            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newgroup"], self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
686            if result :
687                (dn, fields) = result[0]
688                fields["objectClass"].extend(["pykotaGroup"])
689                fields.update(newfields)
690                self.doModify(dn, fields)
691                mustadd = 0
692               
693        if mustadd :
694            fields = { self.info["grouprdn"] : group.Name,
695                       "objectClass" : ["pykotaObject", "pykotaGroup"],
696                       "cn" : group.Name,
697                     } 
698            fields.update(newfields)         
699            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
700            self.doAdd(dn, fields)
701        return self.getGroup(group.Name)
702       
703    def addUserToGroup(self, user, group) :   
704        """Adds an user to a group."""
705        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
706            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
707            if result :
708                fields = result[0][1]
709                if not fields.has_key(self.info["groupmembers"]) :
710                    fields[self.info["groupmembers"]] = []
711                fields[self.info["groupmembers"]].append(user.Name)
712                self.doModify(group.ident, fields)
713                group.Members.append(user)
714               
715    def addUserPQuota(self, user, printer) :
716        """Initializes a user print quota on a printer."""
717        uuid = self.genUUID()
718        fields = { "cn" : uuid,
719                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
720                   "pykotaUserName" : user.Name,
721                   "pykotaPrinterName" : printer.Name,
722                   "pykotaDateLimit" : "None",
723                   "pykotaPageCounter" : "0",
724                   "pykotaLifePageCounter" : "0",
725                 } 
726        dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
727        self.doAdd(dn, fields)
728        return self.getUserPQuota(user, printer)
729       
730    def addGroupPQuota(self, group, printer) :
731        """Initializes a group print quota on a printer."""
732        uuid = self.genUUID()
733        fields = { "cn" : uuid,
734                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
735                   "pykotaGroupName" : group.Name,
736                   "pykotaPrinterName" : printer.Name,
737                   "pykotaDateLimit" : "None",
738                 } 
739        dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
740        self.doAdd(dn, fields)
741        return self.getGroupPQuota(group, printer)
742       
743    def writePrinterPrices(self, printer) :   
744        """Write the printer's prices back into the storage."""
745        fields = {
746                   "pykotaPricePerPage" : str(printer.PricePerPage),
747                   "pykotaPricePerJob" : str(printer.PricePerJob),
748                 }
749        self.doModify(printer.ident, fields)
750       
751    def writeUserLimitBy(self, user, limitby) :   
752        """Sets the user's limiting factor."""
753        fields = {
754                   "pykotaLimitBy" : limitby,
755                 }
756        self.doModify(user.ident, fields)         
757       
758    def writeGroupLimitBy(self, group, limitby) :   
759        """Sets the group's limiting factor."""
760        fields = {
761                   "pykotaLimitBy" : limitby,
762                 }
763        self.doModify(group.ident, fields)         
764       
765    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
766        """Sets the date limit permanently for a user print quota."""
767        fields = {
768                   "pykotaDateLimit" : datelimit,
769                 }
770        return self.doModify(userpquota.ident, fields)
771           
772    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
773        """Sets the date limit permanently for a group print quota."""
774        fields = {
775                   "pykotaDateLimit" : datelimit,
776                 }
777        return self.doModify(grouppquota.ident, fields)
778       
779    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
780        """Increase page counters for a user print quota."""
781        fields = {
782                   "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
783                   "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
784                 }
785        return self.doModify(userpquota.ident, fields)         
786       
787    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
788        """Sets the new page counters permanently for a user print quota."""
789        fields = {
790                   "pykotaPageCounter" : str(newpagecounter),
791                   "pykotaLifePageCounter" : str(newlifepagecounter),
792                 } 
793        return self.doModify(userpquota.ident, fields)         
794       
795    def decreaseUserAccountBalance(self, user, amount) :   
796        """Decreases user's account balance from an amount."""
797        fields = {
798                   "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float },
799                 }
800        return self.doModify(user.idbalance, fields)         
801       
802    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
803        """Sets the new account balance and eventually new lifetime paid."""
804        fields = {
805                   "pykotaBalance" : str(newbalance),
806                 }
807        if newlifetimepaid is not None :
808            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
809        return self.doModify(user.idbalance, fields)         
810           
811    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
812        """Sets the last job's size permanently."""
813        fields = {
814                   "pykotaJobSize" : str(jobsize),
815                   "pykotaJobPrice" : str(jobprice),
816                 }
817        self.doModify(lastjob.ident, fields)         
818       
819    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None) :
820        """Adds a job in a printer's history."""
821        if (not self.disablehistory) or (not printer.LastJob.Exists) :
822            uuid = self.genUUID()
823            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
824        else :   
825            uuid = printer.LastJob.ident[3:].split(",")[0]
826            dn = printer.LastJob.ident
827        fields = {
828                   "objectClass" : ["pykotaObject", "pykotaJob"],
829                   "cn" : uuid,
830                   "pykotaUserName" : user.Name,
831                   "pykotaPrinterName" : printer.Name,
832                   "pykotaJobId" : jobid,
833                   "pykotaPrinterPageCounter" : str(pagecounter),
834                   "pykotaAction" : action,
835                   "pykotaFileName" : str(filename), 
836                   "pykotaTitle" : str(title), 
837                   "pykotaCopies" : str(copies), 
838                   "pykotaOptions" : str(options), 
839                 }
840        if (not self.disablehistory) or (not printer.LastJob.Exists) :
841            if jobsize is not None :         
842                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
843            self.doAdd(dn, fields)
844        else :   
845            # here we explicitly want to reset jobsize to 'None' if needed
846            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
847            self.doModify(dn, fields)
848           
849        if printer.LastJob.Exists :
850            fields = {
851                       "pykotaLastJobIdent" : uuid,
852                     }
853            self.doModify(printer.LastJob.lastjobident, fields)         
854        else :   
855            lastjuuid = self.genUUID()
856            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
857            fields = {
858                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
859                       "cn" : lastjuuid,
860                       "pykotaPrinterName" : printer.Name,
861                       "pykotaLastJobIdent" : uuid,
862                     } 
863            self.doAdd(lastjdn, fields)         
864           
865    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
866        """Sets soft and hard limits for a user quota."""
867        fields = { 
868                   "pykotaSoftLimit" : str(softlimit),
869                   "pykotaHardLimit" : str(hardlimit),
870                 }
871        self.doModify(userpquota.ident, fields)
872       
873    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
874        """Sets soft and hard limits for a group quota on a specific printer."""
875        fields = { 
876                   "pykotaSoftLimit" : str(softlimit),
877                   "pykotaHardLimit" : str(hardlimit),
878                 }
879        self.doModify(grouppquota.ident, fields)
880           
881    def writePrinterToGroup(self, pgroup, printer) :
882        """Puts a printer into a printer group."""
883        if printer.ident not in pgroup.uniqueMember :
884            pgroup.uniqueMember.append(printer.ident)
885            fields = {
886                       "uniqueMember" : pgroup.uniqueMember
887                     } 
888            self.doModify(pgroup.ident, fields)         
889           
890    def removePrinterFromGroup(self, pgroup, printer) :
891        """Removes a printer from a printer group."""
892        try :
893            pgroup.uniqueMember.remove(printer.ident)
894        except ValueError :   
895            pass
896        else :   
897            fields = {
898                       "uniqueMember" : pgroup.uniqueMember,
899                     } 
900            self.doModify(pgroup.ident, fields)         
901           
902    def retrieveHistory(self, user=None, printer=None, datelimit=None, limit=100) :   
903        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
904        precond = "(objectClass=pykotaJob)"
905        where = []
906        if (user is not None) and user.Exists :
907            where.append("(pykotaUserName=%s)" % user.Name)
908        if (printer is not None) and printer.Exists :
909            where.append("(pykotaPrinterName=%s)" % printer.Name)
910        if where :   
911            where = "(&%s)" % "".join([precond] + where)
912        else :   
913            where = precond
914        jobs = []   
915        result = self.doSearch(where, fields=["pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaAction", "pykotaJobSize", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base=self.info["jobbase"])
916        if result :
917            for (ident, fields) in result :
918                job = StorageJob(self)
919                job.ident = ident
920                job.JobId = fields.get("pykotaJobId")[0]
921                job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
922                job.JobSize = int(fields.get("pykotaJobSize", [0])[0])
923                job.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
924                job.JobAction = fields.get("pykotaAction")[0]
925                job.JobFileName = fields.get("pykotaFileName", [""])[0]
926                job.JobTitle = fields.get("pykotaTitle", [""])[0]
927                job.JobCopies = int(fields.get("pykotaCopies", [0])[0])
928                job.JobOptions = fields.get("pykotaOptions", [""])[0]
929                date = fields.get("createTimestamp")[0]
930                year = int(date[:4])
931                month = int(date[4:6])
932                day = int(date[6:8])
933                hour = int(date[8:10])
934                minute = int(date[10:12])
935                second = int(date[12:14])
936                job.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
937                if (datelimit is None) or (job.JobDate <= datelimit) :
938                    job.User = self.getUser(fields.get("pykotaUserName")[0])
939                    job.Printer = self.getPrinter(fields.get("pykotaPrinterName")[0])
940                    job.Exists = 1
941                    jobs.append(job)
942            jobs.sort(lambda x,y : cmp(y.JobDate, x.JobDate))       
943            if limit :   
944                jobs = jobs[:int(limit)]
945        return jobs
946       
947    def deleteUser(self, user) :   
948        """Completely deletes an user from the Quota Storage."""
949        # TODO : What should we do if we delete the last person who used a given printer ?
950        # TODO : we can't reassign the last job to the previous one, because next user would be
951        # TODO : incorrectly charged (overcharged).
952        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaUserName=%s))" % user.Name, base=self.info["lastjobbase"])
953        for (ident, fields) in result :
954            self.doDelete(ident)
955        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
956        for (ident, fields) in result :
957            self.doDelete(ident)
958        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["userquotabase"])
959        for (ident, fields) in result :
960            self.doDelete(ident)
961        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
962        if result :
963            fields = result[0][1]
964            for k in fields.keys() :
965                if k.startswith("pykota") :
966                    del fields[k]
967                elif k.lower() == "objectclass" :   
968                    todelete = []
969                    for i in range(len(fields[k])) :
970                        if fields[k][i].startswith("pykota") : 
971                            todelete.append(i)
972                    todelete.sort()       
973                    todelete.reverse()
974                    for i in todelete :
975                        del fields[k][i]
976            if fields.get("objectClass") or fields.get("objectclass") :
977                self.doModify(user.ident, fields, ignoreold=0)       
978            else :   
979                self.doDelete(user.ident)
980        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
981        for (ident, fields) in result :
982            self.doDelete(ident)
983       
984    def deleteGroup(self, group) :   
985        """Completely deletes a group from the Quota Storage."""
986        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
987        for (ident, fields) in result :
988            self.doDelete(ident)
989        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
990        if result :
991            fields = result[0][1]
992            for k in fields.keys() :
993                if k.startswith("pykota") :
994                    del fields[k]
995                elif k.lower() == "objectclass" :   
996                    todelete = []
997                    for i in range(len(fields[k])) :
998                        if fields[k][i].startswith("pykota") : 
999                            todelete.append(i)
1000                    todelete.sort()       
1001                    todelete.reverse()
1002                    for i in todelete :
1003                        del fields[k][i]
1004            if fields.get("objectClass") or fields.get("objectclass") :
1005                self.doModify(group.ident, fields, ignoreold=0)       
1006            else :   
1007                self.doDelete(group.ident)
1008               
1009    def deletePrinter(self, printer) :   
1010        """Completely deletes an user from the Quota Storage."""
1011        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["lastjobbase"])
1012        for (ident, fields) in result :
1013            self.doDelete(ident)
1014        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["jobbase"])
1015        for (ident, fields) in result :
1016            self.doDelete(ident)
1017        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, base=self.info["groupquotabase"])
1018        for (ident, fields) in result :
1019            self.doDelete(ident)
1020        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, base=self.info["userquotabase"])
1021        for (ident, fields) in result :
1022            self.doDelete(ident)
1023        for parent in self.getParentPrinters(printer) : 
1024            try :
1025                parent.uniqueMember.remove(printer.ident)
1026            except ValueError :   
1027                pass
1028            else :   
1029                fields = {
1030                           "uniqueMember" : parent.uniqueMember,
1031                         } 
1032                self.doModify(parent.ident, fields)         
1033        self.doDelete(printer.ident)   
Note: See TracBrowser for help on using the browser.