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

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

Experimental ldapcache directive added

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