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

Revision 1534, 57.2 kB (checked in by jalet, 20 years ago)

Better log message

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