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

Revision 1380, 52.7 kB (checked in by jalet, 20 years ago)

Final fix for printers searching

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