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

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

ldapcache directive marked as experimental

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