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

Revision 1692, 58.8 kB (checked in by jalet, 20 years ago)

Fixed bug in LDAP user deletion code which didn't correctly delete the user's
pykotaLastJob entries.

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