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

Revision 1358, 51.6 kB (checked in by jalet, 20 years ago)

Don't retrieve data when it's not needed, to avoid database queries

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