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

Revision 1367, 52.4 kB (checked in by jalet, 20 years ago)

datelimit wasn't reset when modifying soft and hard limits with the LDAP backend

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