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

Revision 2039, 75.5 kB (checked in by jalet, 19 years ago)

Fixed some ldap filters

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