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

Revision 1995, 74.1 kB (checked in by jalet, 19 years ago)

Normalized fields names in dumpykota's output so that an LDAP or PostgreSQL
dump is parseable the same way.

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