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

Revision 1379, 52.6 kB (checked in by jalet, 20 years ago)

Missing test when searching printer objects when these objects were manually
created and don't contain the pykotaPrinterName attribute

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