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

Revision 1523, 57.1 kB (checked in by jalet, 20 years ago)

Now catches some exceptions earlier.
storage.py and ldapstorage.py : removed old comments

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