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

Revision 1393, 53.0 kB (checked in by jalet, 20 years ago)

Improvement on strange history entries

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