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

Revision 1584, 57.8 kB (checked in by jalet, 20 years ago)

Better dispatching of error messages

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