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

Revision 2030, 75.4 kB (checked in by jalet, 19 years ago)

Big bug fix wrt the datelimit attribute

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