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

Revision 2041, 75.6 kB (checked in by jalet, 19 years ago)

Performance improvement for user print quota entries search

  • 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.98  2005/01/24 17:35:24  jalet
25# Performance improvement for user print quota entries search
26#
27# Revision 1.97  2005/01/24 17:27:35  jalet
28# typo
29#
30# Revision 1.96  2005/01/24 15:38:51  jalet
31# Fixed some ldap filters
32#
33# Revision 1.95  2005/01/18 19:47:50  jalet
34# Big bug fix wrt the datelimit attribute
35#
36# Revision 1.94  2005/01/01 18:53:27  jalet
37# Implemented in the LDAP backend code the same fix than in PostgreSQL backend
38# code for people who don't use PyKota tools to manage accounts.
39#
40# Revision 1.93  2004/12/31 16:10:57  jalet
41# Fixed recently introduced bugs due to extended userquotabase and groupquotabase
42# directives.
43#
44# Revision 1.92  2004/12/26 14:50:51  jalet
45# Normalized fields names in dumpykota's output so that an LDAP or PostgreSQL
46# dump is parseable the same way.
47#
48# Revision 1.91  2004/12/21 16:46:25  jalet
49# dumpykota's filtering capabilities are now supported within the LDAP
50# backend as well as within the PostgreSQL backend. Untested though since
51# my only PyKota+LDAP setup is on my laptop at work :-)
52#
53# Revision 1.90  2004/12/21 14:45:31  jalet
54# Prepared dumpykota to accept the new --filter command line option. Some
55# additionnal work needs to be done in the backends though.
56#
57# Revision 1.89  2004/12/02 22:27:11  jalet
58# Integrated and extended Stefan Wold's patch to store print quota entries
59# directly below the user or the group object with the LDAP backend
60#
61# Revision 1.88  2004/12/02 22:01:58  jalet
62# TLS is now supported with the LDAP backend
63#
64# Revision 1.87  2004/12/02 12:34:00  jalet
65# Now automates LDAP reconnections if the server dropped the connection due
66# to a timeout.
67#
68# Revision 1.86  2004/10/25 14:12:25  jalet
69# For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
70# to hide print jobs' title, filename, and options.
71#
72# Revision 1.85  2004/10/24 12:55:09  jalet
73# Missing spaces
74#
75# Revision 1.84  2004/10/12 08:58:53  jalet
76# Now warnpykota only warns users who have already printed, to not confuse
77# users who have just opened their account.
78#
79# Revision 1.83  2004/10/07 21:14:28  jalet
80# Hopefully final fix for data encoding to and from the database
81#
82# Revision 1.82  2004/10/05 09:59:20  jalet
83# Restore compatibility with Python 2.1
84#
85# Revision 1.81  2004/10/04 11:27:57  jalet
86# Finished LDAP support for dumpykota.
87#
88# Revision 1.80  2004/10/03 19:57:57  jalet
89# Dump of payments should work with LDAP backend now.
90#
91# Revision 1.79  2004/10/03 19:52:59  jalet
92# More work done on LDAP and dumpykota
93#
94# Revision 1.78  2004/10/02 05:48:56  jalet
95# Should now correctly deal with charsets both when storing into databases and when
96# retrieving datas. Works with both PostgreSQL and LDAP.
97#
98# Revision 1.77  2004/09/28 14:29:00  jalet
99# dumpykota for LDAP backend is almost there.
100#
101# Revision 1.76  2004/09/28 09:11:56  jalet
102# Fix for accented chars in print job's title, filename, and options
103#
104# Revision 1.75  2004/09/24 20:21:50  jalet
105# Fixed pykotaAccountBalance object location during creation
106#
107# Revision 1.74  2004/09/02 10:09:30  jalet
108# Fixed bug in LDAP user deletion code which didn't correctly delete the user's
109# pykotaLastJob entries.
110#
111# Revision 1.73  2004/07/17 20:37:27  jalet
112# Missing file... Am I really stupid ?
113#
114# Revision 1.72  2004/07/01 19:56:43  jalet
115# Better dispatching of error messages
116#
117# Revision 1.71  2004/07/01 17:45:49  jalet
118# Added code to handle the description field for printers
119#
120# Revision 1.70  2004/06/10 20:50:25  jalet
121# Better log message
122#
123# Revision 1.69  2004/06/05 22:18:04  jalet
124# Now catches some exceptions earlier.
125# storage.py and ldapstorage.py : removed old comments
126#
127# Revision 1.68  2004/06/05 22:03:50  jalet
128# Payments history is now stored in database
129#
130# Revision 1.67  2004/06/03 23:14:10  jalet
131# Now stores the job's size in bytes in the database.
132# Preliminary work on payments storage : database schemas are OK now,
133# but no code to store payments yet.
134# Removed schema picture, not relevant anymore.
135#
136# Revision 1.66  2004/05/28 20:56:45  jalet
137# Extended syntax for LDAP specific newuser and newgroup directives. Untested.
138#
139# Revision 1.65  2004/05/27 12:52:12  jalet
140# More useful error message in case of misconfiguration of an LDAP  search base
141# in pykota.conf
142#
143# Revision 1.64  2004/05/26 14:50:01  jalet
144# First try at saving the job-originating-hostname in the database
145#
146# Revision 1.63  2004/05/06 12:37:46  jalet
147# pkpgcounter : comments
148# pkprinters : when --add is used, existing printers are now skipped.
149#
150# Revision 1.62  2004/03/05 14:31:58  jalet
151# Improvement on strange history entries
152#
153# Revision 1.61  2004/03/05 13:19:53  jalet
154# Code safer wrt entries created in other tools
155#
156# Revision 1.60  2004/03/02 14:39:02  jalet
157# Final fix for printers searching
158#
159# Revision 1.59  2004/03/02 14:35:46  jalet
160# Missing test when searching printer objects when these objects were manually
161# created and don't contain the pykotaPrinterName attribute
162#
163# Revision 1.58  2004/02/27 09:30:33  jalet
164# datelimit wasn't reset when modifying soft and hard limits with the LDAP backend
165#
166# Revision 1.57  2004/02/26 14:18:07  jalet
167# Should fix the remaining bugs wrt printers groups and users groups.
168#
169# Revision 1.56  2004/02/25 16:52:39  jalet
170# Small fix wrt empty user groups
171#
172# Revision 1.55  2004/02/23 22:53:21  jalet
173# Don't retrieve data when it's not needed, to avoid database queries
174#
175# Revision 1.54  2004/02/20 16:38:39  jalet
176# ldapcache directive marked as experimental
177#
178# Revision 1.53  2004/02/20 14:42:21  jalet
179# Experimental ldapcache directive added
180#
181# Revision 1.52  2004/02/17 23:41:48  jalet
182# Preliminary work on low-level LDAP specific cache.
183#
184# Revision 1.51  2004/02/04 13:24:41  jalet
185# pkprinters can now remove printers from printers groups.
186#
187# Revision 1.50  2004/02/04 11:17:00  jalet
188# pkprinters command line tool added.
189#
190# Revision 1.49  2004/01/29 22:35:45  jalet
191# Small fix from Matt.
192#
193# Revision 1.48  2004/01/12 14:35:02  jalet
194# Printing history added to CGI script.
195#
196# Revision 1.47  2004/01/10 09:44:02  jalet
197# Fixed potential accuracy problem if a user printed on several printers at
198# the very same time.
199#
200# Revision 1.46  2004/01/08 16:33:27  jalet
201# Additionnal check to not create a circular printers group.
202#
203# Revision 1.45  2004/01/08 16:24:49  jalet
204# edpykota now supports adding printers to printer groups.
205#
206# Revision 1.44  2004/01/08 14:10:33  jalet
207# Copyright year changed.
208#
209# Revision 1.43  2004/01/06 14:24:59  jalet
210# Printer groups should be cached now, if caching is enabled.
211#
212# Revision 1.42  2003/12/29 14:12:48  uid67467
213# Tries to workaround possible integrity violations when retrieving printer groups
214#
215# Revision 1.41  2003/12/27 16:49:25  uid67467
216# Should be ok now.
217#
218# Revision 1.40  2003/11/29 22:02:14  jalet
219# Don't try to retrieve the user print quota information if current printer
220# doesn't exist.
221#
222# Revision 1.39  2003/11/26 23:35:32  jalet
223# Added a bit of code to support the setting of the user's email address
224# which was ignored during writes for now.
225#
226# Revision 1.38  2003/11/24 09:54:06  jalet
227# Small fix for LDAP when pykotaOptions attribute wasn't present.
228#
229# Revision 1.37  2003/11/23 19:01:37  jalet
230# Job price added to history
231#
232# Revision 1.36  2003/11/21 14:28:46  jalet
233# More complete job history.
234#
235# Revision 1.35  2003/11/12 13:06:37  jalet
236# Bug fix wrt no user/group name command line argument to edpykota
237#
238# Revision 1.34  2003/10/24 08:37:55  jalet
239# More complete messages in case of LDAP failure.
240# LDAP database connection is now unbound on exit too.
241#
242# Revision 1.33  2003/10/08 07:01:20  jalet
243# Job history can be disabled.
244# Some typos in README.
245# More messages in setup script.
246#
247# Revision 1.32  2003/10/07 14:23:25  jalet
248# More work on cache
249#
250# Revision 1.31  2003/10/07 09:07:30  jalet
251# Character encoding added to please latest version of Python
252#
253# Revision 1.30  2003/10/06 14:42:36  jalet
254# LDAP group access will be slower when cache is disabled, but at least code
255# is consistent with the rest of the caching mechanis, but at least code
256# is consistent with the rest of the caching mechanism
257#
258# Revision 1.29  2003/10/06 13:12:28  jalet
259# More work on caching
260#
261# Revision 1.28  2003/10/03 12:27:02  jalet
262# Several optimizations, especially with LDAP backend
263#
264# Revision 1.27  2003/10/03 08:57:55  jalet
265# Caching mechanism now caches all that's cacheable.
266#
267# Revision 1.26  2003/10/02 20:23:18  jalet
268# Storage caching mechanism added.
269#
270# Revision 1.25  2003/08/20 15:56:24  jalet
271# Better user and group deletion
272#
273# Revision 1.24  2003/07/29 20:55:17  jalet
274# 1.14 is out !
275#
276# Revision 1.23  2003/07/29 19:52:32  jalet
277# Forgot to read the email field from LDAP
278#
279# Revision 1.22  2003/07/29 09:54:03  jalet
280# Added configurable LDAP mail attribute support
281#
282# Revision 1.21  2003/07/28 09:11:12  jalet
283# PyKota now tries to add its attributes intelligently in existing LDAP
284# directories.
285#
286# Revision 1.20  2003/07/25 10:41:30  jalet
287# Better documentation.
288# pykotme now displays the current user's account balance.
289# Some test changed in ldap module.
290#
291# Revision 1.19  2003/07/14 14:18:16  jalet
292# Wrong documentation strings
293#
294# Revision 1.18  2003/07/11 14:23:13  jalet
295# When adding an user only adds one object containing both the user and
296# its account balance instead of two objects.
297#
298# Revision 1.17  2003/07/07 12:51:07  jalet
299# Small fix
300#
301# Revision 1.16  2003/07/07 12:11:13  jalet
302# Small fix
303#
304# Revision 1.15  2003/07/07 11:49:24  jalet
305# Lots of small fixes with the help of PyChecker
306#
307# Revision 1.14  2003/07/07 08:33:18  jalet
308# Bug fix due to a typo in LDAP code
309#
310# Revision 1.13  2003/07/05 07:46:50  jalet
311# The previous bug fix was incomplete.
312#
313# Revision 1.12  2003/06/30 13:54:21  jalet
314# Sorts by user / group name
315#
316# Revision 1.11  2003/06/25 14:10:01  jalet
317# Hey, it may work (edpykota --reset excepted) !
318#
319# Revision 1.10  2003/06/16 21:55:15  jalet
320# More work on LDAP, again. Problem detected.
321#
322# Revision 1.9  2003/06/16 11:59:09  jalet
323# More work on LDAP
324#
325# Revision 1.8  2003/06/15 22:26:52  jalet
326# More work on LDAP
327#
328# Revision 1.7  2003/06/14 22:44:21  jalet
329# More work on LDAP storage backend.
330#
331# Revision 1.6  2003/06/13 19:07:57  jalet
332# Two big bugs fixed, time to release something ;-)
333#
334# Revision 1.5  2003/06/10 16:37:54  jalet
335# Deletion of the second user which is not needed anymore.
336# Added a debug configuration field in /etc/pykota.conf
337# All queries can now be sent to the logger in debug mode, this will
338# greatly help improve performance when time for this will come.
339#
340# Revision 1.4  2003/06/10 10:45:32  jalet
341# Not implemented methods now raise an exception when called.
342#
343# Revision 1.3  2003/06/06 20:49:15  jalet
344# Very latest schema. UNTESTED.
345#
346# Revision 1.2  2003/06/06 14:21:08  jalet
347# New LDAP schema.
348# Small bug fixes.
349#
350# Revision 1.1  2003/06/05 11:19:13  jalet
351# More good work on LDAP storage.
352#
353#
354#
355
356#
357# My IANA assigned number, for
358# "Conseil Internet & Logiciels Libres, J�me Alet"
359# is 16868. Use this as a base to create the LDAP schema.
360#
361
362import os
363import types
364import time
365import md5
366from mx import DateTime
367
368from pykota.storage import PyKotaStorageError, BaseStorage, StorageObject, StorageUser, StorageGroup, StoragePrinter, StorageJob, StorageLastJob, StorageUserPQuota, StorageGroupPQuota
369
370try :
371    import ldap
372    import ldap.modlist
373except ImportError :   
374    import sys
375    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
376   
377class Storage(BaseStorage) :
378    def __init__(self, pykotatool, host, dbname, user, passwd) :
379        """Opens the LDAP connection."""
380        self.savedtool = pykotatool
381        self.savedhost = host
382        self.saveddbname = dbname
383        self.saveduser = user
384        self.savedpasswd = passwd
385        self.secondStageInit()
386       
387    def secondStageInit(self) :   
388        """Second stage initialisation."""
389        BaseStorage.__init__(self, self.savedtool)
390        self.info = self.tool.config.getLDAPInfo()
391        message = ""
392        for tryit in range(3) :
393            try :
394                self.database = ldap.initialize(self.savedhost) 
395                if self.info["ldaptls"] :
396                    # we want TLS
397                    ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.info["cacert"])
398                    self.database.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
399                    self.database.start_tls_s()
400                self.database.simple_bind_s(self.saveduser, self.savedpasswd)
401                self.basedn = self.saveddbname
402            except ldap.SERVER_DOWN :   
403                message = "LDAP backend for PyKota seems to be down !"
404                self.tool.printInfo("%s" % message, "error")
405                self.tool.printInfo("Trying again in 2 seconds...", "warn")
406                time.sleep(2)
407            except ldap.LDAPError :   
408                message = "Unable to connect to LDAP server %s as %s." % (self.savedhost, self.saveduser)
409                self.tool.printInfo("%s" % message, "error")
410                self.tool.printInfo("Trying again in 2 seconds...", "warn")
411                time.sleep(2)
412            else :   
413                self.useldapcache = self.tool.config.getLDAPCache()
414                if self.useldapcache :
415                    self.tool.logdebug("Low-Level LDAP Caching enabled.")
416                    self.ldapcache = {} # low-level cache specific to LDAP backend
417                self.closed = 0
418                self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (self.savedhost, self.saveddbname, self.saveduser))
419                return # All is fine here.
420        raise PyKotaStorageError, message         
421           
422    def close(self) :   
423        """Closes the database connection."""
424        if not self.closed :
425            self.database.unbind_s()
426            self.closed = 1
427            self.tool.logdebug("Database closed.")
428       
429    def genUUID(self) :   
430        """Generates an unique identifier.
431       
432           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
433        """
434        return md5.md5("%s" % time.time()).hexdigest()
435       
436    def normalizeFields(self, fields) :   
437        """Ensure all items are lists."""
438        for (k, v) in fields.items() :
439            if type(v) not in (types.TupleType, types.ListType) :
440                if not v :
441                    del fields[k]
442                else :   
443                    fields[k] = [ v ]
444        return fields       
445       
446    def beginTransaction(self) :   
447        """Starts a transaction."""
448        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
449       
450    def commitTransaction(self) :   
451        """Commits a transaction."""
452        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
453       
454    def rollbackTransaction(self) :     
455        """Rollbacks a transaction."""
456        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
457       
458    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE, flushcache=0) :
459        """Does an LDAP search query."""
460        message = ""
461        for tryit in range(3) :
462            try :
463                base = base or self.basedn
464                if self.useldapcache :
465                    # Here we overwrite the fields the app want, to try and
466                    # retrieve ALL user defined attributes ("*")
467                    # + the createTimestamp attribute, needed by job history
468                    #
469                    # This may not work with all LDAP servers
470                    # but works at least in OpenLDAP (2.1.25)
471                    # and iPlanet Directory Server (5.1 SP3)
472                    fields = ["*", "createTimestamp"]         
473                   
474                if self.useldapcache and (not flushcache) and (scope == ldap.SCOPE_BASE) and self.ldapcache.has_key(base) :
475                    entry = self.ldapcache[base]
476                    self.tool.logdebug("LDAP cache hit %s => %s" % (base, entry))
477                    result = [(base, entry)]
478                else :
479                    self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
480                    result = self.database.search_s(base, scope, key, fields)
481            except ldap.NO_SUCH_OBJECT, msg :       
482                raise PyKotaStorageError, (_("Search base %s doesn't seem to exist. Probable misconfiguration. Please double check /etc/pykota/pykota.conf : %s") % (base, msg))
483            except ldap.LDAPError, msg :   
484                message = (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg)
485                self.tool.printInfo("LDAP error : %s" % message, "error")
486                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
487                self.close()
488                self.secondStageInit()
489            else :     
490                self.tool.logdebug("QUERY : Result : %s" % result)
491                if self.useldapcache :
492                    for (dn, attributes) in result :
493                        self.tool.logdebug("LDAP cache store %s => %s" % (dn, attributes))
494                        self.ldapcache[dn] = attributes
495                return result
496        raise PyKotaStorageError, message
497           
498    def doAdd(self, dn, fields) :
499        """Adds an entry in the LDAP directory."""
500        fields = self.normalizeFields(fields)
501        message = ""
502        for tryit in range(3) :
503            try :
504                self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
505                entry = ldap.modlist.addModlist(fields)
506                self.tool.logdebug("%s" % entry)
507                self.database.add_s(dn, entry)
508            except ldap.LDAPError, msg :
509                message = (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
510                self.tool.printInfo("LDAP error : %s" % message, "error")
511                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
512                self.close()
513                self.secondStageInit()
514            else :
515                if self.useldapcache :
516                    self.tool.logdebug("LDAP cache add %s => %s" % (dn, fields))
517                    self.ldapcache[dn] = fields
518                return dn
519        raise PyKotaStorageError, message
520           
521    def doDelete(self, dn) :
522        """Deletes an entry from the LDAP directory."""
523        message = ""
524        for tryit in range(3) :
525            try :
526                self.tool.logdebug("QUERY : Delete(%s)" % dn)
527                self.database.delete_s(dn)
528            except ldap.LDAPError, msg :
529                message = (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
530                self.tool.printInfo("LDAP error : %s" % message, "error")
531                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
532                self.close()
533                self.secondStageInit()
534            else :   
535                if self.useldapcache :
536                    try :
537                        self.tool.logdebug("LDAP cache del %s" % dn)
538                        del self.ldapcache[dn]
539                    except KeyError :   
540                        pass
541                return       
542        raise PyKotaStorageError, message
543           
544    def doModify(self, dn, fields, ignoreold=1, flushcache=0) :
545        """Modifies an entry in the LDAP directory."""
546        for tryit in range(3) :
547            try :
548                # TODO : take care of, and update LDAP specific cache
549                if self.useldapcache and not flushcache :
550                    if self.ldapcache.has_key(dn) :
551                        old = self.ldapcache[dn]
552                        self.tool.logdebug("LDAP cache hit %s => %s" % (dn, old))
553                        oldentry = {}
554                        for (k, v) in old.items() :
555                            if k != "createTimestamp" :
556                                oldentry[k] = v
557                    else :   
558                        self.tool.logdebug("LDAP cache miss %s" % dn)
559                        oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)[0][1]
560                else :       
561                    oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE, flushcache=flushcache)[0][1]
562                for (k, v) in fields.items() :
563                    if type(v) == type({}) :
564                        try :
565                            oldvalue = v["convert"](oldentry.get(k, [0])[0])
566                        except ValueError :   
567                            self.tool.logdebug("Error converting %s with %s(%s)" % (oldentry.get(k), k, v))
568                            oldvalue = 0
569                        if v["operator"] == '+' :
570                            newvalue = oldvalue + v["value"]
571                        else :   
572                            newvalue = oldvalue - v["value"]
573                        fields[k] = str(newvalue)
574                fields = self.normalizeFields(fields)
575                self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry, fields))
576                entry = ldap.modlist.modifyModlist(oldentry, fields, ignore_oldexistent=ignoreold)
577                modentry = []
578                for (mop, mtyp, mval) in entry :
579                    if mtyp != "createTimestamp" :
580                        modentry.append((mop, mtyp, mval))
581                self.tool.logdebug("MODIFY : %s ==> %s ==> %s" % (fields, entry, modentry))
582                if modentry :
583                    self.database.modify_s(dn, modentry)
584            except ldap.LDAPError, msg :
585                message = (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
586                self.tool.printInfo("LDAP error : %s" % message, "error")
587                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
588                self.close()
589                self.secondStageInit()
590            else :
591                if self.useldapcache :
592                    cachedentry = self.ldapcache[dn]
593                    for (mop, mtyp, mval) in entry :
594                        if mop in (ldap.MOD_ADD, ldap.MOD_REPLACE) :
595                            cachedentry[mtyp] = mval
596                        else :
597                            try :
598                                del cachedentry[mtyp]
599                            except KeyError :   
600                                pass
601                    self.tool.logdebug("LDAP cache update %s => %s" % (dn, cachedentry))
602                return dn
603        raise PyKotaStorageError, message
604           
605    def getAllPrintersNames(self, printername=None) :   
606        """Extracts all printer names or only the printers' names matching the optional parameter."""
607        printernames = []
608        ldapfilter = "objectClass=pykotaPrinter"
609        if printername :
610            ldapfilter = "(&(%s)(pykotaPrinterName=%s))" % (ldapfilter, printername)
611        result = self.doSearch(ldapfilter, ["pykotaPrinterName"], base=self.info["printerbase"])
612        if result :
613            printernames = [record[1]["pykotaPrinterName"][0] for record in result]
614        return printernames
615       
616    def getAllUsersNames(self, username=None) :   
617        """Extracts all user names or only the users' names matching the optional parameter."""
618        usernames = []
619        ldapfilter = "objectClass=pykotaAccount"
620        if username :
621            ldapfilter = "(&(%s)(pykotaUserName=%s))" % (ldapfilter, username)
622        result = self.doSearch(ldapfilter, ["pykotaUserName"], base=self.info["userbase"])
623        if result :
624            usernames = [record[1]["pykotaUserName"][0] for record in result]
625        return usernames
626       
627    def getAllGroupsNames(self, groupname=None) :   
628        """Extracts all group names or only the groups' names matching the optional parameter."""
629        groupnames = []
630        ldapfilter = "objectClass=pykotaGroup"
631        if groupname :
632            ldapfilter = "(&(%s)(pykotaGroupName=%s))" % (ldapfilter, groupname)
633        result = self.doSearch(ldapfilter, ["pykotaGroupName"], base=self.info["groupbase"])
634        if result :
635            groupnames = [record[1]["pykotaGroupName"][0] for record in result]
636        return groupnames
637       
638    def getUserNbJobsFromHistory(self, user) :
639        """Returns the number of jobs the user has in history."""
640        result = self.doSearch("(&(pykotaUserName=%s)(objectClass=pykotaJob))" % user.Name, None, base=self.info["jobbase"])
641        return len(result)
642       
643    def getUserFromBackend(self, username) :   
644        """Extracts user information given its name."""
645        user = StorageUser(self, username)
646        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaUserName", "pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
647        if result :
648            fields = result[0][1]
649            user.ident = result[0][0]
650            user.Name = fields.get("pykotaUserName", [username])[0] 
651            user.Email = fields.get(self.info["usermail"])
652            if user.Email is not None :
653                user.Email = user.Email[0]
654            user.LimitBy = fields.get("pykotaLimitBy")
655            if user.LimitBy is not None :
656                user.LimitBy = user.LimitBy[0]
657            else :   
658                user.LimitBy = "quota"
659            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid", "pykotaPayments"], base=self.info["balancebase"])
660            if not result :
661                raise PyKotaStorageError, _("No pykotaAccountBalance object found for user %s. Did you create LDAP entries manually ?") % username
662            else :
663                fields = result[0][1]
664                user.idbalance = result[0][0]
665                user.AccountBalance = fields.get("pykotaBalance")
666                if user.AccountBalance is not None :
667                    if user.AccountBalance[0].upper() == "NONE" :
668                        user.AccountBalance = None
669                    else :   
670                        user.AccountBalance = float(user.AccountBalance[0])
671                user.AccountBalance = user.AccountBalance or 0.0       
672                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
673                if user.LifeTimePaid is not None :
674                    if user.LifeTimePaid[0].upper() == "NONE" :
675                        user.LifeTimePaid = None
676                    else :   
677                        user.LifeTimePaid = float(user.LifeTimePaid[0])
678                user.LifeTimePaid = user.LifeTimePaid or 0.0       
679                user.Payments = []
680                for payment in fields.get("pykotaPayments", []) :
681                    (date, amount) = payment.split(" # ")
682                    user.Payments.append((date, amount))
683            user.Exists = 1
684        return user
685       
686    def getGroupFromBackend(self, groupname) :   
687        """Extracts group information given its name."""
688        group = StorageGroup(self, groupname)
689        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
690        if result :
691            fields = result[0][1]
692            group.ident = result[0][0]
693            group.Name = fields.get("pykotaGroupName", [groupname])[0] 
694            group.LimitBy = fields.get("pykotaLimitBy")
695            if group.LimitBy is not None :
696                group.LimitBy = group.LimitBy[0]
697            else :   
698                group.LimitBy = "quota"
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        return group
707       
708    def getPrinterFromBackend(self, printername) :       
709        """Extracts printer information given its name : returns first matching printer."""
710        printer = StoragePrinter(self, printername)
711        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"])
712        if result :
713            fields = result[0][1]       # take only first matching printer, ignore the rest
714            printer.ident = result[0][0]
715            printer.Name = fields.get("pykotaPrinterName", [printername])[0] 
716            printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0)
717            printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0)
718            printer.uniqueMember = fields.get("uniqueMember", [])
719            printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
720            printer.Exists = 1
721        return printer   
722       
723    def getUserPQuotaFromBackend(self, user, printer) :       
724        """Extracts a user print quota."""
725        userpquota = StorageUserPQuota(self, user, printer)
726        if printer.Exists and user.Exists :
727            if self.info["userquotabase"].lower() == "user" :
728                base = user.ident
729            else :   
730                base = self.info["userquotabase"]
731            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=base)
732            if result :
733                fields = result[0][1]
734                userpquota.ident = result[0][0]
735                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0] or 0)
736                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0] or 0)
737                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
738                if userpquota.SoftLimit is not None :
739                    if userpquota.SoftLimit[0].upper() == "NONE" :
740                        userpquota.SoftLimit = None
741                    else :   
742                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
743                userpquota.HardLimit = fields.get("pykotaHardLimit")
744                if userpquota.HardLimit is not None :
745                    if userpquota.HardLimit[0].upper() == "NONE" :
746                        userpquota.HardLimit = None
747                    elif userpquota.HardLimit is not None :   
748                        userpquota.HardLimit = int(userpquota.HardLimit[0])
749                userpquota.DateLimit = fields.get("pykotaDateLimit")
750                if userpquota.DateLimit is not None :
751                    if userpquota.DateLimit[0].upper() == "NONE" : 
752                        userpquota.DateLimit = None
753                    else :   
754                        userpquota.DateLimit = userpquota.DateLimit[0]
755                userpquota.Exists = 1
756        return userpquota
757       
758    def getGroupPQuotaFromBackend(self, group, printer) :       
759        """Extracts a group print quota."""
760        grouppquota = StorageGroupPQuota(self, group, printer)
761        if group.Exists :
762            if self.info["groupquotabase"].lower() == "group" :
763                base = group.ident
764            else :   
765                base = self.info["groupquotabase"]
766            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=base)
767            if result :
768                fields = result[0][1]
769                grouppquota.ident = result[0][0]
770                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
771                if grouppquota.SoftLimit is not None :
772                    if grouppquota.SoftLimit[0].upper() == "NONE" :
773                        grouppquota.SoftLimit = None
774                    else :   
775                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
776                grouppquota.HardLimit = fields.get("pykotaHardLimit")
777                if grouppquota.HardLimit is not None :
778                    if grouppquota.HardLimit[0].upper() == "NONE" :
779                        grouppquota.HardLimit = None
780                    else :   
781                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
782                grouppquota.DateLimit = fields.get("pykotaDateLimit")
783                if grouppquota.DateLimit is not None :
784                    if grouppquota.DateLimit[0].upper() == "NONE" : 
785                        grouppquota.DateLimit = None
786                    else :   
787                        grouppquota.DateLimit = grouppquota.DateLimit[0]
788                grouppquota.PageCounter = 0
789                grouppquota.LifePageCounter = 0
790                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
791                if usernamesfilter :
792                    usernamesfilter = "(|%s)" % usernamesfilter
793                if self.info["userquotabase"].lower() == "user" :
794                    base = self.info["userbase"]
795                else :
796                    base = self.info["userquotabase"]
797                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)%s)" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=base)
798                if result :
799                    for userpquota in result :   
800                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter", [0])[0] or 0)
801                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter", [0])[0] or 0)
802                grouppquota.Exists = 1
803        return grouppquota
804       
805    def getPrinterLastJobFromBackend(self, printer) :       
806        """Extracts a printer's last job information."""
807        lastjob = StorageLastJob(self, printer)
808        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
809        if result :
810            lastjob.lastjobident = result[0][0]
811            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
812            result = None
813            try :
814                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)
815            except PyKotaStorageError :   
816                pass # Last job entry exists, but job probably doesn't exist anymore.
817            if result :
818                fields = result[0][1]
819                lastjob.ident = result[0][0]
820                lastjob.JobId = fields.get("pykotaJobId")[0]
821                lastjob.UserName = fields.get("pykotaUserName")[0]
822                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
823                try :
824                    lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
825                except ValueError :   
826                    lastjob.JobSize = None
827                try :   
828                    lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
829                except ValueError :   
830                    lastjob.JobPrice = None
831                lastjob.JobAction = fields.get("pykotaAction", [""])[0]
832                lastjob.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
833                lastjob.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
834                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
835                lastjob.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
836                lastjob.JobHostName = fields.get("pykotaHostName", [""])[0]
837                lastjob.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
838                date = fields.get("createTimestamp", ["19700101000000"])[0]
839                year = int(date[:4])
840                month = int(date[4:6])
841                day = int(date[6:8])
842                hour = int(date[8:10])
843                minute = int(date[10:12])
844                second = int(date[12:14])
845                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
846                lastjob.Exists = 1
847        return lastjob
848       
849    def getGroupMembersFromBackend(self, group) :       
850        """Returns the group's members list."""
851        groupmembers = []
852        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
853        if result :
854            for username in result[0][1].get(self.info["groupmembers"], []) :
855                groupmembers.append(self.getUser(username))
856        return groupmembers       
857       
858    def getUserGroupsFromBackend(self, user) :       
859        """Returns the user's groups list."""
860        groups = []
861        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
862        if result :
863            for (groupid, fields) in result :
864                groupname = (fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0]
865                group = self.getFromCache("GROUPS", groupname)
866                if group is None :
867                    group = StorageGroup(self, groupname)
868                    group.ident = groupid
869                    group.LimitBy = fields.get("pykotaLimitBy")
870                    if group.LimitBy is not None :
871                        group.LimitBy = group.LimitBy[0]
872                    else :   
873                        group.LimitBy = "quota"
874                    group.AccountBalance = 0.0
875                    group.LifeTimePaid = 0.0
876                    for member in self.getGroupMembers(group) :
877                        if member.Exists :
878                            group.AccountBalance += member.AccountBalance
879                            group.LifeTimePaid += member.LifeTimePaid
880                    group.Exists = 1
881                    self.cacheEntry("GROUPS", group.Name, group)
882                groups.append(group)
883        return groups       
884       
885    def getParentPrintersFromBackend(self, printer) :   
886        """Get all the printer groups this printer is a member of."""
887        pgroups = []
888        result = self.doSearch("(&(objectClass=pykotaPrinter)(uniqueMember=%s))" % printer.ident, ["pykotaPrinterName"], base=self.info["printerbase"])
889        if result :
890            for (printerid, fields) in result :
891                if printerid != printer.ident : # In case of integrity violation.
892                    parentprinter = self.getPrinter(fields.get("pykotaPrinterName")[0])
893                    if parentprinter.Exists :
894                        pgroups.append(parentprinter)
895        return pgroups
896       
897    def getMatchingPrinters(self, printerpattern) :
898        """Returns the list of all printers for which name matches a certain pattern."""
899        printers = []
900        # see comment at the same place in pgstorage.py
901        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"])
902        if result :
903            for (printerid, fields) in result :
904                printername = fields.get("pykotaPrinterName", [""])[0] or fields.get(self.info["printerrdn"], [""])[0]
905                printer = StoragePrinter(self, printername)
906                printer.ident = printerid
907                printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0)
908                printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0)
909                printer.uniqueMember = fields.get("uniqueMember", [])
910                printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
911                printer.Exists = 1
912                printers.append(printer)
913                self.cacheEntry("PRINTERS", printer.Name, printer)
914        return printers       
915       
916    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
917        """Returns the list of users who uses a given printer, along with their quotas."""
918        usersandquotas = []
919        if self.info["userquotabase"].lower() == "user" :
920           base = self.info["userbase"]
921        else :
922           base = self.info["userquotabase"]
923        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=base)
924        if result :
925            for (userquotaid, fields) in result :
926                user = self.getUser(fields.get("pykotaUserName")[0])
927                userpquota = StorageUserPQuota(self, user, printer)
928                userpquota.ident = userquotaid
929                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0] or 0)
930                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0] or 0)
931                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
932                if userpquota.SoftLimit is not None :
933                    if userpquota.SoftLimit[0].upper() == "NONE" :
934                        userpquota.SoftLimit = None
935                    else :   
936                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
937                userpquota.HardLimit = fields.get("pykotaHardLimit")
938                if userpquota.HardLimit is not None :
939                    if userpquota.HardLimit[0].upper() == "NONE" :
940                        userpquota.HardLimit = None
941                    elif userpquota.HardLimit is not None :   
942                        userpquota.HardLimit = int(userpquota.HardLimit[0])
943                userpquota.DateLimit = fields.get("pykotaDateLimit")
944                if userpquota.DateLimit is not None :
945                    if userpquota.DateLimit[0].upper() == "NONE" : 
946                        userpquota.DateLimit = None
947                    else :   
948                        userpquota.DateLimit = userpquota.DateLimit[0]
949                userpquota.Exists = 1
950                usersandquotas.append((user, userpquota))
951                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
952        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
953        return usersandquotas
954               
955    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
956        """Returns the list of groups which uses a given printer, along with their quotas."""
957        groupsandquotas = []
958        if self.info["groupquotabase"].lower() == "group" :
959           base = self.info["groupbase"]
960        else :
961           base = self.info["groupquotabase"]
962        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=base)
963        if result :
964            for (groupquotaid, fields) in result :
965                group = self.getGroup(fields.get("pykotaGroupName")[0])
966                grouppquota = self.getGroupPQuota(group, printer)
967                groupsandquotas.append((group, grouppquota))
968        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
969        return groupsandquotas
970       
971    def addPrinter(self, printername) :       
972        """Adds a printer to the quota storage, returns it."""
973        fields = { self.info["printerrdn"] : printername,
974                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
975                   "cn" : printername,
976                   "pykotaPrinterName" : printername,
977                   "pykotaPricePerPage" : "0.0",
978                   "pykotaPricePerJob" : "0.0",
979                 } 
980        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
981        self.doAdd(dn, fields)
982        return self.getPrinter(printername)
983       
984    def addUser(self, user) :       
985        """Adds a user to the quota storage, returns it."""
986        newfields = {
987                       "pykotaUserName" : user.Name,
988                       "pykotaLimitBy" : (user.LimitBy or "quota"),
989                    }   
990                       
991        if user.Email :
992            newfields.update({self.info["usermail"]: user.Email})
993        mustadd = 1
994        if self.info["newuser"].lower() != 'below' :
995            try :
996                (where, action) = [s.strip() for s in self.info["newuser"].split(",")]
997            except ValueError :
998                (where, action) = (self.info["newuser"].strip(), "fail")
999            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["userrdn"], user.Name), None, base=self.info["userbase"])
1000            if result :
1001                (dn, fields) = result[0]
1002                fields["objectClass"].extend(["pykotaAccount", "pykotaAccountBalance"])
1003                fields.update(newfields)
1004                fields.update({ "pykotaBalance" : str(user.AccountBalance or 0.0),
1005                                "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), })   
1006                self.doModify(dn, fields)
1007                mustadd = 0
1008            else :
1009                message = _("Unable to find an existing objectClass %s entry with %s=%s to attach pykotaAccount objectClass") % (where, self.info["userrdn"], user.Name)
1010                if action.lower() == "warn" :   
1011                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
1012                else : # 'fail' or incorrect setting
1013                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
1014               
1015        if mustadd :
1016            if self.info["userbase"] == self.info["balancebase"] :           
1017                fields = { self.info["userrdn"] : user.Name,
1018                           "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
1019                           "cn" : user.Name,
1020                           "pykotaBalance" : str(user.AccountBalance or 0.0),
1021                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
1022                         } 
1023            else :             
1024                fields = { self.info["userrdn"] : user.Name,
1025                           "objectClass" : ["pykotaObject", "pykotaAccount"],
1026                           "cn" : user.Name,
1027                         } 
1028            fields.update(newfields)         
1029            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
1030            self.doAdd(dn, fields)
1031            if self.info["userbase"] != self.info["balancebase"] :           
1032                fields = { self.info["balancerdn"] : user.Name,
1033                           "objectClass" : ["pykotaObject", "pykotaAccountBalance"],
1034                           "cn" : user.Name,
1035                           "pykotaBalance" : str(user.AccountBalance or 0.0),
1036                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
1037                         } 
1038                dn = "%s=%s,%s" % (self.info["balancerdn"], user.Name, self.info["balancebase"])
1039                self.doAdd(dn, fields)
1040           
1041        return self.getUser(user.Name)
1042       
1043    def addGroup(self, group) :       
1044        """Adds a group to the quota storage, returns it."""
1045        newfields = { 
1046                      "pykotaGroupName" : group.Name,
1047                      "pykotaLimitBY" : (group.LimitBy or "quota"),
1048                    } 
1049        mustadd = 1
1050        if self.info["newgroup"].lower() != 'below' :
1051            try :
1052                (where, action) = [s.strip() for s in self.info["newgroup"].split(",")]
1053            except ValueError :
1054                (where, action) = (self.info["newgroup"].strip(), "fail")
1055            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
1056            if result :
1057                (dn, fields) = result[0]
1058                fields["objectClass"].extend(["pykotaGroup"])
1059                fields.update(newfields)
1060                self.doModify(dn, fields)
1061                mustadd = 0
1062            else :
1063                message = _("Unable to find an existing entry to attach pykotaGroup objectclass %s") % group.Name
1064                if action.lower() == "warn" :   
1065                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
1066                else : # 'fail' or incorrect setting
1067                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
1068               
1069        if mustadd :
1070            fields = { self.info["grouprdn"] : group.Name,
1071                       "objectClass" : ["pykotaObject", "pykotaGroup"],
1072                       "cn" : group.Name,
1073                     } 
1074            fields.update(newfields)         
1075            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
1076            self.doAdd(dn, fields)
1077        return self.getGroup(group.Name)
1078       
1079    def addUserToGroup(self, user, group) :   
1080        """Adds an user to a group."""
1081        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
1082            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
1083            if result :
1084                fields = result[0][1]
1085                if not fields.has_key(self.info["groupmembers"]) :
1086                    fields[self.info["groupmembers"]] = []
1087                fields[self.info["groupmembers"]].append(user.Name)
1088                self.doModify(group.ident, fields)
1089                group.Members.append(user)
1090               
1091    def addUserPQuota(self, user, printer) :
1092        """Initializes a user print quota on a printer."""
1093        uuid = self.genUUID()
1094        fields = { "cn" : uuid,
1095                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
1096                   "pykotaUserName" : user.Name,
1097                   "pykotaPrinterName" : printer.Name,
1098                   "pykotaDateLimit" : "None",
1099                   "pykotaPageCounter" : "0",
1100                   "pykotaLifePageCounter" : "0",
1101                 } 
1102        if self.info["userquotabase"].lower() == "user" :
1103            dn = "cn=%s,%s" % (uuid, user.ident)
1104        else :   
1105            dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
1106        self.doAdd(dn, fields)
1107        return self.getUserPQuota(user, printer)
1108       
1109    def addGroupPQuota(self, group, printer) :
1110        """Initializes a group print quota on a printer."""
1111        uuid = self.genUUID()
1112        fields = { "cn" : uuid,
1113                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
1114                   "pykotaGroupName" : group.Name,
1115                   "pykotaPrinterName" : printer.Name,
1116                   "pykotaDateLimit" : "None",
1117                 } 
1118        if self.info["groupquotabase"].lower() == "group" :
1119            dn = "cn=%s,%s" % (uuid, group.ident)
1120        else :   
1121            dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
1122        self.doAdd(dn, fields)
1123        return self.getGroupPQuota(group, printer)
1124       
1125    def writePrinterPrices(self, printer) :   
1126        """Write the printer's prices back into the storage."""
1127        fields = {
1128                   "pykotaPricePerPage" : str(printer.PricePerPage),
1129                   "pykotaPricePerJob" : str(printer.PricePerJob),
1130                 }
1131        self.doModify(printer.ident, fields)
1132       
1133    def writePrinterDescription(self, printer) :   
1134        """Write the printer's description back into the storage."""
1135        fields = {
1136                   "description" : self.userCharsetToDatabase(str(printer.Description)), 
1137                 }
1138        self.doModify(printer.ident, fields)
1139       
1140    def writeUserLimitBy(self, user, limitby) :   
1141        """Sets the user's limiting factor."""
1142        fields = {
1143                   "pykotaLimitBy" : limitby,
1144                 }
1145        self.doModify(user.ident, fields)         
1146       
1147    def writeGroupLimitBy(self, group, limitby) :   
1148        """Sets the group's limiting factor."""
1149        fields = {
1150                   "pykotaLimitBy" : limitby,
1151                 }
1152        self.doModify(group.ident, fields)         
1153       
1154    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
1155        """Sets the date limit permanently for a user print quota."""
1156        fields = {
1157                   "pykotaDateLimit" : datelimit,
1158                 }
1159        return self.doModify(userpquota.ident, fields)
1160           
1161    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
1162        """Sets the date limit permanently for a group print quota."""
1163        fields = {
1164                   "pykotaDateLimit" : datelimit,
1165                 }
1166        return self.doModify(grouppquota.ident, fields)
1167       
1168    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
1169        """Increase page counters for a user print quota."""
1170        fields = {
1171                   "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
1172                   "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
1173                 }
1174        return self.doModify(userpquota.ident, fields)         
1175       
1176    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
1177        """Sets the new page counters permanently for a user print quota."""
1178        fields = {
1179                   "pykotaPageCounter" : str(newpagecounter),
1180                   "pykotaLifePageCounter" : str(newlifepagecounter),
1181                   "pykotaDateLimit" : None,
1182                 } 
1183        return self.doModify(userpquota.ident, fields)         
1184       
1185    def decreaseUserAccountBalance(self, user, amount) :   
1186        """Decreases user's account balance from an amount."""
1187        fields = {
1188                   "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float },
1189                 }
1190        return self.doModify(user.idbalance, fields, flushcache=1)         
1191       
1192    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
1193        """Sets the new account balance and eventually new lifetime paid."""
1194        fields = {
1195                   "pykotaBalance" : str(newbalance),
1196                 }
1197        if newlifetimepaid is not None :
1198            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
1199        return self.doModify(user.idbalance, fields)         
1200           
1201    def writeNewPayment(self, user, amount) :       
1202        """Adds a new payment to the payments history."""
1203        payments = []
1204        for payment in user.Payments :
1205            payments.append("%s # %s" % (payment[0], str(payment[1])))
1206        payments.append("%s # %s" % (str(DateTime.now()), str(amount)))
1207        fields = {
1208                   "pykotaPayments" : payments,
1209                 }
1210        return self.doModify(user.idbalance, fields)         
1211       
1212    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
1213        """Sets the last job's size permanently."""
1214        fields = {
1215                   "pykotaJobSize" : str(jobsize),
1216                   "pykotaJobPrice" : str(jobprice),
1217                 }
1218        self.doModify(lastjob.ident, fields)         
1219       
1220    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None) :
1221        """Adds a job in a printer's history."""
1222        if (not self.disablehistory) or (not printer.LastJob.Exists) :
1223            uuid = self.genUUID()
1224            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
1225        else :   
1226            uuid = printer.LastJob.ident[3:].split(",")[0]
1227            dn = printer.LastJob.ident
1228        if self.privacy :   
1229            # For legal reasons, we want to hide the title, filename and options
1230            title = filename = options = "Hidden because of privacy concerns"
1231        fields = {
1232                   "objectClass" : ["pykotaObject", "pykotaJob"],
1233                   "cn" : uuid,
1234                   "pykotaUserName" : user.Name,
1235                   "pykotaPrinterName" : printer.Name,
1236                   "pykotaJobId" : jobid,
1237                   "pykotaPrinterPageCounter" : str(pagecounter),
1238                   "pykotaAction" : action,
1239                   "pykotaFileName" : ((filename is None) and "None") or self.userCharsetToDatabase(filename), 
1240                   "pykotaTitle" : ((title is None) and "None") or self.userCharsetToDatabase(title), 
1241                   "pykotaCopies" : str(copies), 
1242                   "pykotaOptions" : ((options is None) and "None") or self.userCharsetToDatabase(options), 
1243                   "pykotaHostName" : str(clienthost), 
1244                   "pykotaJobSizeBytes" : str(jobsizebytes),
1245                 }
1246        if (not self.disablehistory) or (not printer.LastJob.Exists) :
1247            if jobsize is not None :         
1248                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
1249            self.doAdd(dn, fields)
1250        else :   
1251            # here we explicitly want to reset jobsize to 'None' if needed
1252            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
1253            self.doModify(dn, fields)
1254           
1255        if printer.LastJob.Exists :
1256            fields = {
1257                       "pykotaLastJobIdent" : uuid,
1258                     }
1259            self.doModify(printer.LastJob.lastjobident, fields)         
1260        else :   
1261            lastjuuid = self.genUUID()
1262            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
1263            fields = {
1264                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
1265                       "cn" : lastjuuid,
1266                       "pykotaPrinterName" : printer.Name,
1267                       "pykotaLastJobIdent" : uuid,
1268                     } 
1269            self.doAdd(lastjdn, fields)         
1270           
1271    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
1272        """Sets soft and hard limits for a user quota."""
1273        fields = { 
1274                   "pykotaSoftLimit" : str(softlimit),
1275                   "pykotaHardLimit" : str(hardlimit),
1276                   "pykotaDateLimit" : "None",
1277                 }
1278        self.doModify(userpquota.ident, fields)
1279       
1280    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
1281        """Sets soft and hard limits for a group quota on a specific printer."""
1282        fields = { 
1283                   "pykotaSoftLimit" : str(softlimit),
1284                   "pykotaHardLimit" : str(hardlimit),
1285                   "pykotaDateLimit" : "None",
1286                 }
1287        self.doModify(grouppquota.ident, fields)
1288           
1289    def writePrinterToGroup(self, pgroup, printer) :
1290        """Puts a printer into a printer group."""
1291        if printer.ident not in pgroup.uniqueMember :
1292            pgroup.uniqueMember.append(printer.ident)
1293            fields = {
1294                       "uniqueMember" : pgroup.uniqueMember
1295                     } 
1296            self.doModify(pgroup.ident, fields)         
1297           
1298    def removePrinterFromGroup(self, pgroup, printer) :
1299        """Removes a printer from a printer group."""
1300        try :
1301            pgroup.uniqueMember.remove(printer.ident)
1302        except ValueError :   
1303            pass
1304        else :   
1305            fields = {
1306                       "uniqueMember" : pgroup.uniqueMember,
1307                     } 
1308            self.doModify(pgroup.ident, fields)         
1309           
1310    def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) :   
1311        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
1312        precond = "(objectClass=pykotaJob)"
1313        where = []
1314        if (user is not None) and user.Exists :
1315            where.append("(pykotaUserName=%s)" % user.Name)
1316        if (printer is not None) and printer.Exists :
1317            where.append("(pykotaPrinterName=%s)" % printer.Name)
1318        if hostname is not None :
1319            where.append("(pykotaHostName=%s)" % hostname)
1320        if where :   
1321            where = "(&%s)" % "".join([precond] + where)
1322        else :   
1323            where = precond
1324        jobs = []   
1325        result = self.doSearch(where, fields=["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaAction", "pykotaJobSize", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base=self.info["jobbase"])
1326        if result :
1327            for (ident, fields) in result :
1328                job = StorageJob(self)
1329                job.ident = ident
1330                job.JobId = fields.get("pykotaJobId")[0]
1331                job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
1332                try :
1333                    job.JobSize = int(fields.get("pykotaJobSize", [0])[0])
1334                except ValueError :   
1335                    job.JobSize = None
1336                try :   
1337                    job.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
1338                except ValueError :
1339                    job.JobPrice = None
1340                job.JobAction = fields.get("pykotaAction", [""])[0]
1341                job.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
1342                job.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
1343                job.JobCopies = int(fields.get("pykotaCopies", [0])[0])
1344                job.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
1345                job.JobHostName = fields.get("pykotaHostName", [""])[0]
1346                job.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
1347                date = fields.get("createTimestamp", ["19700101000000"])[0]
1348                year = int(date[:4])
1349                month = int(date[4:6])
1350                day = int(date[6:8])
1351                hour = int(date[8:10])
1352                minute = int(date[10:12])
1353                second = int(date[12:14])
1354                job.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
1355                if (datelimit is None) or (job.JobDate <= datelimit) :
1356                    job.UserName = fields.get("pykotaUserName")[0]
1357                    job.PrinterName = fields.get("pykotaPrinterName")[0]
1358                    job.Exists = 1
1359                    jobs.append(job)
1360            jobs.sort(lambda x, y : cmp(y.JobDate, x.JobDate))       
1361            if limit :   
1362                jobs = jobs[:int(limit)]
1363        return jobs
1364       
1365    def deleteUser(self, user) :   
1366        """Completely deletes an user from the Quota Storage."""
1367        todelete = []   
1368        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
1369        for (ident, fields) in result :
1370            todelete.append(ident)
1371        if self.info["userquotabase"].lower() == "user" :
1372            base = self.info["userbase"]
1373        else :
1374            base = self.info["userquotabase"]
1375        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaPrinterName", "pykotaUserName"], base=base)
1376        for (ident, fields) in result :
1377            # ensure the user print quota entry will be deleted
1378            todelete.append(ident)
1379           
1380            # if last job of current printer was printed by the user
1381            # to delete, we also need to delete the printer's last job entry.
1382            printername = fields["pykotaPrinterName"][0]
1383            printer = self.getPrinter(printername)
1384            if printer.LastJob.UserName == user.Name :
1385                todelete.append(printer.LastJob.lastjobident)
1386           
1387        for ident in todelete :   
1388            self.doDelete(ident)
1389           
1390        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
1391        if result :
1392            fields = result[0][1]
1393            for k in fields.keys() :
1394                if k.startswith("pykota") :
1395                    del fields[k]
1396                elif k.lower() == "objectclass" :   
1397                    todelete = []
1398                    for i in range(len(fields[k])) :
1399                        if fields[k][i].startswith("pykota") : 
1400                            todelete.append(i)
1401                    todelete.sort()       
1402                    todelete.reverse()
1403                    for i in todelete :
1404                        del fields[k][i]
1405            if fields.get("objectClass") or fields.get("objectclass") :
1406                self.doModify(user.ident, fields, ignoreold=0)       
1407            else :   
1408                self.doDelete(user.ident)
1409        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
1410        for (ident, fields) in result :
1411            self.doDelete(ident)
1412       
1413    def deleteGroup(self, group) :   
1414        """Completely deletes a group from the Quota Storage."""
1415        if self.info["groupquotabase"].lower() == "group" :
1416            base = self.info["groupbase"]
1417        else :
1418            base = self.info["groupquotabase"]
1419        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=base)
1420        for (ident, fields) in result :
1421            self.doDelete(ident)
1422        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
1423        if result :
1424            fields = result[0][1]
1425            for k in fields.keys() :
1426                if k.startswith("pykota") :
1427                    del fields[k]
1428                elif k.lower() == "objectclass" :   
1429                    todelete = []
1430                    for i in range(len(fields[k])) :
1431                        if fields[k][i].startswith("pykota") : 
1432                            todelete.append(i)
1433                    todelete.sort()       
1434                    todelete.reverse()
1435                    for i in todelete :
1436                        del fields[k][i]
1437            if fields.get("objectClass") or fields.get("objectclass") :
1438                self.doModify(group.ident, fields, ignoreold=0)       
1439            else :   
1440                self.doDelete(group.ident)
1441               
1442    def deletePrinter(self, printer) :   
1443        """Completely deletes an user from the Quota Storage."""
1444        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["lastjobbase"])
1445        for (ident, fields) in result :
1446            self.doDelete(ident)
1447        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["jobbase"])
1448        for (ident, fields) in result :
1449            self.doDelete(ident)
1450        if self.info["groupquotabase"].lower() == "group" :
1451            base = self.info["groupbase"]
1452        else :
1453            base = self.info["groupquotabase"]
1454        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, base=base)
1455        for (ident, fields) in result :
1456            self.doDelete(ident)
1457        if self.info["userquotabase"].lower() == "user" :
1458            base = self.info["userbase"]
1459        else :
1460            base = self.info["userquotabase"]
1461        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, base=base)
1462        for (ident, fields) in result :
1463            self.doDelete(ident)
1464        for parent in self.getParentPrinters(printer) : 
1465            try :
1466                parent.uniqueMember.remove(printer.ident)
1467            except ValueError :   
1468                pass
1469            else :   
1470                fields = {
1471                           "uniqueMember" : parent.uniqueMember,
1472                         } 
1473                self.doModify(parent.ident, fields)         
1474        self.doDelete(printer.ident)   
1475       
1476    def extractPrinters(self, extractonly={}) :
1477        """Extracts all printer records."""
1478        pname = extractonly.get("printername")
1479        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1480        if entries :
1481            result = [ ("dn", "printername", "priceperpage", "priceperjob", "description") ]
1482            for entry in entries :
1483                result.append((entry.ident, entry.Name, entry.PricePerPage, entry.PricePerJob, entry.Description))
1484            return result 
1485       
1486    def extractUsers(self, extractonly={}) :
1487        """Extracts all user records."""
1488        uname = extractonly.get("username")
1489        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1490        if entries :
1491            result = [ ("dn", "username", "balance", "lifetimepaid", "limitby", "email") ]
1492            for entry in entries :
1493                result.append((entry.ident, entry.Name, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy, entry.Email))
1494            return result 
1495       
1496    def extractGroups(self, extractonly={}) :
1497        """Extracts all group records."""
1498        gname = extractonly.get("groupname")
1499        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1500        if entries :
1501            result = [ ("dn", "groupname", "limitby", "balance", "lifetimepaid") ]
1502            for entry in entries :
1503                result.append((entry.ident, entry.Name, entry.LimitBy, entry.AccountBalance, entry.LifeTimePaid))
1504            return result 
1505       
1506    def extractPayments(self, extractonly={}) :
1507        """Extracts all payment records."""
1508        uname = extractonly.get("username")
1509        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1510        if entries :
1511            result = [ ("username", "amount", "date") ]
1512            for entry in entries :
1513                for (date, amount) in entry.Payments :
1514                    result.append((entry.Name, amount, date))
1515            return result       
1516       
1517    def extractUpquotas(self, extractonly={}) :
1518        """Extracts all userpquota records."""
1519        pname = extractonly.get("printername")
1520        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1521        if entries :
1522            result = [ ("username", "printername", "dn", "userdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1523            uname = extractonly.get("username")
1524            for entry in entries :
1525                for (user, userpquota) in self.getPrinterUsersAndQuotas(entry, names=[uname or "*"]) :
1526                    result.append((user.Name, entry.Name, userpquota.ident, user.ident, entry.ident, userpquota.LifePageCounter, userpquota.PageCounter, userpquota.SoftLimit, userpquota.HardLimit, userpquota.DateLimit))
1527            return result
1528       
1529    def extractGpquotas(self, extractonly={}) :
1530        """Extracts all grouppquota records."""
1531        pname = extractonly.get("printername")
1532        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1533        if entries :
1534            result = [ ("groupname", "printername", "dn", "groupdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1535            gname = extractonly.get("groupname")
1536            for entry in entries :
1537                for (group, grouppquota) in self.getPrinterGroupsAndQuotas(entry) :
1538                    if (gname is None) or (group.Name == gname) :
1539                        result.append((group.Name, entry.Name, grouppquota.ident, group.ident, entry.ident, grouppquota.LifePageCounter, grouppquota.PageCounter, grouppquota.SoftLimit, grouppquota.HardLimit, grouppquota.DateLimit))
1540            return result
1541       
1542    def extractUmembers(self, extractonly={}) :
1543        """Extracts all user groups members."""
1544        gname = extractonly.get("groupname")
1545        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1546        if entries :
1547            result = [ ("groupname", "username", "groupdn", "userdn") ]
1548            uname = extractonly.get("username")
1549            for entry in entries :
1550                for member in entry.Members :
1551                    if (uname is None) or (member.Name == uname) :
1552                        result.append((entry.Name, member.Name, entry.ident, member.ident))
1553            return result       
1554               
1555    def extractPmembers(self, extractonly={}) :
1556        """Extracts all printer groups members."""
1557        pname = extractonly.get("printername")
1558        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1559        if entries :
1560            result = [ ("pgroupname", "printername", "pgroupdn", "printerdn") ]
1561            pgname = extractonly.get("pgroupname")
1562            for entry in entries :
1563                for parent in self.getParentPrinters(entry) :
1564                    if (pgname is None) or (parent.Name == pgname) :
1565                        result.append((parent.Name, entry.Name, parent.ident, entry.ident))
1566            return result       
1567       
1568    def extractHistory(self, extractonly={}) :
1569        """Extracts all jobhistory records."""
1570        uname = extractonly.get("username")
1571        if uname :
1572            user = self.getUser(uname)
1573        else :   
1574            user = None
1575        pname = extractonly.get("printername")
1576        if pname :
1577            printer = self.getPrinter(pname)
1578        else :   
1579            printer = None
1580        entries = self.retrieveHistory(user, printer, limit=None)
1581        if entries :
1582            result = [ ("username", "printername", "dn", "jobid", "pagecounter", "jobsize", "action", "jobdate", "filename", "title", "copies", "options", "jobprice", "hostname", "jobsizebytes") ] 
1583            for entry in entries :
1584                result.append((entry.UserName, entry.PrinterName, entry.ident, entry.JobId, entry.PrinterPageCounter, entry.JobSize, entry.JobAction, entry.JobDate, entry.JobFileName, entry.JobTitle, entry.JobCopies, entry.JobOptions, entry.JobPrice, entry.JobHostName, entry.JobSizeBytes)) 
1585            return result   
Note: See TracBrowser for help on using the browser.