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

Revision 1392, 52.9 kB (checked in by jalet, 20 years ago)

Code safer wrt entries created in other tools

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