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

Revision 1365, 52.2 kB (checked in by jalet, 20 years ago)

Should fix the remaining bugs wrt printers groups and users groups.

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