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

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

typo

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