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

Revision 1361, 51.8 kB (checked in by jalet, 20 years ago)

Small fix wrt empty user groups

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